How to get value of SharedPreferences android - android

I'm trying to use SharedPreferences here is what i do
public void StoreToshared(Object userData){
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userData);
Log.d("data", " Setup --> "+json);
prefsEditor.putString("userinfo", json);
prefsEditor.commit();
}
Log.d result is like this
Setup --> {"nameValuePairs":{"userData":{"nameValuePairs":{"phone":"089688xxxxxxx",
"username":"username of User","flag":1,"Email":"mymail#mail.com",
"tipe":"TP001","Deskripsi":"Ini tentang gua","user_id":"USER001",
"password":"c83e4046a7c5d3c4bf4c292e1e6ec681","fullname":My fullname"}},"status":"true"}}
then i'm trying to retrieve it, in other activity here is what i do
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String data = mPrefs.getString("userinfo", null);
Log.i("Text", "Here is the retrieve");
Log.i("data", " retrieve --> "+data);
}
and here how i open my other activity
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
With my script above, the result from my logcat , i only see like Log.d above. So my question is, how can i retrieve it ?

Try to add a key on your SharedPreferences:
public void StoreToshared(Object userData){
SharedPreferences mPrefs = getSharedPreferences("your_sp_key", MODE_PRIVATE); //add key
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userData);
Log.d("data", " Setup --> "+json);
prefsEditor.putString("userinfo", json);
prefsEditor.commit();
}
Retrieval:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("your_sp_key", MODE_PRIVATE); //add key
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String data = mPrefs.getString("userinfo", null);
Log.i("Text", "Here is the retrieve");
Log.i("data", " retrieve --> "+data);
}

You can create 2 method:
// put value
public static void putPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
and
// get value
public static String getPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
then you can put value
putPref("userinfo", "/** user data json */", getApplicationContext());
and get value
String data = getPref("userinfo", getApplicationContext());
I hope it can help your problem!

You need to convert the string data from SharedPreferences back to a PoJo using Gson. Simply do this:
Object userData = new Gson().fromJson(data, Object.class);
I guess that should solve it.

The api: getPreferences will use the activity name to create an xml file if not exists. For example, assume StoreToshared method is put in activity: LoginActivity.java, it will create a file: LoginActivity.xml to store your pref data. Hence, when you go into other activity, let say its name is: MainActivity.java, getPreferences will look into file "MainActivity.xml" instead of "LoginActivity.xml", that is why you cannot retrieve your data.
The solution is to use: getSharedPreferences.
Hence your code can be modified as follow:
public void StoreToshared(Object userData) {
SharedPreferences mPrefs = getSharedPreferences("FILE_NAME",MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userData);
Log.d("data", " Setup --> "+json);
prefsEditor.putString("userinfo", json);
prefsEditor.commit();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("FILE_NAME",MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String data = mPrefs.getString("userinfo", null);
Log.i("Text", "Here is the retrieve");
Log.i("data", " retrieve --> "+data);
}
Hope this help.

In year 2020,
Google has been released new data storage that is repleced of Shared Preference...
It' is developed with "Kotlin"
Source

Related

passing data with two activity using sharedPreference

Hy, I'm writing an application for a project. I'm trying to pass data between two activities. I tried to use the SharedPreference but it's doesn't work. The output send me always " ".
I post the two function below.
function for send data:
public void SaveUser(FirebaseUser user){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(TEXT, user.getDisplayName());
}
function for get data:
public String ReturnCreatorName(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
String name = sharedPreferences.getString(TEXT, "");
return name;
}
you forgot editor.commit();
public void SaveUser(FirebaseUser user){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(TEXT, user.getDisplayName());
editor.commit();
}

Get a java.lang.ClassCastException during using SharedPreferences

I use SharedPreferences in my app to save small Integer data . But I get ClassCastException in this line .
int number = mySharedPref.getInt("numberOne",0);
Here is my code .
To store data .
mySharedPref=getSharedPreferences("MyPref",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mySharedPref.edit();
editor.putInt("numberOne",myInteger);
To get data
mySharedPref = getSharedPreferences("MyPref",Context.MODE_PRIVATE);
int number= mySharedPref.getInt("numberOne",0);
display(number);
I think the problem is that you have not committed the data stored in SharedPreferences.
So you should do a
editor.commit();
while storing the data.
Try this
To Store data
public static void setInteger(Context context, String key, Integer Value) {
sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor sEdit = sharedPreferences.edit();
sEdit.putInt(key, Value);
sEdit.commit();
}
To get data
public static Integer getInteger(Context context, String key) {
sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Integer value = sharedPreferences.getInt(key, 0);
return value;
}
You have to call commit() method to save data changes in SharedPreferences.
Here is the get data method
private void showData() {
SharedPreferences sharedPreferences = getSharedPreferences("MyFile", Context.MODE_PRIVATE);
int number = sharedPreferences.getInt("numberOne", 0);
display(number);
}
Here is get savemethod
private void saveData(int value) {
SharedPreferences sharedPreferences = getSharedPreferences("MyFile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("numberOne", value);
editor.commit();
}

ArrayList won't load when app is restarted

I'm quite new to android, and I am having a problem with save and load data.
I am trying to make an app with a save and a load button, these buttons should save 2 ArrayLists with x- and y-coordinates.
I've tried doing it with SharedPreferences and it works until the apps restarts or the screen rotates.
When i take look in the app files the ArrayLists files are in the SharedPreferences folder, but my app will not load those if I press the load button.
Could anyone help we why this does not work when the app is restarted?
this is my load and save code:
public void saveArrayList(ArrayList aList, String s) {
SharedPreferences sharedPrefs = getSharedPreferences(prefs, MODE_PRIVATE);
editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(aList);
editor.putString(s, json);
editor.commit();
}
public void loadFloatList(ArrayList aList, String s) {
SharedPreferences sharedPrefs = getSharedPreferences(prefs, MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPrefs.getString(s, null);
Type type = new TypeToken<ArrayList<Float>>() {
}.getType();
aList = gson.fromJson(json, type);
}
Possible error; you are re-initializing gson and sharedPrefs which then takes a new state with the same key value. you should do this in onCreate.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPrefs = getSharedPreferences(PREFS, MODE_PRIVATE);
json = sharedPrefs.getString(JSON_KEY, "");
gson = new Gson();
}
it is best to use apply() because this save the value(s) of your sharedprefs as instance but commit() do this when the app closes.
public void saveArrayList(ArrayList aList) {
String json = gson.toJson(aList);
editor = sharedPrefs.edit();
editor.putString(JSON_KEY, json);
editor.apply();
}
public void loadFloatList(ArrayList aList, String s) {
json = sharedPrefs.getString(JSON_KEY, "");
Type type = new TypeToken<ArrayList<Float>>() {
}.getType();
aList = gson.fromJson(json, type);
}
note also the PREFS and JSON_KEY are final key values
private final String PREFS = "prefs";
private final String JSON_KEY = "json";
private SharedPreferences sharedPrefs;
private SharedPreferences.Editor editor;
private String json;
private Gson gson;

Shared Preference not working across two activities?

Writing preference from file Login.java:
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
SharedPreferences.Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
Loading preference in UpdateList.java:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(UpdateList.this);
String post_username = sp.getString("username", "anon");
I want to pass this shared preference to a php file through json, but it is not able to save the preference across two activities
Try this code to access and write your SharePreference
public static final String PREF_FIELD = "name";
public String getText(Context context) {
SharedPreferences preferences = context.getSharedPreferences(
"GLOBAL",
Context.MODE_PRIVATE);
String sessionId = preferences.getString(
PREF_FIELD,
"");
return sessionId;
}
public void setText(Context context, String text) {
SharedPreferences preferences = context.getSharedPreferences(
"GLOBAL",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(PREF_FIELD, text);
editor.commit();
}

How to save TextView Values in SharedPreferences

How to save TextView values in SharedPreferences, see my code below and let me know how to store to SharedPreferences and retrieve in onCreate(..)
my code looks like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtOperative = (TextView) findViewById(R.id.currentOperative);
txtEvent = (TextView) findViewById(R.id.currentEvent);
intent = getIntent();
strEventName = intent.getStringExtra("eventName");
strOperativeName = intent.getStringExtra("operativeName");
txtEvent.setText(strEventName);
txtOperative.setText(strOperativeName);
}
I want to show these values always in TextViews, whenever user comes back to this activity
Simple use this for save your TextView value in sharedpreference
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("textvalue", txtEvent.getText().toString());
sedt.putString("txtopertaive", txtOperative.getText().toString());
sedt.commit();
Now after that retrieve it anywhere in your Activity class or any other Activity by
SharedPreferences sp = getSharedPreferences("key", 0);
String tValue = sp.getString("textvalue","");
String tOperative = sp.getString("txtopertaive","");
To save the data, Can't see any call for SharedPreferences - editor/ editor.commit()
Add those functions to your activity:
When you want to save data:
saveDataToPreferences(context, "strEventName", valueHere);
And in your activity,
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
context=this;
txtOperative = (TextView) findViewById(R.id.currentOperative);
txtEvent = (TextView) findViewById(R.id.currentEvent);
intent = getIntent();
strEventName = intent.getStringExtra("eventName");
strOperativeName = intent.getStringExtra("operativeName");
txtEvent.setText(getDataFromPreferences(context,"strEventName"));
txtOperative.setText(getDataFromPreferences(context,"strEventName"));
}
public static void saveDataToPreferences(Context context, String key,
String value) {
SharedPreferences prefs = context.getSharedPreferences("your package name",
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getDataFromPreferences(Context context, String key) {
SharedPreferences prefs = context.getSharedPreferences("your package name",
Context.MODE_PRIVATE);
return prefs.getString(key, Constants.BLANK);
}
To store in shared preferences your value use that code.
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("OPERATIVE", txtOperative.getText().toString());
editor.String("EVENT", txtEvent.getText().toString());
editor.commit();
Use
prefs.edit().putString(context.getString(R.string.NAME), name).commit();
in order to save data to shared preferences and
prefs.getString(context.getString(R.string.NAME), "");
to get data from shared preferences.
define Editor like below
private Editor editor;
and initialize it after initializing shared preference like
editor = prefs.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.commit();
And to retrieve this value just call
String value = prefs.getString("key1","");

Categories

Resources