Search code examples
androidandroid-listviewandroid-fragmentsandroid-listfragment

update ListFragment when Activity finishes


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.

enter image description here

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


Solution

  • 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.