Home » Android » android – How to share same data between multiple activities

android – How to share same data between multiple activities

Posted by: admin May 14, 2020 Leave a comment

Questions:

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.

How to&Answers:

One way to do it is to extend Application, and then call getApplication in your activities. This site has some examples.

Answer:

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

Answer:

Answer:

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;

Answer:

You should use sharedpreferences as per below details ,
http://developer.android.com/guide/topics/data/data-storage.html#pref

Answer:

After reading doc about SharedPreferences and the nearly to flamewar discussion about Singleton vs Application in android.

I conclude: Please disprove any conclusion

  • SharedPreferences: Good if you plan to keep only primitives, and easy to keep different parcels.
  • Parcelable: A low level solution, with a lot of boilerplate code, you can use in Extras
  • Serializable: If you don’t want to bother with Parcelable. See this
  • Singleton: My choice. Simple, quick and no boilerplate. My contribution is to use a Map inside for flexibility.

    public class Config {
    
        private static Config instance;
        private HashMap<String, Object> map;
    
        /*Keep doc about keys and its purpose if needed*/
    
        public static final String TOKEN = "token";
        public static final String SESSION = "sessionId";
    
        /** A bean with A LOT of useful user info */ 
        public static final String USER_BEAN = "userBean";
    
        private Config() {
            map = new HashMap<String, Object>();
        }
    
        public static final Config getInstance() {
            if (instance == null) {
                instance = new Config();
            }
            return instance;
        }
    
        public void setKey(String key, Object value) {
            map.put(key, value);
        }
    
        public Object getKey(String key) {
            return map.get(key);
        }
    }
    
  • Application: Almost the same as singleton, but for some hide-to-me reason, ease the testing and more android standarized way of doing things.

Answer:

I dont know what exactly the code is you are dealing with, but have you tried like this

in your current activity, create an intent

Intent i = new Intent(getApplicationContext(), ActivityB.class);
i.putExtra(key, value);
startActivity(i);

then in the other activity, retrieve those values.

Bundle extras = getIntent().getExtras(); 
if(extras !=null) {
    String value = extras.getString(key);
}

Answer:

The way that I do is that I extend a global class from Activity, and then extend all actual activities that the user will interact with from it. That’s how I learned to do it with some “learn to code for android” books I bought.

This is pretty much like using the Application class though.

Answer:

You can store it in SharedPreferences or in Singleton class.
where i would suggest to use singleton class.

  • SharedPreferences :

Write value

SharedPreferences mPref= this.getSharedPreferences("session", MODE_WORLD_READABLE);
mPref.edit().putString("session_id", your_session_value).commit();

Read Value

SharedPreferences mPref= getSharedPreferences("session", MODE_WORLD_READABLE);
String sSession_id= mPref.getString("session_id", null);
  • Singleton class

    public class Session {
    
        private static Session session = null;
    
        private String mSessionId;
    
        private Session() {
        }
    
        public static Session getInstance() {
            if (session == null) {
                session = new Session();
            }
            return session;
        }
    
        public String getSessionId() {
            return mSessionId;
        }
    
        public void setSessionId(String pSessionId) {
            this.mSessionId = pSessionId;
        }
    }
    

Write to singleton

Session mSession  = Session.getInstance();
mSession.setSessionId("your_session_id");

Read from singleton

Session mSession  = Session.getInstance();
String mSessionId = mSession.getSessionId();