I try to save a location on my Preference. SavedLocation class store three variables: name, location and the location type. All look great until I try to read saved dates from Preference. The name and location type are stored perfectly but stored location is null. In debug savedlocation contain all wanted variable but look like ed.putString(SAVED_LOCATIONS, gson.toJson(savedLocations, savedLocationsType));
not write correct my dates.
private void saveLocation(SavedLocation savedlocation, Context context) {
Gson gson = new Gson();
Type savedLocationsType = new TypeToken<ArrayList<SavedLocation>>() {}.getType();
ArrayList<SavedLocation> savedLocations = getSavedLocations(context);
savedLocations.add(savedlocation);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor ed = prefs.edit();
ed.putString(SAVED_LOCATIONS, gson.toJson(savedLocations, savedLocationsType));
ed.apply();
}
SavedLocation class is alike:
public SavedLocation(String name, Location location, LocationType type) {
this.name = name;
this.location = location;
this.type = type;
}
Any suggestion?
Try this
Create variable for SharedPreferences and Editor.
SharedPreferences pref;
Editor editor;
String PREF_NAME="my_location"
Now get preference
pref = this.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
Now add location to preference
editor.putString(SAVED_LOCATIONS, gson.toJson(savedLocations, savedLocationsType));
editor.commit();
Then fetch the data
String location=pref.getString(savedLocations, "defaultvalue");
Related
I am unable to to show updated values in edit text. I have database on server. I am updating user values using retrofit. On server values updates successfully but when i revisit the profile page it shows the values populated from shared preferences. On login i save values in shared preferences and throughout application uses these values.
The code for saving and retrieving the values is below:
Get and set email address in shared preferences
public void putEmail(String loginorout) {
SharedPreferences.Editor edit = app_prefs.edit();
edit.putString(EMAIL, loginorout);
edit.apply();
}
public String getEmail() {
return app_prefs.getString(EMAIL, "");
}
Retrieve values from shared preferences
accountETSU1.setText(preferenceHelper.getEmail());
It's more simple if you create a object called PreferenceHelper, in that object you create a static string for the name of the email like:
final String emailUser = "emailUser";
With that string you create 2 functions one to write:
public void writeEmail(String : email, Context : context){
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(emailUser, email);
editor.commit();
}
The other one to get :
public String getEmail(Context : context){
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
String email = sharedPref.getString(emailUser, "");
return email;
}
Then call the object in your activity
Context context = this#YourActivity;
accountETSU1.setText(PreferenceHelper.getEmail(context));
I made a chat room app which asks the user to enter its username every time i open it. How can i make it remember me? I am using fire-base for the back end.
See Code Here
Create Shared Preference class where first time when user enter his/her username store it.
You can read more about Shared Preference here
The for you as follows
public class SharePref {
public static final String PREF_NAME = "chatroom.shared.pref";
public static final String PREF_KEY = "chatroom.shared.username";
public SharePref() {
}
public void save(Context context, String text) {
SharedPreferences sharePref;
SharedPreferences.Editor editor;
sharePref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
editor = sharePref.edit();
editor.putString(PREF_KEY,text);
editor.apply();
}
public String getData(Context context) {
SharedPreferences sharePref;
String text;
sharePref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
text = sharePref.getString(PREF_KEY,null);
return text;
}
}
Now in your MainActivity you can check if you have already stored the username for user
inside your onCreate()
SharePref sharePref = new SharePref();
String UserName = sharePref.getData(mContext);
if(UserName == null) {
String value = //username value;
SharePref sharePref = new SharePref();
sharePref.save(context,value);
}
else {
// you already have username do your stuff
}
Hope this will help
You can use shared preference. Say you are saving username in String called User. To save username:
SharedPreferences shareit = getSharedPreferences("KEY",Context.MODE_PRIVATE);
SharedPreferences.Editor eddy = shareit.edit();
eddy.putString("AKEY", User);
eddy.commit();
And everytime user login:
SharedPreferences sharedPreferences = getContext().getSharedPreferences("KEY", Context.MODE_PRIVATE);
String getName = sharedPreferences.getString("AKEY", "");
String getName will have the value of your username. The "KEY" and "AKEY" used above are to give special id to different values saved via shared preference.
SharedPreferencec prefs = getSharedPreferences("username",Context.MODE_PRIVATE);
SharedPreference.Editor editor = prefs.edit();
if (!prefs.getString("username",null)
//do the chatting
else {
//show dialog to get username
//now save it in shared preferences
editor.putString("username",username);
editor.commit();
}
I'm newbie for Android Studio & Java, i'm PHP user.
Just want to know how to do like PHP session in Android Studio.
No matter which Activity i go to, i can easily get the session value example like the User ID. (session["USERID"])
now the method i using is putting extra everytime i call for another activity.
i'm sure there will be a better way to do this.
anyone have any good suggestion?
PS: I google around and it keep return me PHP session tutorial/example/etc but not for Android Studio....(may be i enter work #keyword or sentence)
Thank You Very Much
Thanks to fillobotto & Arshid KV
here is my code
first_main activity
sharedpreference = getSharedPreferences(BIZInfo, Context.MODE_PRIVATE);
sharedpreference.edit().putString(userid, "12345");
sharedpreference.edit().commit();
second_main activity
sharedpreference = PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = sharedpreference.getString("text", null);
if (restoredText != null) {
sp_name = sharedpreference.getString("userid", "No name defined");
}
Log.i("TAG", "onCreate: [" + sp_name + "]");
log show empty value/nothing...
what went wrong!?
You can use SharedPreferences as session in php
Demo code :-
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Arshid");
editor.putInt("Age", 22);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int Age = prefs.getInt("Age", 0); //0 is the default value.
}
You were really near to the solution. This is what I use:
public static String getSession(Activity context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getString("session", null);
}
public static void setSession(Activity context, String session) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("session", session);
editor.apply();
}
I'm actually passing the Activityto get SharedPreferences, but in this way you will obtain an instance of the object which is not activity-related.
I need to know how can shared preference can be used to keep my data persistent and also update the values.I have written some code.
MainActivity.java
SharedPreferences sPrefs= this.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
if(sPrefs.contains("userData"))
{
retreivepreviousdata=gson.fromJson(sPrefs.getString("userData",""),DataStore.class);
userDataStore.getDataStore().addAll(retreivepreviousdata.getDataRetrieve());
}
userDataStore.getDataStore().add(usrData);
SharedPreferences.Editor prefEditor = getSharedPreferences(mypreference, Context.MODE_PRIVATE).edit();
String saveData = gson.toJson(userDataStore);
prefEditor.putString("userData", saveData);
prefEditor.apply();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();`
SecondActivity.java
String mypreference="user_data";
SharedPreferences sPrefs= this.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
DataStore dataPull=new DataStore();
Gson gson=new Gson();
String pull=sPrefs.getString("userData","");
dataPull=gson.fromJson(pull,DataStore.class);
System.out.println(dataPull.getDataStore().get(0).toString());
RecyclerView recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
MyRecyclerAdapter mAdapter=new MyRecyclerAdapter(dataPull);
recyclerView.setAdapter(mAdapter);
The problem with this code is the values entered are saved and persistent.But when i close,reopen the app and enter values the previous data gets override.
For Storing the value into SharedPreferences
SharedPreferences shared = getSharedPreferences("user_Info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("key", value);
editor.commit();
For retrieving values from SharedPreferences just use this
SharedPreferences sharedPref = getSharedPreferences("user_Info", Context.MODE_PRIVATE);
String value = sharedPref.getString("key", "defaultValue");
If you want to store an ArrayList inside SharedPreferences, just convert it to a string. Then, you can "deconvert" it. E.G.
String toSave;
// Object is for your object type. Just get your objects converted to string, that's the point.
for(Object obj : arrayList){
toSave += obj.toString() + "\n";
}
SharedPreferences prefs = getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", toSave);
editor.apply();
and...
SharedPreferences prefs = getSharedPreferences("PREFS_NAME",Context.MODE_PRIVATE);
String toGet = prefs.getString("key", "");
String[] parts = toGet.split("\n");
for(String s : parts){
arrayList.add(s); // or do whatever conversion you want to get your Object type
}
I am trying to save an integer value and retrieve the value using a same button using shared preferences.
To be more precise, when i click a button the value should be incremented(i++) and then it should be stored. When i close and open the application, it should retrieve the same value from where i left it. How do i do this?
I am using eclipse.
This works for me
public class OnPreferenceManager {
private SharedPreferences.Editor editor;
private SharedPreferences prefs;
private String startHour = "startHour";
private OnPreferenceManager() {}
private OnPreferenceManager(Context mContext) {
prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
editor = prefs.edit();
}
public static OnPreferenceManager getInstance(Context mContext)
{
OnPreferenceManager _app = null;
if (_app == null)
_app = new OnPreferenceManager(mContext);
return _app;
}
public void setStartHour(int hour){
editor.putInt(startHour, hour);
editor.apply();
}
public int getStartHour(){
int selectionStart = prefs.getInt(startHour, -1);
return selectionStart;
}
}
When you need to set integer just write as below
OnPreferenceManager.getInstance(this).setStartHour(theValueYouWantToStore);
And to retrieve write
OnPreferenceManager.getInstance(this).getStartHour()
You can use shared preferences as below.
//To save integer value
SharedPreferences preference = getSharedPreferences("YOUR_PREF_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YOU_KEY",you_int_value);
editor.commit();
//To retrieve integer value
SharedPreferences settings = getSharedPreferences("YOUR_PREF_NAME", 0);
int snowDensity = settings.getInt("YOU_KEY", 0); //0 is the default value
Check this gist https://gist.github.com/john1jan/b8cb536ca51a0b2aa1da4e81566869c4
I have created a Preference Utils class that will handle all the cases.
Its Easy to Use
Storing into preference
PrefUtils.saveToPrefs(getActivity(), PrefKeys.USER_INCOME, income);
Getting from preference
Double income = (Double) PrefUtils.getFromPrefs(getActivity(), PrefKeys.USER_INCOME, new Double(10));