How to update ListView after onResume from other activity?

后端 未结 1 808
花落未央
花落未央 2021-01-15 13:08

Im trying to create an application that enable user to create event, then invite participant. So when user go to \"add participant\" page, after entering all information, im

1条回答
  •  清酒与你
    2021-01-15 13:30

    First, your adapter.notifyDataSetChanged() right before setListAdapter(adapter); in the onCreate() method is useless because the list isn't aware of the data unless you call setListAdapter().

    So here is the easy way in you class EventPage :

    @Override
    protected void onResume()
    {
        super.onResume();
    
        if (getListView() != null)
        {
            updateData();
        }
    }
    
    private void updateData()
    {
        SimpleAdapter adapter = new SimpleAdapter(EventPage.this, 
                                                  controller.getAllFriends(queryValues), 
                                                  R.layout.view_friend_entry, 
                                                  new String[] {"friendId", "friendName" },
                                                  new int[] { R.id.friendId, R.id.friendName });
        setListAdapter(adapter);
    }
    

    So here, we basically refresh the data every time onResume() is called.

    If you want to do it only after adding a new item, then you must use onActivityResult() instead on onResume():

    private static final int ADD_PARTICIPANT = 123;// the unique code to start the add participant activity 
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == ADD_PARTICIPANT && resultCode == Activity.RESULT_OK)
        {
            updateData();
        }
    }
    
    private void updateData()
    {
        SimpleAdapter adapter = new SimpleAdapter(EventPage.this, 
                                                  controller.getAllFriends(queryValues), 
                                                  R.layout.view_friend_entry, 
                                                  new String[] {"friendId", "friendName" },
                                                  new int[] { R.id.friendId, R.id.friendName });
        setListAdapter(adapter);
    }
    

    Now, simply replace in your onCreate() method the startActivity by startActivityForResult(objIndent, ADD_PARTICIPANT);

    Lastly, in your AddParticipant activity, add setResult(Activity.RESULT_OK); just before onFinish();

    0 讨论(0)
提交回复
热议问题