0

How to set values globally so that i can access from any activity or fragment.

For eg : activity_login.java > user_id need to store globally so every time any section which depends on user_id, checking and pulling data from backend will be easy instead of passing through activity (intent)

Edit : i do need setter and getter from fragment or activtiy.

Shadab Khan
  • 93
  • 1
  • 9

3 Answers3

2

There are many ways to store values globally so it can be access from any where in application all classes :

  1. Declare public static variable but it's not preferable for long storage.
  2. Use shared preferences - SharedPreferences
  3. Use database - SQlite

You can use any of one above alternative to access globally values.

Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
  • static variables must be used with care. The OS can remove an app from memory when the space is needed and the static variables are then typically not restored when the activity is activated again. – Henry Oct 19 '16 at 05:20
  • @Henry,If you need to load a bunch of stuff in memory, that's either a problem or it isn't – Haresh Chhelana Oct 19 '16 at 05:23
  • Exactly, that's why I said "use with care". For long term storage static variables are almost always the wrong approach. – Henry Oct 19 '16 at 05:28
  • @Henry,Thanks now you can see my updated answer. – Haresh Chhelana Oct 19 '16 at 05:30
0

Use Sharedpreferences.its safe, Here's the example https://www.tutorialspoint.com/android/android_shared_preferences.htm

vyshak
  • 26
  • 2
0

Use sharedPreferences and access the values at any of your class

Put the below code at SamplePreferences.java

private static final String TOTALCOUNT = "total_count";

public static void setTotalCount(Context thisActivity, String id) {
    Editor editor = thisActivity.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
    editor.putString(TOTALCOUNT, id);
    editor.commit();
}

public static String getTotalCount(Context thisActivity) {
    SharedPreferences user_pref = thisActivity.getSharedPreferences(KEY, Context.MODE_PRIVATE);
    return user_pref.getString(TOTALCOUNT, "0");

}

You can set the values from any of your class use below code

SamplePreferences.setTotalCount(thisContext, "2");

Access that value using below code

SamplePreferences.getTotalCount(thisContext);
Ram Suthakar
  • 275
  • 2
  • 15