Android - Storing/Retrieving Strings with Shared Preferences

Android - Storing/retrieving strings with shared preferences

I solved it!
It didn't work when I called the methods from within the class! I had to call it from another class for some reason, and write "classname.this" as Context parameter.
Here's the final working:

SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
settings = ctx.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(tal, pathtilsave);
editor.commit();

How to save a string in sharedPreferences

You need a fixed key to save and read your preference and you forgot to apply the modifications of the SharedPreference.

You need to do like this:

private static final String SHARED_PREFS = "sharedPrefs";
private static final String TEXT = "ahhsaushhuuashu";
private static final String KEY = "myKey";

public static void saveData(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(KEY, TEXT);
editor.apply();
}

public static String loadData(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
String text = sharedPreferences.getString(KEY, "");
return text;
}

Not able to get String value from SharedPreferences

For storing values into SharedPreferences you are using Editor and method call:

prefs.edit().putString(String key, String value)

And you did it right:

prefs.edit().putString("userPhone", userPhone).apply();

For retrieving data, we are using the same key as we used for storing. In your case, it is "userPhone".
So, you should do it with:

prefs.getString("userPhone", "Some default value");

But, you mixed key with preferences name and you called

prefs.getString(Config.PREF_NAME, "userPhone");

How to store strings in Shared Preferences

Algorhithm:

  • At a certain point in your app lifecycle, write a preference using a "name" and a value.
  • Retrieve the value when the app starts and compare it to something.
  • Act consequently.

From the reference site: http://developer.android.com/guide/topics/data/data-storage.html#pref

Using Shared Preferences

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).

User Preferences

Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).

To get a SharedPreferences object for your application, use one of two methods:

  • getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
  • getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

To write values:

  • Call edit() to get a SharedPreferences.Editor.
  • Add values with methods such as putBoolean() and putString().
  • Commit the new values with commit()
  • To read values, use SharedPreferences methods such as getBoolean() and getString().

Here is an example that saves a preference for silent keypress mode in a calculator:

public class Calc extends Activity
{
public static final String PREFS_NAME = "MyPrefsFile";

@Override
protected void onCreate(Bundle state){
super.onCreate(state);
//...

// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}

@Override
protected void onStop()
{
super.onStop();

// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);

// Commit the edits!
editor.commit();
}
}

How to use SharedPreferences in Android to store, fetch and edit values

To obtain shared preferences, use the following method
In your activity:

SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);

To read preferences:

String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());

To edit and save preferences

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();

The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory

Edit==>

I noticed, it is important to write difference between commit() and apply() here as well.

commit() return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.

apply() was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit.
More detail is here.

android studio save string shared preference, start activity and load the saved string

The issue with the code you have given is not with how you done it with shared preferences (you did that correctly btw)
Your issue is that you are comparing strings via == as this compares the string reference and not the string value. Use .equals() or .contains() instead.

if (payment_status.equals("success")) {
Log.i("payment status", "success");
}

Save ArrayList to SharedPreferences

After API 11 the SharedPreferences Editor accepts Sets. You could convert your List into a HashSet or something similar and store it like that. When you read it back, convert it into an ArrayList, sort it if needed and you're good to go.

//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);

//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();

You can also serialize your ArrayList and then save/read it to/from SharedPreferences. Below is the solution:

EDIT:

Ok, below is the solution to save ArrayList as a serialized object to SharedPreferences and then read it from SharedPreferences.

Because API supports only storing and retrieving of strings to/from SharedPreferences (after API 11, it's simpler), we have to serialize and de-serialize the ArrayList object which has the list of tasks into a string.

In the addTask() method of the TaskManagerApplication class, we have to get the instance of the shared preference and then store the serialized ArrayList using the putString() method:

public void addTask(Task t) {
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}
currentTasks.add(t);

// save the task list to preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
}

Similarly we have to retrieve the list of tasks from the preference in the onCreate() method:

public void onCreate() {
super.onCreate();
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}

// load tasks from preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);

try {
currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

You can get the ObjectSerializer class from the Apache Pig project ObjectSerializer.java



Related Topics



Leave a reply



Submit