Search code examples
androidandroid-fragmentsandroid-intentandroid-activity

How to trigger a reload on activity close?


So I have an Activity containing a ViewPager, which contains a few Fragments, including one with a RecyclerView. You can click one of the items on the RecyclerView to edit all its details, which is done by launching a second Activity with editable fields specific to that item.

However let's say I change the name of the item. Now I press Save or the Back Button or whatever to close this Activity and go back to the first Activity. Since the name might be different now, the RecyclerView should also have the item's name updated.

But how do I detect this event? How do I basically do "when closing the second Activity, notify that the item has changed in the RecyclerView in the Fragment in the ViewPager of the first Activity"?

Can I use onActivityResult? If I am calling the second Activity from a Fragment using startActivityForResult, can I define onActivityResult in that same Fragment and then somehow use the Intent data to see, "okay, I need to refresh this position of the RecyclerView"?


Solution

  • Can I use onActivityResult?

    Yes. Here's how you can use it:

    1. When an item is clicked in your RecyclerView, you keep track of the adapter position of the clicked item.
    2. You start the second activity for result from within your fragment.

      // adapterPosition is the position of the clicked item
      Intent intent = new Intent(getActivity(), SecondActivity.class);
      intent.putExtras("adapter_position", adapterPosition);
      startActivityForResult(intent, 1); 
      
    3. In your SecondActivity set the adapterPosition as part of the result Intent. Handle SecondActivity result in your fragment.

    In SecondActivity

        // adapterPosition is what you received from your fragment
        Intent result = new Intent();
        result.putExtra("adapter_position", adapterPosition);
        // put other stuff you might need
        setResult(Activity.RESULT_OK, result);
        finish();
    

    In fragment

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                int adapterPosition = data.getIntExtra("adapter_position");
                // Update your RecyclerAdapter data. 
                // You will need to define this method in your RecyclerAdapter
    
                yourAdapter.notifyItemChanged(adapterPosition);
            }
            else {
                // Some error/cancel handling
            }
        }
    }