2

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?

BluGeni
  • 3,378
  • 8
  • 36
  • 64

3 Answers3

5

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?

Community
  • 1
  • 1
M D
  • 47,665
  • 9
  • 93
  • 114
0

You could use SharedPreferences (kind of a persistence layer). Or you could pass data through Intent.

Community
  • 1
  • 1
mbmc
  • 5,024
  • 5
  • 25
  • 53
  • SharedPreferences holds the values even after the app closes correct? and with an Intent I would have to pass the variables from every activity to keep track of them? – BluGeni Mar 03 '14 at 16:10
0

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 
Elias Sh.
  • 510
  • 6
  • 11