Jose Bernhardt Jose Bernhardt - 3 months ago 12
Java Question

Updating list view periodically

I currently have a

List View
that takes data from an
ArrayList
that gets update every certain amount of time in the
MainActivity
. I want to update the List View every certain amount of time, let say 2 seconds. The problem is that I have this Adapter on a fragment and if I call the
notifyDataSetChanged();
from the Adapter, the View only gets update if I switch between the
MainActivity
and the
fragment
. I want that this List view refreshes every 2 seconds while I'm having the fragment in View. I have tried to run a
TimerTask
on the Adapter class, but I get an exception:


android.view.ViewRootImpl$CalledFromWrongThreadException: Only the
original thread that created a view hierarchy can touch its views.


I guess you can only update the view from the MainActivity that has the fragment attached.

This how I was running the timer:

public void setTimer(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}

public class RemindTask extends TimerTask {

//Refreshing list view
public void run() {

notifyDataSetChanged();
timer.cancel();
setTimer(2);
}
}


Would it be safe to create an instance of the adapter on the MainActivity and call
notifyDataSetChanged()
every certain amount of time?

Answer

You can Create one broadcast receiver in Fragment. with certain action name. Lets say "refresh_data". Then send this broadcast from MainActivity. Example Code.

 public class MyFragment extends Fragment{
      private BroadcastReceiver  refreshData = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
            myAdapter.notifyDataSetChanged();
      }
    };  
@Override
    public void onResume() {
        super.onResume();
    LocalBroadcastManager.getInstance(context).registerReceiver(refreshData,
    new IntentFilter("refresh_Data"));  
    }
    @Override
    public void onPause() {
        LocalBroadcastManager.getInstance(context).unregisterReceiver(refreshData);
       super.onPause();
    }
    }

In Activity call following method whenever your list is updated

Intent intent = new Intent("refresh_data");   
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Comments