简体   繁体   中英

Android App Store data

I have an android app which stores a bit of String data in an Object. I want to use this object all over the app.

Meaning: In my MainActivity i start a new intend getDataActivity, in this activity i get the data via TextFields and store them in a new Object file. after putting the data in i return via intent back to the MainActivity. In the main Activity I want to start a second Activity writeDataActivity. For that i need the data object from the getDataActivity.

Whats the best way to the data. It dont have to be a file or anything i can be temporally while the app is opened. I read something aber ContextData but Im not sure how to implement that. So whats the best way to save the data.

Data:

String url;
String username;
String password;
boolean connected;

Thx for any help or ideas.

You could use a singleton (eg a Credentials object which you create) to store the data. Alternatively you could just declare the Strings as static which will allow you to access those Strings anywhere. The data will be wiped when your process is killed/terminated by Android (leaving the app and coming back most of the time will not kill your app).

public class Credentials {
    public static String username;
    public static String password;
}
// write (assuming 'uname' is the user's name you want to save)
Credentials.username = uname;
// read
String user = Credentials.username;

If you wish to store the data persistently then you should use SharedPreferences . You can obtain this from any valid Context (eg your Activity ).

// write (assuming 'uname' is the string you want to save)
// NOTE: getSharedPreferences needs a valid context (so you can call this in onResume/onPause, or just MyActivity.this.getSharedPreferences()
SharedPreferences settings = getSharedPreferences("SharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", uname);

// read
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String username = settings.getString("username","");

Create a separate class with the reference of your object. Each time you need it you call this class

Use SharedPreferences

It's pretty easy to save a string: (For example username)

SharedPreferences prefs = context.getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", yourUsername);
editor.commit();

To read this string use:

prefs.getString("username", "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM