Best Practise? Pass parameter between activities

Viewed 288

The best way to pass parameter between activites is to use the putExtra() method. Passing an object is possible by putParcelable(). But not all objects are parcelable. If you want to pass a not parcelable object how could you do this?

I have solved this by making a static object-variable in the target activity and fill this variable in the calling activity. Is this a good possibility or shouldn't I do this. If yes, why? Could this cause any problems?

Example:

MainActivity

class FirstActivity extends AppCompatActivity {

  MyOwnNotParcelableObject mObject;

  public void openNextActivity() {
    final Intent intent = new Intent(this, SecondActivity.class);
    SecondActivity.mObject = mObject;  //<--Fills the static variable
    startActivity(intent);
  }
}

SecondActivity

class SecondActivity extends AppCompatActivity {

  static MyOwnNotParcelableObject mObject;

}
3 Answers

If you want to pass a not parcelable object how could you do this?

Use ViewModel: https://developer.android.com/topic/libraries/architecture/viewmodel

for sharing primitive data use shared-preference and for complex data/non Parcelable data use ViewModel.

Extending ViewModel class has many benefits :

  • you don’t need to worry about UI data holder lifecycle. ViewModel will be created automatically by a factory and you don’t need to handle creating it and destroying on your own
  • data will be always updated — you’ll get the same data after phone rotation as it was before. Thanks to this you don’t need to pass manually data to the new activity or make a second call to the database. It’s all done for you!
  • data will wait for you. If you’ll make an API call, you’ll rotate the phone and the result will be delivered before activity will be recreated, you’re sure the data will be stored in ViewModel and you can get it immediately after activity recreation

Using static objects is not preferable. You can save your data in shared preference instead and retrieve it in some other activity.

@ANMOL SRIVASTAVA I am sorry to contradict you but this at the moment can not happen in the activities.

What you say is right in the fragment, as the viewmodel instance will be linked to the context. If we insert a ViewModel from activity instance A, I will not have the same data in activity B, unless I use the factory that creates a single instance copy. The probelam is also here below. How do I manage the oncleared of the viewmodel?

This is a good question. So, I suggest you go to use the viewmodel only between an activity and its fragments. Therefore 1 activity can possess N fragment linked by N viewmodel of instance of the parent activity. To pass data between activities, pass an id if the object is saved in the database and retrieve it from the ViewModel. While if it is not saved in the Database, save a temporary object somewhere but not in the shared! It slow down UI

Related