How can I create a user-specific SharedPreference? - android

I'm trying to create a SharedPreference that is user specific. All I want to store is the layouts background depending on what is from the settings menu. How can I store and load SharedPreference depending on the Account being used?

You can use your user id as a key for SharedPreference and then save your user details as object in it's value.
In this way you store User data for all users locally.
/*Save the object in shared Preferences*/
public void saveObjectToPreferences(String key, Object value) {
final SharedPreferences prefs = getSharedPreferences(ApplicationConstants.PREF_FILE_CONFIG, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
String jsonValue = new Gson().toJson(value);
editor.putString(key, jsonValue);
editor.apply();
}
/*Get the object from shared Preferences*/
public Object getObjectFromPreferences(String key, Object defaultObj) {
final SharedPreferences prefs = getSharedPreferences(ApplicationConstants.PREF_FILE_CONFIG, Context.MODE_PRIVATE);
String value = prefs.getString(key, "");
Object object = new Gson().fromJson(value, defaultObj.getClass());
return object;
}
Pass user id in key and details in object in these methods. it will work.

Could you add a value field that contains the users information? Then you would search for the username and check it's children for corresponding information. You might have to store information as objects then.
If you are using Shared Preferences, it should only contain a small amount of key-value pairs. Since you are using a local database, I suggest storing your values there instead. You could have a table for each type of information you want to store, say High Scores. You would need a "USERID" field so that when you perform a search on the Database you could use the where clause to specify which USERID to search for. Once you have searched for the user's information you can store into Shared Preferences to make it easier to work with and only have a small amount of data as opposed to everyone's data. Once you're done with using the information you would save the information back to the DB.

Related

Store data in android studio by using sharedPreferences

When storing data in android studio using SharedPreferences. it store did not store the Newest value at first. I mean the data location does not update.
I want to newest store data in 1st location and the previously stored data automatics shift to the next location.
Example>
I enter/store first time a value in Edit Text. it stores in the first location but when I store the Second value. It did not update the first value location it store data in the second location.
btnSaved.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("id", item.getId());
editor.putString("name", item.getName());
editor.putString("image", item.getImge());
editor.putString("status", item.getStatus());
editor.putString("timeStamp", item.getTimeStamp());
editor.putString("URL", item.getUrl());
editor.commit();
if you are new to android studio understand data storage options clearly.
this one will help.
if you are going to use id like "status", "email", "name" multiple times save them in a separate class as static final variables.
don't save variables like that make a separate class as User or something, set the value there, and save it as a JSON object.
like this
getAppPrefsEditor().putString("user", provideGson().toJson(object of YourClass)).apply();
and get them like this
String userStr = getAppPrefs().getString("user", null);
user = provideGson().fromJson(userStr, YourClass.class);
and you can get the value inside "user"
also there is some free cloud storage if you want to try you can check,
firebase is quite easy to start with.firebase web link

SharedPreferences - Difference between these two ways of retrieving the Preference value?

I am using the Preference-API..
Typically when I need to retrieve the value of a Preference, I currently do something like this:
final SharedPreferences getPrefs =
PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean isThisPrefEnabled = getPrefs.getBoolean(REFERENCE_TO_PREF_NAME, false);
// OR
String theChosenPref = getPrefs.getString(PREF_NAME, DEFAULT_VALUE);
But I'm curious, couldn't I also do it like this? and if so, what is the difference?
Preference nameOfPref = findPreference(PREFERENCE_KEY);
boolean isPrefEnabled = nameOfPref.isEnabled();
// OR
String thePrefValue = nameOfPref.toString();
It seems to be more efficient, but the first example seems to be what get's used. Why is this?
Thanks.
SharedPreferences is an android specific interface documentation
android.content.SharedPreferences : is a key/value store where you can save a data under certain key. To read the data from the store you have to know the key of the data. This makes reading the data very easy. But as easy as it is to store a small amount of data as difficult it is to store and read large structured data as you need to define key for every single data, furthermore you cannot really search within the data except you have a certain concept for naming the keys.
Preferences is a core java class documentation
java.util.prefs.Preferences : This class allows applications to store
and retrieve user and system preference and configuration data. This
data is stored persistently in an implementation-dependent backing
store.

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

Saving a value on android

I want to save a String value on Android and have access to this
String every time the application starts.
For instance the String value will have the user's name which he has created by
his own. And after restaring the api he would have this name already on the top.
Like a cookie or sth. How to save such file on android memory ?
Can someone guide me?
Use the following:
private static final String PREFS_NAME = "YOUR_TAG";
private static final String DATA_TAG = "DATA_TAG";
private static final String data = "oh, what a data!";
//init
SharedPreferences mSettings = context.getSharedPreferences(PREFS_NAME, 0);
//commit
SharedPreferences.Editor editor = mSettings.edit();
editor.putString(DATA_TAG, data);
editor.commit();
//clear
SharedPreferences.Editor editor = mSettings.edit();
editor.clear();
editor.commit();
//get
String data= mSettings.getString(DATA_TAG, null);
If you would like to store your data not only on your local device but share this data across the devices for the same user or even across different platforms you can use a simple API of Skiller SDK. I am ofcourse from Skiller, for full disclosure.
If you're looking to only store the data locally, use SharedPreferences. If you're looking to have this data persist across multiple devices (always available for this user), check out Swarm's Cloud Data, which provides a simple set/get (like SharedPreferences) for storing data in the cloud.
This is what SharedPreferences is all about.
Best way to implement is, store in shredpreferences, read it on lauch of your application. Shared Preference API. HEre is an example
on how to use SharedPreferences

Categories

Resources