java.lang.NullPointerException using preferencemanager - java

Logcat error:
01-21 07:23:04.021: E/AndroidRuntime(361): Caused by: java.lang.NullPointerException }
In what i believe to be this piece of java code:
while (date.equals("01:00:00") || bSet);
int randomNumber = rand.nextInt(ids.length);
String last = ((getResources().getString(ids[randomNumber])));
tv.setText(last);
edit.putString(last, null);
edit.commit();
i have previously set up preferences as so, just before my oncreate method:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = prefs.edit();

context is not available before onCreate so you cannot use this
here:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = prefs.edit();
put this inside onCreate like:
SharedPreferences prefs;
SharedPreferences.Editor edit;
and in onCreate
prefs = PreferenceManager.getDefaultSharedPreferences(this);
edit = prefs.edit();

Related

getSharedPreferences Activity to Fragment

I'm trying to save data on Activity and read on the Fragment.
public void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(kekoyaz,mykey );
editor.apply();
Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show();
}
Load data on fragment
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
//SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
String beimtext = sharedPreferences.getString(kekoyaz, "");
Toast.makeText(getActivity(), "bu"+beimtext, Toast.LENGTH_SHORT).show();
}
But getSharedPreferences turn red on the fragment and it's suggested to create SharedPreferences method. So I did and there is no error left.
private SharedPreferences getSharedPreferences(String sharedPrefs, int modePrivate) {
return null;
}
I get error when I run the app.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.prestige.user, PID: 32516
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference
at com.prestige.user.BlankFragment.loadData(BlankFragment.java:1918)
at com.prestige.user.BlankFragment.onCreateView(BlankFragment.java:1898)
UPDATE
I removed this line
/*private SharedPreferences getSharedPreferences(String sharedPrefs, int modePrivate) {
return null;
}*/
and I use your code
public void loadData() {
getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
String beimtext = sharedPreferences.getString(kekoyaz);
Toast.makeText(getActivity(), "bu"+beimtext, Toast.LENGTH_SHORT).show();
}
I add
private ResourceBundle sharedPreferences;
But I got an error again.
After you update your question, you getSharedPreferences() with Activity but did't assign sharedPreferences variable value
Replace your code with below.
public void loadData() {
sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
String beimtext = sharedPreferences.getString(kekoyaz);
Toast.makeText(getActivity(), "bu"+beimtext, Toast.LENGTH_SHORT).show();
}
This is because getSharedPreferences need a Context.
So, you can use the following:
getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);

sharedPreferences.getString() return null

Im trying to display the user email in a textView using SharedPreferences.
Shared preferences is created in loginActivity.
I try to access it from mainActivity.
My session using sharedPreference work well (with a login boolean saved in sharedPreferences files).
So what's wrong?
- A context error?
- Because I try to access the data from an another activity?
Please help :) Thanks a lot!
Here is the code im using :
Login Activity :
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
...
//Creating a shared preference in a login()
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
editor.putString(Config.EMAIL_SHARED_PREF, email);
//Saving values to editor
editor.commit();
...
Main Activity :
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
email_session = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Private");
usernameText.setText(email_session);
}
to read the stored preferences you need to do:
to save
SharedPreferences spref = getSharedPreferences("your_prefs_name", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("myTextViewValue", prefVal); //
editor.commit();
to read it
SharedPreferences preferences = getPreferences(Activity.MODE_PRIVATE);
String storedPreference = preferences.getStr("myTextViewValue", null);
This happens because your value is not stored in the shared preferences.
SharedPreferences pref = getSharedPreferences("your Pref Name", 0) // 0 for Private Mode
String name = pref.getString("your key store when login", null); // null is the default value you can put it here "No value". then you will not get null pointer.

Can't read SharedPreferences

I'm storing some values in my PreferencesFragment in this way:
// SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
SharedPreferences prefs = getPreferenceScreen().getSharedPreferences();
SharedPreferences.Editor edit = prefs.edit();
edit.putInt(getString(R.string.valOneKey), 100);
edit.putInt(getString(R.string.valTwoKey), 200);
edit.commit();
Then, I want to read the preferences in a non activity class:
// SharedPreferences prefs = ActivityHandler.getCurrentActivity().getSharedPreferences("Test", 0);
SharedPreferences prefs = ActivityHandler.getCurrentActivity().getPreferences(0);
int valOne = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valOneKey), 0);
int valTwo = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valTwoKey), 0);
I've tried also the uncommented code, but I get always 0 for both values.
Try this
Store with SharedPreferences
SharedPreferences sharedPref = getSharedPreferences("my_pref", Context.MODE_MULTI_PROCESS);
Editor editor = sharedPref.edit();
editor.putInt("KEY", VAL);
..
..
editor.commit();
Retrieve from SharedPreferences
SharedPreferences sharedPref = getSharedPreferences(
"my_pref", Context.MODE_MULTI_PROCESS);
int size = sharedPref.getInt("KEY", default_VAL);
This will be helpful...thanks
You are doing it wrong. Each time you are getting a different shared preference. Use this code:
For storing value:
SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt(getString(R.string.valOneKey), 100);
edit.putInt(getString(R.string.valTwoKey), 200);
edit.commit();
For fetching value:
SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
int valOne = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valOneKey), 0);
int valTwo = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valTwoKey), 0);
Hope this will help you.

