Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share same data between multiple activities

Tags:

android

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.

like image 273
Harish Avatar asked Oct 25 '11 06:10

Harish


2 Answers

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;
like image 138
Padma Kumar Avatar answered Oct 05 '22 21:10

Padma Kumar


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

like image 40
Pratik Bhat Avatar answered Oct 05 '22 20:10

Pratik Bhat