Skip to content

Instantly share code, notes, and snippets.

@shibbirweb
Last active August 23, 2020 06:24
Show Gist options
  • Select an option

  • Save shibbirweb/21959006ef0eb60462d4454bd7ffd563 to your computer and use it in GitHub Desktop.

Select an option

Save shibbirweb/21959006ef0eb60462d4454bd7ffd563 to your computer and use it in GitHub Desktop.
Android Shared Preferences Helper Class
public class ActivityOrFragment extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// usage
// save in shared preference
SharedPreferencesHelper.init(getApplicationContext(), "Shared Preference Name")
.setEditor()
.putString("key", "value")
.apply();
// retrieve from shared preference
String stringValue = SharedPreferencesHelper.init(getApplicationContext(), "Shared Preference Name")
.get()
.getString("key", null);
}
}
package com.utilities.helpers;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPreferencesHelper {
private SharedPreferences sharedPreferences;
public SharedPreferencesHelper() {
}
/**
*
* Initialize Shared Preference
*
* @param context
* @param sharedPreferenceName
*/
public SharedPreferencesHelper(Context context, String sharedPreferenceName) {
sharedPreferences = context.getSharedPreferences(sharedPreferenceName, Context.MODE_PRIVATE);
}
/**
*
* Initialize Shared Preference
*
* @param context
* @param sharedPreferenceName
* @param mode
*/
public SharedPreferencesHelper(Context context, String sharedPreferenceName, Integer mode) {
sharedPreferences = context.getSharedPreferences(sharedPreferenceName, mode);
}
/**
*
* Initialize Shared Preference from Activity or Fragment
*
* @param context
* @param sharedPreferenceName
* @return SharedPreferencesHelper
*/
public static SharedPreferencesHelper init(Context context, String sharedPreferenceName){
return new SharedPreferencesHelper(context, sharedPreferenceName);
}
/**
*
* Initialize Shared Preference from Activity or Fragment
*
* @param context
* @param sharedPreferenceName
* @param mode
* @return SharedPreferencesHelper
*/
public static SharedPreferencesHelper init(Context context, String sharedPreferenceName, Integer mode){
return new SharedPreferencesHelper(context, sharedPreferenceName, mode);
}
/**
*
* Set Editor
*
* @return SharedPreferences.Editor
*/
public SharedPreferences.Editor setEditor(){
return sharedPreferences.edit();
}
/**
* Get value from shared preference
*
* @return
*/
public SharedPreferences get(){
return sharedPreferences;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment