update ListFragment when Activity finishes

て烟熏妆下的殇ゞ 提交于 2019-12-09 19:00:32

问题


I have create a listfragment and a button which looks like as follows ( Image on the left )

whenever i click on a ADD button a new Activity opens up and inside that user write something and click on DONE , the activty finishes and return to the ListFragment , but after click over DONE how would i update the ListFragment with new values. i mean where can i write notifyDataSetChanged.

Note: when i click on DONE , the data will get store in the database , and when the ListFragment loads , it will fetch the data inside it

i am using android support compatibility library


回答1:


You should be using StartActivityForResult().

//place in shared location
int MYACTIVITY_REQUEST_CODE = 101

//start Activity
Intent intent = new Intent(getActivity(), MyActivity.class);
startActivityForResult(intent, MYACTIVITY_REQUEST_CODE);

You should then override onActivityResult() in the fragment. The method will be called after the activity is closed.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if ((requestCode == MYACTIVITY_REQUEST_CODE) && (resultCode == Activity.RESULT_OK))
        adapter.notifyDataSetChanged()
}

The result Code is set in the activity before it is finished via:

setResult(Activity.RESULT_OK)

Using the requestCode and resultCode are really optional. You only need to use the requestCode if you are launching more than one activity from the fragment. You only need to use the resultCode if you need to return different results from the activity.




回答2:


Alternatively, you can call self.setListAdapter() again in onActivityResult() as well. It worked fine for me.



来源:https://stackoverflow.com/questions/9843454/update-listfragment-when-activity-finishes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!