I am trying to change the view from one class when the data changes in another class using notifyDataSetChanged()
on custom adapter.
Class FragmentOne
starts thread where listItems
are added.
Then I am using class FragmentTwo
and getting those listItems
and updating my view.
My code---
Class FragmentOne
static ArrayList<String> listItems = null;
private class MonitorLogThread extends Thread
{
BufferedReader br;
@Override
public void run() {
while(((line=br.readLine()) != null) && !this.isInterrupted()){
listItems.add(line);
}
}
Class FragmentTwo
private BBLogListAdapter mBBLogListAdapter;
ArrayList<String> receiptlist;
@Override
protected void onResume() {
super.onResume();
if(receiptlist == null)
receiptlist = new ArrayList<String>();
else
receiptlist.clear();
// Initializes list view adapter.
mBBLogListAdapter = new BBLogListAdapter();
setListAdapter(mBBLogListAdapter);
mBBLogListAdapter.updateReceiptsList(FragmentOne.listItems);
mBBLogListAdapter.notifyDataSetChanged();
}
// Custom Adapter
private class BBLogListAdapter extends BaseAdapter {
//Code to set view dynamically according to data in adapter
public void updateReceiptsList(ArrayList<String> newlist) {
receiptlist.clear();
receiptlist.addAll(newlist);
}
//Some more code..
}
}
So, currently I am using method updateReceiptsList in the method onResume() to update the contents. This only updates when we resume the activity.
But I want to auto refresh the contents while in this activity according to data change from another activity.
Grab a hold of your adapter object and create a static method in "FragmentTwo",
public static void notifyDataChanged(){
if(mBBLogListAdapter != null){
mBBLogListAdapter.updateReceiptsList(FragmentOne.listItems);
mBBLogListAdapter.notifyDataSetChanged();
}
}
Whenever your data changes in your thread call this static method.
static ArrayList<String> listItems = null;
private class MonitorLogThread extends Thread
{
BufferedReader br;
@Override
public void run() {
while(((line=br.readLine()) != null) && !this.isInterrupted()){
listItems.add(line);
FragmentTwo.notifyDataChanged();
}
}
Note that, you need to use the same adapter object that you used to setAdapter in FragmentTwo's onResume
setListAdapter(mBBLogListAdapter);
PS: A cleaner alternative would be to use a listener on "FragmentTwo" that listens to any data changes on "FragmentOne". See here for implementation details - http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Hope this helps.