'How to refresh a fragment before going back to it from an activity?

Here's my code for going to an activity from a fragment

Intent intent = new Intent(getActivity(), Product_info.class);
intent.putExtra("product_key", postIDs.get(position));
startActivity(intent);

And here's my code for going back to that fragment from that activity

back_button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        finish();
    }
});

For context, I am changing some details displayed on the fragment on the activity. I have tried to use intent instead of finish but it doesn't work as intended. Is there a way to refresh the fragment before going back to it?



Solution 1:[1]

If you want to get some results from activity and refresh status in fragement then use start activity for result. and before finishing your activity set result ok or cancel and check for result in fragment

example

 ActivityResultLauncher<Intent> launchSomeActivity = registerForActivityResult(
     new ActivityResultContracts.StartActivityForResult(),
     new ActivityResultCallback<ActivityResult>() {
              @Override
              public void onActivityResult(ActivityResult result) {
                   if (result.getResultCode() == Activity.RESULT_OK) {
                         Intent data = result.getData();
                         // update your fragment here
                    }
               }
      });

      public void openYourActivity() {
            Intent intent = new Intent(this, SomeActivity.class);
            launchSomeActivity.launch(intent);
      }

once you have done some action in activity then you need to set result to OK or cancel before finishing activity

if(some condition) {
   //return data if you want to resurn to calling activity or fragment 
   Intent intent = new Intent()
   intent.putExtra("data", data)

   setResult(Activity.RESULT_OK, intent)
}

finish()


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 imran khan