SharedPreferences saving string [duplicate] - android

This question already has answers here:
Shared preferences for creating one time activity
(14 answers)
Closed 4 years ago.
I read about SharedPreferences but did not understand where i need to put the saving data and where to put the get objects.
In my app i get the full name when i open it in the first time by dialog.
I need to save the full name for ever (until the user will delete the app or something).
Where and what should i write to save the data(in onDestroy)?
Like :
// Create object of SharedPreferences.
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
//now get Editor
SharedPreferences.Editor editor= sharedPref.edit();
//put your value
editor.putString("name", strName);
editor.commit();
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
String name = sharedPref.getString("name", "");
And where and what should i write to get the data(in onCreate)?

You don't have to to anything in onDestroy(). If your app gets uninstalled your data in shared preferences will be removed as well.
editor.putString("name", strName);
The first parameter is the key and the second one ist the value.
if you want to save the user's name, you pass the first parameter "name" and for the second parameter, the user's name.
when you want to read the user's name later you use
String name = sharedPref.getString("name", "");
Again, the first parameter is the key. You want to read the user's name so you use "name" and the second parameter is the default value, if there hasn't been saved a value, yet.

Related

How can I save data from an EditText component so it shows up when the app is reopened?

I am using Android Studio and programming in Kotlin. I haven't been able to find a way to save the data entered by the user so it appears when they reopen the app. Thank you ahead of time!
You have to store your data in shared preference when any click event listen or on edittext textwatcher you can set your character in preference but best way is on any click event save data on preference and when activity open set data from preference on edittext.
Store it in Shared Preferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
use this save the value..
Editor editor = sharedpreferences.edit();
editor.putString("key_name", "value"); //here give name and value to save
editor.commit();
use this to get the value.
String edittextvalue = pref.getString("key_name", null); //put edittextvalue where ever you what to show the value.
use this step to remove or clear the value
editor.remove("name");
editor.commit();

Android, SharedPreferences default values not set if there is no pref

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

how to append data in Shared Preference in Android

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.

Does SharedPreferences work in Eclipse emulator?

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

Shared Preference problem in android app

in my app the first activity is a sign in page. In the edit boxes i am typing the user name and password. Those values are been move to an api and in return i am getting the userid from the server as an xml file.
I am parsing the xml file and storing the value in shared preferrence as follows
SharedPreferences.Editor IdEditor = Id.edit();
IdEditor.putString("useridValue", chap.getid());
IdEditor.commit();
And in the next time when the user opens the app i want to check whether it is already signed i or not. How to check this using the value stored in Shared preference
is your Id class extending SharedPreferences ?
maybe
String userId = Id.getString("useridValue");
If your preference is stored in the default preference then you can
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userId = prefs.getString("useridValue");
on a side note you shouldn't really use a capital I on the IdEditor variable it should probably be idEditor
Check whether this entry already exist in shared preference, using:
id.containskey("useridvalue")

Categories

Resources