I am Wondering about One-time screens... I know, I should use something like SharedPreferences or stuff like that.
If someone has a simple solution for one-time login screen. And a little example.
My login contains: weight, name , height, age and gender (spinner)
You can take a look at Android User info and Sign in :
https://developer.android.com/training/sign-in/index.html
Or you can use login with Facebook API.
Otherwise, I would use Shared prefs.
Create a shared prefs file
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
This will create a private file for the current activity. You can use MODE_WORLD_READABLE and MODE_WORLD_WRITABLE if it fits your needs.
You can also provide a file name as the first parameter if needed :
SharedPreferences sharedPreferences = getPreferences("com.example.stackoverflow.myfile", Context.MODE_PRIVATE);
Write a shared pref
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("USERNAME", "test");
editor.commit();
You can put any primitive type : int, string, boolean, etc.
It is a key/value set. the key string "USERNAME" will then have a value of "test".
Read shared pref
String username = sharedPreferences.getString("USERNAME", "NO NAME");
The second parameter is a default value to use if the key "USERNAME" didn't get any value.
Related
So basically I have an activity (SplashActivity) that serves as a splash screen. It reads a key named username from the application's SharedPreferences, then if it finds the key, starts HomePage activity. Otherwise it starts LoginActivity. When the login is successful in LoginActivity, I am storing the username and password via this code:
SharedPreferences prefs = LoginActivity.this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", username);
editor.putString("password", password);
editor.apply();
The login page also has an autocomplete feature for the password field. This is how I am reading the password:
String password = this.getPreferences(MODE_PRIVATE).getString("password", "");
And I get the stored password. However, when I restart the app and run SplashActivity I can't read the password despite using the exact same code as above. Is there something wrong I am doing here?
Quoting the JavaDocs for getPreferences():
Retrieve a SharedPreferences object for accessing preferences that are private to this activity.
(emphasis added)
So, SplashActivity cannot read a value written to the private preferences of LoginActivity.
You probably want to switch to getSharedPreferences(), where you provide your own name that can be shared between the two activities.
String getString(String name, String defValue){...}
This is the definition of getString(...) method of SharedPreferences so I think it's possible if I run code below, it returns 1 two times:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
Timber.e(pref.getString("new", "1"));
Timber.e(pref.getString("new", "100"));
because at the first time its empty, so "1" will store, after that because of it has value ("1"), it will return it's value ("1") not default value ("100")
but it returns "1" and "100" and "new" does not store in my pref file (located in data/data/...)
Am I understanding it wrong or something goes wrong in this code?
Use can only get The data using getString.
to store data use Editor.commit();
Editor editor = settings.edit();
editor.putString("someKey", "someVal");
editor.commit();
only after that you can get this value.
String value = settings.getString("someKey", "someDefaultValueIfThisKeyNotUsedBefore");
In this example, you will recieve "someVal" if commit is used beforehand.
You must put"Something" to SharedPreferences.Editor, and commit them.
pref.getString wont store anything.
Refer to the links below:
https://developer.android.com/reference/android/content/SharedPreferences.html
https://developer.android.com/reference/android/content/SharedPreferences.Editor.html
I tried to append the data in shared preference file by using
SharedPreferences sharedPreferences = getSharedPreferences("myData", MODE_APPEND);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", userName.getText().toString());
editor.putString("password", password.getText().toString());
editor.commit();
But I found that new value overwrites the old value. Will you help me to fix this issue?
MODE_APPEND doesn't mean that you add multiple values for each key. It means that if the file already exists it is appended to and not erased . We usually used MODE_PRIVATE.
As for saving multiple names and passwords, you can take a look at putStringSet(string key Set<String> values Method.
You can save the for each key a set of string values. You can separate the username and password by some special character or string. You may even serialize an object to json.
So basically what you need to do is:
Get the list of values from Shared Preferences
Append the current value to the list.
Save the List back to Shared Preferences.
I saw this on stack Need to save a high score for an Android game
This is what it told me
//setting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();
//getting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0); //0 is the default value
I was wondering, should "key" be the string where the highscore is located? and does it matter what i name my prefs key.
Thanks for your time.
The Android Developers documentation is an excellent place to start with any question like this. SharedPreferences can be found here. SharedPreferences is a simple Key-Value pair storage, so if you put an int into your shared preferences as with the key "high score", then in the future, if you want to get that int, you need to use prefs.getInt("high score"). It doesn't matter what you name your keys, but it is generally good practice to use private static final string variables to store keys you will use on a regular basis.
You can name the string whatever you like. Click here for documentation. You can name it anything from "foo" to "bar".
I am attempting to save a user id using SharedPreferences. Do values saved as SharePreferences persist across all Activities in my application so I can access the userid from any application? Below is my code for saving the userid.
userid = result.substring(3, result.length());
Log.d("userid at onpostexecute", userid);
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); // to update userid
editor.putString("userid", userid);
editor.commit();
And here is the code for accessing the userid from the SharedPreferences in another activity.
SharedPreferences prefs = getPreferences(MODE_PRIVATE); // to access userid
String userid = prefs.getString("userid", "");
Log.d("shared prefs userid", userid);
What is strange is that the above code is in my onCreate method but it doesn't show up in the Logcat even though other log data is displayed before and after this code. So is there something wrong with my code that I can't even get it to display in my logcat? I can't even tell if it is being updated.
Values saved as sharedPreferences can be shared between activities if you tell it to. Right now you are creating a preference that is only accessible to that same activity. You need to use:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
Like this you are creating a sharedPreference between your application. There is a lot of explanation on the topic in the accepted answer to another question. Link to question
As discussed in the answer the way you are using to save the preference will only work in the same activity that saved it.
I assume you mean can you access them from any Activity, yes, they do persist even when you leave your app and come back. From the Docs
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
If this Log.d("userid at onpostexecute", userid); doesn't even show up then I would put a breakpoint there and make sure you have a value for userid. I would also check your logcat filters to make sure that you are getting all logs. Just make sure that the type in the spinner is set to "verbose" just to be sure