-2

What is the best way to pass data from an Activity to fragment, but the fragment is hosted by another activity.

Elaborating: Activity A hosts Fragment A (content in activity A) <== Activity B

I have already achieved this, but apparently, my way of doing it has caused some memory leak.

An example would be to refresh a RecyclerView contained in a fragment when an activity is closed, but I do not want to put it in the onResume.

interface contained in the activity(is not the host)

public class Activity extends AppCompatActivity{
    public static OnlistenClose delegate;
    public interface OnlistenClose {
        void refreshList();
    }
}

//fragment that implements the interface

public class FragmentB extends Fragment implements Activity.OnlistenClose{

       Activity.delegate = this;

       @Override
       public void refreshList(){
          //my code
       }
}

Using square/leakcanary indicates there are leaks.

Nilesh Singh
  • 1,750
  • 1
  • 18
  • 30
kevinzdzul
  • 1
  • 1
  • 3

2 Answers2

1

What is the best way to pass data from an Activity to fragment, but the fragment is hosted by another activity.

Ultimately, you are passing data from one activity to another. If the data is stored permanently in a database or file, then the receiving activity should just read the data after the first one has updated it.

On the other hand, if you are passing data that only needs to be available in memory, then you can pass the data with an Intent.

As you have seen, keeping a reference to one activity in another activity causes memory leaks. The callback method which you are attempting to use is only valid for the activity which owns the fragment, not for a second activity. Instead, you should honor the activity lifecycle and use Intents for communication as appropriate.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

There is no "best practice" for a general question or even a specific circumstance.

Standard ways of passing data:

  • Intents
  • Storage
    • Shared Preferences
    • Internal Storage
    • External Storage
    • SQLite Databases
    • Network Connection
  • Static class (no link necessary)
  • Etc, etc

There are many ways to accomplish a task as there are ways to describe that task in a sentence.

  • I finished my work.
  • I completed my task.
  • It's published in the Play Store.
  • I'm done.
  • I have nothing to do.
Sam
  • 86,580
  • 20
  • 181
  • 179