Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice: passing objects between Android activities

I was wondering what the best practice is to pass objects between activies? My logged out user is on a content item and should be able to get back to this item after the login process. Therefore I need to pass the content id between these activities

I see 2 basic options:

  1. Pass the content-id in the intent as URI (intent.putExtra()) and pass them between activities
  2. Save the content-id to the local storage and load it again after login

Are there any other options and best practices?

like image 690
sonix Avatar asked Jul 29 '14 15:07

sonix


People also ask

What way is used to pass data between activities in Android?

We can send the data using putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.

Can we pass object through Intent in Android?

One way to pass objects in Intents is for the object's class to implement Serializable. This interface doesn't require you to implement any methods; simply adding implements Serializable should be enough. To get the object back from the Intent, just call intent.


1 Answers

i would suggest using SharedPreferences which is like the option 2. which allows your to get the content-id(or string or json object) after the app is closed. you can also encrypt the content-id before put it in sharedPreferences

Besides intent (ram) and local storage (rom/sdcard , including database), i cant see any other option(locally).

Case 1: you need to resume activity after the app is closed
you should use local storage

Case 2: you don't need to resume activity after the app is closed

option 1:
  0. load the first activity
  1. start login_activity (startActivityForResult()) (do not call finish() )
  2. after login is done (call finish())
  3. activity is resumed (if login fail -> redirect to other activity )

option 2:
  1. create a public class with a data member to save the content-id/activity class
     (you may assign singleton design pattern) 
like image 199
AC28 Avatar answered Nov 15 '22 00:11

AC28