Reputation: 67
I am using this code to save string:
public class MySharedPref {
private static final String APP_SHARED_PREFS = "TripDetails";
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public MySharedPref(Context activity) {
this.appSharedPrefs = activity.getSharedPreferences(APP_SHARED_PREFS,
Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public String getPrefsValue(String value) {
return appSharedPrefs.getString(value, "");
}
public void savePrefsValue(String key, String Value) {
prefsEditor.putString(key, Value);
prefsEditor.commit();
}
public String getImei(String value) {
return appSharedPrefs.getString(value, "");
}
public void saveImei(String key, String Value) {
prefsEditor.putString(key, Value);
prefsEditor.commit();
}
public Boolean checkKey(String Key) {
if (appSharedPrefs.contains(Key))
return true;
else
return false;
}
}
and calling with:
MySharedPref mySharedPref = new MySharedPref(context);
mySharedPref.saveImei("Imei", Imei);
but within a handler. I am getting null pointer Exception. I am not getting the reason, Why it is so. Please Help.
logcat:
java.lang.NullPointerException
09-15 11:46:52.213: W/System.err(17575): at com.example.util.MySharedPref.<init>(MySharedPref.java:14)
09-15 11:46:52.215: W/System.err(17575): at com.example.util.SerialRecieveThread.handleWaitBuffer(SerialThread.java:273)
09-15 11:46:52.216: W/System.err(17575): at com.example.util.SerialRecieveThread.step(SerialThread.java:612)
09-15 11:46:52.219: W/System.err(17575): at com.example.util.SerialRecieveThread.run(SerialThread.java:172)
09-15 11:46:52.220: W/System.err(17575): at java.lang.Thread.run(Thread.java:841)
Upvotes: 1
Views: 1458
Reputation: 26034
Use following way
Step 1
Create an Application class
public class MyApplication extends Application{
private static Context context;
public void onCreate(){
super.onCreate();
MyApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MyApplication.context;
}
}
Step 2
In Android Manifest file declare following
<application android:name="com.xyz.MyApplication">
</application>
Step 3
MySharedPref mySharedPref = new MySharedPref(MyApplication.getAppContext());
mySharedPref.saveImei("Imei", Imei);
Upvotes: 1