Sorry for the title, I do not know how it would be a better way to ask.
I'm learning to program in android applications, and found a class in JAVA to make it easier to use SharedPreferences . But I did not quite understand how to use it.
I found the here code
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 did not understand why he put that example there and PrefsFile in private .
Would it 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 like this, but is that right? Only It always saves in a file named PrefsFile.xml
. If I want to separate the preferences I think I would need to modify this class. Anyone have any better ideas?