Reputation: 3454
I have a basic understanding of java and android but am still new and am struggling to find the correct way to save a variable and be able to access it/read it from other classes/activities. I have seen singletons but I am confused if it is the right way and how it would look, also do I need to make sure its thread safe?
Is there a better way that I am unaware of?
Basically I have a login that gets a username and some info about that user. How can I save that to a class/singleton and access it later?
EDIT
after some more searching I found this example:
public class Drivers {
private static Array drivers;
public static void setDrivers(Array c){
drivers = c;
}
public static Array getDrivers(){
return drivers;
}
}
and get and set like this:
public class AnyClass {
{
int clicks = ActionClass.getDrivers();
ActionClass.setDrivers(0);
}
Would this work/be correct?
Upvotes: 2
Views: 162
Reputation: 47807
Create a Constant
Class like :
public class Constant {
public static String USERNAME = "";
public static String PASSWORD = "";
}
Now, you can set this value in Activity1
like
Constant.USERNAME = "uname";
Constant.PASSWORD= "password";
Now, get this value in Activity2
like:
String u_name = Constant.USERNAME;
String pass = Constant.PASSWORD;
You can access this variables any where in your app.
And/or for Preference go to my this answer:Android. How to save user name and password after the app is closed?
Upvotes: 5
Reputation: 510
You can use sharedPreferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("PASSWORD_KEY", mPassword);
editor.commit();
String s = sharedPreferences.getString("PASSWORD_KEY", ""); // get the saved string
Upvotes: 0
Reputation: 5105
You could use SharedPreferences
(kind of a persistence layer). Or you could pass data through Intent
.
Upvotes: 0