I want to use the SharedPreferences in a Class that has no Activity. I have wrote this code but im still getting an error. Can you help me out please?
package com.example.keypass;
import android.content.Context;
import android.content.SharedPreferences;
public class test {
SharedPreferences sharedPreferences;
public void loadInt(){
sharedPreferences = this.getSharedPreferences("com.example.keypass",Context.MODE_PRIVATE);
int usrPassword = sharedPreferences.getInt("meinInteger", 0);
}
}
If I use the same code in a Class with Activity it works. But in this class is not working.
Here Maybe this help
Its a good practice making separate class file for shared prefrence
first, create a file(class) name Constants.java
public class Constants {
static Constants _instance;
Context context;
SharedPreferences sharedPref;
SharedPreferences.Editor sharedPrefEditor;
public static Constants instance(Context context) {
if (_instance == null) {
_instance = new Constants();
_instance.configSessionUtils(context);
}
return _instance;
}
public static Constants instance() {
return _instance;
}
public void configSessionUtils(Context context) {
this.context = context;
sharedPref = context.getSharedPreferences("AppPreferences", Activity.MODE_PRIVATE);
sharedPrefEditor = sharedPref.edit();
}
public void storeValueString(String key, String value) {
sharedPrefEditor.putString(key, value);
sharedPrefEditor.commit();
}
public String fetchValueString(String key) {
return sharedPref.getString(key, null);
}
}
The above code will generate an XML file inside your phone with the name AppPreferences
where you can store value in key-value pair
Now go to an activity where you want to access shared preference
Constants.instance(this.getApplicationContext());
Now when you want to store inside shared preference use like that
Constants.instance().storeValueString("companyKey", "Brainwash Inc.");
now when you want to fetch data from shared prefrence
String companyName = (Constants.instance().fetchValueString("companyKey"));
Note Its for Activity if you want to use inside fragments use getactivity() instead of getapplicationcontext()