I have a class A this class does not extend or implement any other classes. I then have an Class B, this class also does not extend or implement any other classes.
My Class B is solely used to manage SharedPreferences :
private static SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
Here is the problem method in Class B:
public static void setCurrentUsersEmail(String email){
sharedPreferences.edit().putString("userEmail",email).commit();
}
Now class A is a database manager and needs to store the users email in SharedPreferences for later use. I do this with the following code:`
MySharedPrefs.setCurrentUsersEmail(currentUsersEmail);
However, when i try run the code in Class A i get the error:
java.lang.ExceptionInInitializerError
at com.test.Android.MySharedPrefs.setCurrentUsersEmail(MySharedPrefs.java:0)
I am really confused as to why this happens I couldn't find a solution online after searching either, I use my sharedPreferences class in other activities perfectly fine. Is it an activity problem?
Any help is much appreciated.
You can use singleton for your requirement :
public class MyPrefs {
private static MyPrefs myPrefs;
private SharedPreferences sharedPreferences;
private MyPrefs(Context context){
sharedPreferences=context.getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
}
public static MyPrefs getInstance(Context context){
if(myPrefs==null)
myPrefs=new MyPrefs(context);
return myPrefs;
}
public void setCurrentUsersEmail(String email){
sharedPreferences.edit().putString("userEmail",email).commit();
}
}
You can put email in this way :
MyPrefs.getInstance(context).setCurrentUsersEmail(currentUsersEmail);
You need to pass context at first time for the reference of sharedPreferences in your Class.
or
From Activity call MyPrefs.getInstance(context) at once
Then you can call without context
MyPrefs.getInstance().setCurrentUsersEmail(currentUsersEmail);
getInstance() method :
public static MyPrefs getInstance(){
if(myPrefs==null) throw new AssertionError("MyPrefs cannot be null");
else
return myPrefs;
}
You could do this , in any activity, dont need to create a new method:
To save:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("email", "YOURUSEREMAIL#.email");
editor.commit();
To restore:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("email", null);
You cant call MyPrefs.aFunctionYouCreated() !!!
Related
This is in my main activity class, I can pass and retrieve data in my other class through shared preferences but I cant clear the shared preferences in my other class. Also tell me how to check that my shared preferences are cleared.
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "userKey";
public static final String Pass = "passKey";
sharedPreferences=getApplicationContext().getSharedPreferences(MyPREFERENCES,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name,userName);
editor.putString(Pass,password);
editor.commit();
this is in my other class
SharedPreferences sharedPreferences;
sharedPreferences=getApplicationContext().getSharedPreferences(SignUPActivity.MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
editor.commit();
Hi if you want just pass value from one Activity to Another or One Fragment to other than I suggest you to use INTENT to pass data
Look at this example how to pass -http://startandroid.ru/en/lessons/241-lesson-28-extras-passing-data-using-intent.html
Also -https://stackoverflow.com/a/30166602/4741746
sharedPreferences is used when data used for all activity which is permanatly stored in application you also can clear data
Remove given String from shearedPrefrance
public static void removeFromSharedPreferences(Context mContext, String key) {
if (mContext != null) {
SharedPreferences mSharedPreferences = mContext.getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, 0);
if (mSharedPreferences != null)
mSharedPreferences.edit().remove(key).commit();
}
}
Remove All value from SharedPrefrance
public static void removeSharedPreferences(Context mContext) {
if (mContext != null) {
SharedPreferences preferences = mContext.getSharedPreferences("PREFERENCE", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
}
}
And why your code is not working is you have to passs Context.MODE_PRIVATE insted MODE_PRIVATE jsut confirm both should have same value
Put this code in both the classes
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Possible Reason is you are not using the same preferences.
In your first activity you are using:
sharedPreferences = getApplicationContext()
.getSharedPreferences(MyPREFERENCES,MODE_PRIVATE);
And in the other activity you should also use it.
Try to read these
http://developer.android.com/reference/android/app/Activity.html
also from the docs
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity. This simply calls the underlying
getSharedPreferences(String, int) method by passing in this activity's
class name as the preferences name.
I am new to android..and I'm developing an application using Json. I want to pass a string value from my main activity to another class without starting the activity class. I heard there is some way using shared preferences. I just tried.. but didn't worked..i got null point exception.. here is my code...
confirm = check.AuthenticateUser(name, passwd);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name",confirm);
editor.commit();
here is the place i want to send the value of "confirm" (string variable)
and below code shows where i want to get that preference..actually that class named "ShortList".
here is the code where i trying to get the value
public class ShortList extends Activity {
//ArrayList<HashMap<String, String>> arl;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String cargivr = preferences.getString("Name","");
please some one help me..
public static String CREDENTIALS_FILENAME = "com.myapp.credentials";
public static String PIN = "pin";
public static void writeCredentials(Context c,String pin) {
SharedPreferences credentialsPref = c.getSharedPreferences(CREDENTIALS_FILENAME, 0);
SharedPreferences.Editor editor = credentialsPref.edit();
editor.putString(PIN, pin);
editor.commit();
}
public static String readCredentials(Context c,String pin) {
SharedPreferences credentialsPref = c.getSharedPreferences(CREDENTIALS_FILENAME, 0);
SharedPreferences.Editor editor = credentialsPref.edit();
return credentialsPref.getString(PIN, "default value");
}
MainActivity.java
SharedPreferences pref = getApplicationContext().getSharedPreferences("New",Context.MODE_PRIVATE);
Editor edit = pref.edit();
edit.putString("SomeKey", "SomeValue");
edit.commit();
SecondActivity.java
SharedPreferences prefs = getApplicationContext().getSharedPreferences("New",Context.MODE_PRIVATE);
String value = prefs.getString("SomeKey","DefaultValue");
Also make sure that you have added the second activity details in your android manifest file -
<activity
android:name="com.example.projectName.SecondActivity"
android:parentActivityName="com.example.sharedpref.MainActivity">
</activity>
public class ShortList extends Activity {
//ArrayList<HashMap<String, String>> arl;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String cargivr = preferences.getString("Name","");
Here it seems you're initializing member variables.
You cannot use an Activity as a Context until onCreate() in the activity lifecycle. Member variable initialization is too early and will usually lead to NPE in getBaseContext().
Move the initialization of preferences and cargivr to onCreate() or later.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ShortList.this);
String cargivr = preferences.getString("Name","");
I'm building an android project that contains SharedPreferences.
My SharedPreferences works fine and I tested it in mutiple activity. but in a class that I defined for global variables, defining that SharedPreferences will cause force close (eclipse didn't show any error in codes).
public class Globals extends Application {
final SharedPreferences s = getSharedPreferences("Prefs", MODE_PRIVATE);
}
What is the problem ?
You should pass the Context and use
SharedPreferences prefs = Context.getSharedPreferences(
"Prefs", Context.MODE_PRIVATE);
Create a constructor and pass a Context variable as a parameter. Any activity that want to use this preference then you have to pass the activity. Here's the code given below:
public class Globals extends Application {
private Context context;
public Globals (Context context) {
this.context = context;
}
SharedPreferences myPref = context.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
}
You can't run getSharedPreferences() in the actual class. Everything you do must be in the Application's onCreate method. If you try to run this in the class, it will fail since it has not been initialized yet. Think of it almost as an activity, since both the activity and the application have a lifecycle.
Try the following:
public class Globals extends Application {
#Override
public void onCreate() {
super.onCreate();
final SharedPreferences s = getSharedPreferences("Prefs", MODE_PRIVATE);
}
}
I have SharedPreferences in main activity like this :
public class MainActivity extends SherlockFragmentActivity {
public void showUserSettings() {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
Editor editor= sharedPrefs.edit();
editor.putString("userFormat", sharedPrefs.getString("example_list", "2"));
editor.commit();
}
now I wanna get value from SharedPreferences but in bellow class :
public class ReadFormatSharePerf extends Activity {
private DecimalFormat df;
public String finalFormat(String finalFormat) {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
String customFormat = sharedPrefs.getString("userFormat", "#.##");
df = new DecimalFormat(customFormat);
String result = df.format(finalFormat);
return result;
}
I called above activity like this code :
public class Angles {
...
...
ReadFormatSharePerf my= new ReadFormatSharePerf();
result=my.finalFormat(String.valueOf(finalValue));
}
I caught error :
10-16 15:57:24.035: E/AndroidRuntime(10792): java.lang.NullPointerException
atandroid.content.ContextWrapper.getApplicationContext(ContextWrapper.java:101)
how I can do it ?
You should not be instantiating your Activity objects with new. Instead, either make the class not inherit from Activity, or instantiate it via Intent.
The NPE comes from trying to use an Activity as a Context before its onCreate() i.e. in a constructor or a member variable initializer. If you're using the Intent-based instantation, move the code that requires a Context to onCreate() or later in the activity lifecycle. If you make the class not an Activity, pass in a Context reference from caller.
Instead, do:
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
This code snippet will help you and Shared Preference KEY values must be same
Saving the values
SharedPreferences preferences = getSharedPreferences("MY_SHARED_PREF",0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(String.valueOf(key), value);//store int values, can use string,arrays,etc
editor.commit();
Try to use this
Load the saved values
SharedPreferences getProgramPrefs = this.getSharedPreferences(
"MY_SHARED_PREF", MODE_WORLD_READABLE);
int Index = getProgramPrefs.getInt(String.valueOf(key), -1);
Using shared preferences I saved data in one of the activity Now I want to use that data in another activity how to do that?
Create a sharedPreference where you want to add shared data. A little example of code like this:
SharedPreferences prefs = this.getSharedPreferences("CONSTANT_FILE_NAME",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("isPaid", true);
editor.commit();
And to retrieve that shared data use this code:
SharedPreferences prefs = this.getSharedPreferences("CONSTANT_FILE_NAME",
Context.MODE_PRIVATE);
prefs.getBoolean("isPaid",false);
Read this from developer site: click here
PREFS_NAME is the value you stored in shared preference.
public static final String PREFS_NAME = "MyPrefsFile";
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false)
Look at Restoring preferences
Edited:To use it among all classes i.e. setter getter method.Perfect use of OOPS.You can call the value from any class thats 1-line job
Make a normal class name as ReturningClass.
public class ReturningClass {
private static String MY_STRING_PREF = "mystringpref";
private static String MY_INT_PREF = "shareduserid";
public static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences("UserNameAcrossApplication", context.MODE_PRIVATE);
}
public static String getMyStringPref(Context context) {
return getPrefs(context).getString(MY_STRING_PREF, "default");
}
public static int getMyIntPref(Context context) {
return getPrefs(context).getInt(MY_INT_PREF, 0);
}
public static void setMyStringPref(Context context, String value) {
// perform validation etc..
getPrefs(context).edit().putString(MY_STRING_PREF, value).commit();
}
public static void setMyIntPref(Context context, int value) {
// perform validation etc..
getPrefs(context).edit().putInt(MY_INT_PREF, value).commit();
}
Set your value by calling
ReturningClass.setMyIntPref(mContext,22);
Once You have set your sharedPreference.Then just call this method.Just pass the context.from your class
int usersharedpreference=ReturningClass.getMyIntPref(mContext);
This link can help you.
Unable to use shared preference values in class A extends BroadcastReceiver , Android
also
http://saigeethamn.blogspot.in/2009/10/shared-preferences-android-developer.html
//decleration
SharedPreferences saveWord;
//onCreate
saveWord=PreferenceManager.getDefaultSharedPreferences(ActivityName.this);
String word=saveWord.getBoolean(PREFS_NAME, false);