Zareen Arshad
Zareen Arshad

Reputation: 1

Declaring a android Global Variable that changes time to time

I am creating a location tracking application where I want the email-id of the logged in person as a global variable. As the email will keep changing depending on who logs in, i have a little confusion on how to go about with. Thanku :)

Upvotes: 0

Views: 50

Answers (2)

Umar Farooq
Umar Farooq

Reputation: 51

Instead of creating Global variables please, Shared preferences and save them. Now, you can access them across the app or even after when user come back to app after closing App. Just as following :

SharedPreferences sharedPref =     getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("email", [email protected]);
editor.commit();
//to read shared prefere
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String defaultValue = "[email protected]"; //this is default email, so if you don't have values in preferences then it will be returned 
String email= sharedPref.getString("email", defaultValue );

For details, Please follow Tutorial at: Official doc : SharedPreferences - Saving Key-Value Sets

Upvotes: 2

Menelaos Kotsollaris
Menelaos Kotsollaris

Reputation: 5506

As Kunu recomended, SharedPreferences are for these cases.

public static String PREFS_NAME = "loginDetails";
public static String LOGGED_EMAIL = "Email";

To edit your email:

public static void editEmail(String email)
{
    Context context = getAppContext();
    SharedPreferences.Editor editor = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
    editor.putString(LOGGED_EMAIL , email);
    editor.apply();
}

For more details about SharedPreferences check this answer.

Upvotes: 0

Related Questions