0

I have an Activity with some Fragments and have to persist some fair amount of data but not fair enough for SQL. Now what is the best practice in use of SharedPreferences? I wanna avoid calls to the file and the commits of it as much as possible. Because I assume parsing of that file and especially the commits are bad for performance.

I know this question, which says that the call on the SharedPreferences file always returns the same object. But what about the commit?

Should I use f.e. a Bundle to save my data and persist them at once when the Activity goes in the background? Or should I always persist a portion of my data like in every Fragment? Or I just hunting ghosts?

Community
  • 1
  • 1
Steve Benett
  • 12,843
  • 7
  • 59
  • 79
  • Shared pref exist for storing.... pref so it won't be mass data. Just the user pref (police size, clear, cache, login, passord, ui color ...) – An-droid Aug 22 '13 at 15:39

3 Answers3

3

I think this is an unnecessary and premature optimization that won't realistically have any performance impact. How much data are you storing in SharedPreferences? I think you are just hunting ghosts.

If you are using it as a means of communication between fragments then you are using it for an unintended purpose.

edit: For some further evaluation, SharedPreferences basically stores things in a Key/Value map. This makes it really convenient to store and retreive simple things such as user preferences (hence the name). If you need to do anything more complex than that, you can quickly see how cumbersome it would become using a Key/Value map, which is why it would make sense to move to a database storage like SQLite. With a database you get the obvious benefit of using queries. Basically the point of SharedPreferences is added convenience to developers so that you don't need to create a full database to store simple values. See here for more:

Pros and Cons of SQLite and Shared Preferences

Community
  • 1
  • 1
telkins
  • 10,440
  • 8
  • 52
  • 79
  • I just use the SharedPreferences as they are mentioned to. For passing values I know better approaches. But a map can grow like any other collection. The point was just the performance of it and the right usage. – Steve Benett Aug 22 '13 at 15:49
  • @SteveBenett Did you see my edit? Let me know if that doesn't clear it up. – telkins Aug 22 '13 at 15:51
2

Not sure what "fair amount of data" really is, but use SQL - that's why it is here for. I do really so no excuse to not do so, knowing how really easy it is. If you never tried sqlite on android (which could explain why you want to try to avoid it :) then go thru elementary tutorial and you are really done.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
0

You can use a public class and we have to call it's method whenever we required.

example:

 SessionManager mSessionManager = new SessionManager(this);
 mSessionManager.putStringData("key", "value");   

The Class is given below:

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;


public class SessionManager {
// Shared Preferences
SharedPreferences pref;

// Editor for Shared preferences
Editor editor;

// Context
Context _context;

// Shared pref mode
int MODE_MULTI_PROCESS = 0;

// Sharedpref file name
private static final String PREF_NAME = "SharedPref_Name";

private SharedPreferences getPref() {
    return _context.getSharedPreferences(PREF_NAME, Context.MODE_MULTI_PROCESS);
}

// Constructor
public SessionManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, MODE_MULTI_PROCESS);
    editor = pref.edit();
}


/**
 * Set the String data in the preferences.
 */
public void putStringData(String keyname, String value) {
    editor.putString(keyname, value);
    editor.commit();
}

/**
 * @return the string data from the prefs
 */
public String getStringData(String keyName) {
    return pref.getString(keyName, "");
}

/**
 * Set the int data in the preferences.
 */
public void putIntData(String keyname, int value) {
    editor.putInt(keyname, value);
    editor.commit();
}

/**
 * @return the boolean data from the prefs
 */
public int getIntData(String keyName) {
    return pref.getInt(keyName, 0);
}

/**
 * Set the boolean data in the preferences.
 */
public void putBooleanData(String keyname, boolean value) {
    editor.putBoolean(keyname, value);
    editor.commit();
}

/**
 * @return the boolean data from the prefs
 */
public boolean getBooleanData(String keyName) {
    return pref.getBoolean(keyName, false);
}

/**
 * Set the long data in the preferences.
 */
public void putLongData(String keyname, long value) {
    editor.putLong(keyname, value);
    editor.commit();
}

/**
 * @return the long data from the prefs
 */
public long getLongData(String keyName) {
    return pref.getLong(keyName, 99);
}

/**
 * remove data from pref
 *
 * @param keyName
 */
public void removeData(String keyName) {
    editor.remove(keyName);
    editor.commit();
}


//Save arrayList of Model type
public void saveAssignedLocationsToSharedPrefs(List<Locations> LocationModel) {
    Gson gson = new Gson();
    String jsonLocation = gson.toJson(LocationModel);
    editor.putString("LocationArray", jsonLocation);
    editor.commit();
}

//get arrayList of Model type
public ArrayList<Locations> getAssignedLocationsFromSharedPrefs() {
    List<Locations> LocationData;

        String jsonLocation = pref.getString("LocationArray", null);
        Gson gson = new Gson();
        Locations[] LocationItems = gson.fromJson(jsonLocation,
                Locations[].class);

        LocationData = Arrays.asList(LocationItems);
        LocationData = new ArrayList<Locations>(LocationData);

    return (ArrayList<Locations>) LocationData;
}

}
Pratibha Sarode
  • 1,819
  • 17
  • 17
  • I also create the same type of class but I define the getter setter with Kotlin extension function. https://arkapp.medium.com/how-to-use-shared-preferences-the-easy-and-fastest-way-98ce2013bf51 – abdul rehman Dec 05 '20 at 10:20