I have a login session ID which multiple activities need to use. How do I share this common data between multiple activities? Presently, I'm passing the data in the Intent but it is not working properly. For some activities, I pass some other data, and the common data is lost.
Use Singleton class for sharing.
sample code
public class Category {
private static final Category INSTANCE = new Category();
public String categoryName = "";
public int categoryColor = 0;
public boolean status = false;
// Private constructor prevents instantiation from other classes
private Category() {}
public static Category getInstance() {
return INSTANCE;
}
}
in other Activity/Class for setting the value as:
Category cat;
cat=Category.getInstance();
cat.categoryName="some name";
cat.status=ture;
for getting the values every where you want in your application.
Category cat;
cat=Category.getInstance();
String sq=cat.categoryName;
boolean stat=cat.status;
Use shared preferences like this:
SharedPreferences myprefs= this.getSharedPreferences("user", MODE_WORLD_READABLE);
myprefs.edit().putString("session_id", value).commit();
You can retrieve this info across your app like this:
SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
String session_id= myprefs.getString("session_id", null);
You should use intents when you want to start another activity from your current activity... also if the child activity is totally dependent on data from parent activity ...use intents
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With