1
Sorry about the title, I don’t know how else would be a better way to ask.
I’m learning to code on android apps, and I found a JAVA class to facilitate the use of Sharedpreferences. But I don’t quite understand how to use.
I found the code here.
And the code is this:
import android.content.Context;
import android.content.SharedPreferences;
/**
* Copyright (C) 2016 Mikhael LOPEZ
* Licensed under the Apache License Version 2.0
* Utility class for the SharedPreferences management
*/
public class SharedPreferencesUtils {
// PUBLIC PREF NAME
public static final String PREFS_EXAMPLE = "example";
//region Singleton Shared Preferences
private static final String PREFS_FILE_NAME = "PrefsFile";
private static SharedPreferences mSharedPreferences;
private static SharedPreferences getSharedPreferencesEditor(Context context) {
if (mSharedPreferences == null) {
mSharedPreferences = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE);
}
return mSharedPreferences;
}
//endregion
public static void setString(Context context, String name, String value) {
SharedPreferences.Editor editor = getSharedPreferencesEditor(context).edit();
editor.putString(name, value);
editor.commit();
}
public static String getString(Context context, String name) {
return getSharedPreferencesEditor(context).getString(name, null);
}
public static void remove(Context context, String name) {
getSharedPreferencesEditor(context).edit().remove(name).commit();
}
}
I don’t understand why he put that example there and the Prefsfile in private.
It would be better to increment this code to change this data with a constructor?
I’m using it this way for now:
SharedPreferencesUtils.setString(getApplicationContext(), "userLogged", varuserlogged);
and
UsernameLogged = SharedPreferencesUtils.getString(getApplicationContext(),"userLogged");
It’s working that way, but is that right? Just that it always saves in a file called PrefsFile.xml
. If I want to separate preferences I think I would need to modify this class. Does anyone have a better idea?
You don’t understand my question, young man, I’m talking about this line here:
private static final String PREFS_FILE_NAME = "PrefsFile";
be in private, because it requires all preferences to be only in a single file.– Samanta Silva
and on these lines
public static final String PREFS_EXAMPLE = "example";
I don’t understand her usefulness in the code. And tbm about a way to make this class look better to use, and if I’m using it right. About Sharedpreferences I already know how to use, and MODE_PRIVATE as well. Still thanks for responding.– Samanta Silva
updated the response
– Caique Oliveira