10

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.

Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31
Harish
  • 3,122
  • 2
  • 31
  • 46
  • 1
    what you want to pass exactly? And post your code here – Paresh Mayani Oct 25 '11 at 06:07
  • You can either share data via intent or you can make 1 global class and access data through that..sending data via intent is very simple..u just have to put your data in intent.putExtra(suitable datatype) method and share it over multiple activities... – android Oct 25 '11 at 06:09
  • I have Login in my application in that i'll get sessionid i need to use it across all the activities which ever comeing after login also i need to pass some other data to next activities(including sessionid).Now i'm trying with intent but it's diverting sometimes to other activities. – Harish Oct 25 '11 at 06:15

9 Answers9

14

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

Patrick D'Souza
  • 3,491
  • 2
  • 22
  • 39
Pratik Bhat
  • 7,166
  • 2
  • 35
  • 57
7
Community
  • 1
  • 1
Reno
  • 33,594
  • 11
  • 89
  • 102
7

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;
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
Padma Kumar
  • 19,893
  • 17
  • 73
  • 130
2

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.

Community
  • 1
  • 1
albfan
  • 12,542
  • 4
  • 61
  • 80
2

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

Maneesh
  • 6,098
  • 5
  • 36
  • 55
1

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);
}
Randroid
  • 3,688
  • 5
  • 30
  • 55
0

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.

Andi Jay
  • 5,882
  • 13
  • 51
  • 61
0

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();
bhumik
  • 231
  • 2
  • 11
0

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

skynet
  • 9,898
  • 5
  • 43
  • 52