Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best-practice: Update ArrayAdapter continuously

I have a Service which fetches some data from the web and updates a List which is "stored" in the Application.

Thus, i can access it from the main activity and use it for my ArrayAdapter.

When I update the data, the referenced item from the list is changed.

My Question is, how is the best practice to update the data in the Adapter in the main activity?

I have two solutions in mind, but I dont know if they are correct that way. Additional to that, I would like to implement a version which is not using much battery!

First: Thread which is called every second, updating the Adapter with notifyDataSetChanged():

private void startListUpdateThread()  
{
    Thread ListManageThread = new Thread() {
        LinkItem listItem;
        public void run() {
            Log.d("DL", "List Update - start");
            while(true)
            {   
                runOnUiThread(UpdateGUIList);

                try {
                    Thread.sleep(1000); //5Sekunden!
                } 
                catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.e("DL", "ERROR: InterruptedException - " + e.getMessage());
                }
            }
        }
    };
    ListManageThread.start();  
}

private Runnable UpdateGUIList = new Runnable() {

    @Override
    public void run() {
        mFileAdapter.notifyDataSetChanged();
    }
};    

Second: Using a delayed Handler post private final Handler handler = new Handler();

private void startListUpdate()
{
    handler.removeCallbacks(UpdateListUI);
    handler.postDelayed(UpdateListUI, 1000); // 1 second   

}

private Runnable UpdateListUI = new Runnable() {
    public void run() { 
        //Remove Elements first
        removeDeletedItemsFromList();

        //Update Adapter
        mFileAdapter.notifyDataSetChanged();

        handler.postDelayed(this, 1500); // 1,5 seconds
    }
};  

So, whats the best way to do it? Perhaps there is also an other Way to do it, but of which I haven`t thought of before!

like image 661
Webchen Avatar asked Nov 13 '22 11:11

Webchen


1 Answers

Instead of using the handler you will use the Async task. Though handler works here but it's JAVA concept and Async Task is Android.

And you can update the list view by using the : mFileAdapter.notifyDataSetChanged(); only it's correct.

like image 58
mayur rahatekar Avatar answered Nov 16 '22 03:11

mayur rahatekar