Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharedPreferences per user?

I need to keep a set of preferences per user and another set of preferences for the whole app. The users are kept in a SQLite database.

I will also be using PreferenceFragment to show the preferences.

If I use getSharedPreferences() per user and one for the system, will the preference fragments show the correct preferences?

Or should I use tables in my case and either:

  1. forego the use of PreferenceFragment and write my own classes and layouts
  2. Fill one preferences file on startup based on user and system preferences stored in SQLite

What is the best practice in this case?

like image 705
Ivan-Mark Debono Avatar asked Jun 11 '26 01:06

Ivan-Mark Debono


1 Answers

You can create Multiple Preference File which have Userid associated with it along with a prefix. Like :-

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

/**
 * Created by vikas on 12/14/15.
 */
public class Pref {
    private static final String PREF_NAME = "AppName_%s";
    private SharedPreferences mPreferences;
    private String mUserId;
    private static Pref sInstance;

    private Pref(Context pContext, String pUserId) {
        mUserId = pUserId;
        mPreferences = pContext.getSharedPreferences(String.format(PREF_NAME, pUserId), Context.MODE_PRIVATE);
    }


    public String getUserId() {
        return mUserId;
    }

    public static Pref getPreferences(Context context, String userId) {
        if (null != sInstance || !TextUtils.equals(sInstance.getUserId(), userId)) {
            sInstance = new Pref(context, userId);
        }
        return sInstance;
    }

    //write methods for updating in preference files
}
like image 75
VikasGoyal Avatar answered Jun 14 '26 20:06

VikasGoyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!