How to share same data between multiple activities

Solution 1:

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

Solution 2:

  • Use the Application class to share common data.
  • Use Shared Prefrences or databases or some sort of persistant storage.

Solution 3:

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;