Search code examples
androidlistviewonresume

update List View onResume (can't get view)


I need to update my List View in onResume function, them problem is that my view is null there:

mList = (ListView) v.findViewById(R.id.list); //v is null

what should I do? how can I get my list view to update it?

Here is part of onCreate function:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View v = findViewById(R.id.large_screen_layout);
    mList = (ListView) v.findViewById(R.id.list);
}

Here is the on resume function:

@Override
protected void onResume() 
{
super.onResume();

mMyBroadcastReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent)
{
// Here you can refresh your listview or other UI
String textmessage = intent.getStringExtra("Message");
Toast.makeText(getApplicationContext(), textmessage, Toast.LENGTH_LONG).show();
item = new RowItem(R.drawable.alert_icon, "text1", "text2");
rowItems.add(item);
adapter = new CustomListViewAdapter(getApplicationContext(),R.id.list,rowItems);
adapter.notifyDataSetChanged();
//now either, i need to use view (v) or mList(List View):
mList = (ListView) v.findViewById(R.id.list); //v and mList are NULL here
mList.setAdapter(adapter); 
}
};
try {
LocalBroadcastManager.getInstance(this).registerReceiver(mMyBroadcastReceiver,new     IntentFilter("your_action"));   
} catch (Exception e)
{
            // TODO: handle exception
            e.printStackTrace();
}
}

any idea how can I update it?

Thank you!

Eran.


Solution

  • @Override
    protected void onResume() 
    {
    super.onResume();
    
    mMyBroadcastReceiver = new BroadcastReceiver() {
    
    @Override
    public void onReceive(Context context, Intent intent)
    {
    // Here you can refresh your listview or other UI
    String textmessage = intent.getStringExtra("Message");
    Toast.makeText(getApplicationContext(), textmessage, Toast.LENGTH_LONG).show();
    item = new RowItem(R.drawable.alert_icon, "text1", "text2");
    rowItems.add(item);
    adapter = new CustomListViewAdapter(getApplicationContext(),R.id.list,rowItems);
    adapter.notifyDataSetChanged();
    //now either, i need to use view (v) or mList(List View):
    
    // need to find V
    View v = findViewById(R.id.large_screen_layout);
    
    mList = (ListView) v.findViewById(R.id.list); //v and mList are NULL here
    mList.setAdapter(adapter); 
    
    }
    };
    try {
    LocalBroadcastManager.getInstance(this).registerReceiver(mMyBroadcastReceiver,new     IntentFilter("your_action"));   
    } catch (Exception e)
    {
                // TODO: handle exception
                e.printStackTrace();
    }
    }
    

    Also be sure to deregister your broadcast receiver in onPause or it may receive notifications in unexpected ways..