SharedPreferences Login

I'm trying to create something that needs to get information in the first time and save it. The app starts at the MainActivity, if it does not have the information needed, the app send you to the MotoActivity. Once the app has the information you don't need to go to the MotoActivity anymore. I know i'm wrong but I don't know how to do.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("valid", 0);
editor.commit();
int n = sp.getInt("valid", -1);
if(n == 0){
editor.putInt("valid", 1);
editor.commit();
startActivity(new Intent(MainActivity.this, MotoActivity.class));
MainActivity.this.finish();
}
First check for the very first time that, if "userLoggedBefore" is true or false from the SharedPreferences, if the user had used the application before and had entered the right credentials, we will save authenticated to true and if he hasn't we will set the default value as false.
SharedPreferences sharedPref = getSharedPreferences("Save", 0);
boolean authenticated = sharedPref.getBoolean("userLoggedBefore", false);
then check -
if (authenticated){
//show your MainActivity
} else {
// show your MotoActivity
}
in your MotoActivity,
//if credentials matches
if(credentialMatches)
SharedPreferences sharedPref = getSharedPreferences(
"Save", 0);
SharedPreferences.Editor prefEditor = sharedPref
.edit();
prefEditor.putBoolean("userLoggedBefore", true);
prefEditor.commit();
else{ // if credentials doesn't match
SharedPreferences sharedPref = getSharedPreferences("Save", 0);
SharedPreferences.Editor prefEditor = sharedPref
.edit();
prefEditor.putBoolean("userLoggedBefore", false);
prefEditor.commit();
}
Try this:
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
// app already has the needed info.
if(sp.getInt("valid", -1) == 1){
// do something
}
// app needs info. first, when you have got the info. in MotoActivity then set preferences key 'valid' to 1
else{
startActivity(new Intent(MainActivity.this, MotoActivity.class));
finish();
}

SharedPreferences not working as expected, cannot read nor write preferences

private void init() {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
// SET VALUE RECORD
record = prefs.getInt("record", 0);
prefs.edit().commit();
}
private void setRecord(int i ) {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
if(i > prefs.getInt("record", 0))
prefs.edit().putInt("record", i);
prefs.edit().commit();
}
private int getRecord() {
int rec;
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
rec = prefs.getInt("record", 0);
prefs.edit().commit();
Toast toast = Toast.makeText(this, rec+"", Toast.LENGTH_SHORT);
toast.show();
return rec;
}
this code should set an int and retrieve it, but it doesn't seem to ever set it... can you see why is that?
Think it is best to call the interface SharedPreferences.Editor to edit preferences instead of using prefs.edit().putInt("record", i);. The docs say...
Modifications to the preferences must go through an
SharedPreferences.Editor object to ensure the preference values remain
in a consistent state and control when they are committed to storage.
If you change your setMethod to the following it should work...
private void setRecord(int i ) {
SharedPreferences prefs = getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if(i > prefs.getInt("record", 0))
editor.putInt("record", i);
editor.commit();
}
And I guess you are calling the above method setRecord somewhere in your code as I can't see it being called anywhere in the code snippet you pasted.
try
Editor editor = prefs.edit();
editor.putInt("record",i);
editor.commit();

Categories

Resources