(REMOVED THE OLD CONTENT OF THE POST)
EDIT #2: Okay, so now I am crystal clear that it is the editor trying to reach the preference that causes the nullpointerexception. Any help here on how to fix it?
Here is the updated activity:
public SharedPreferences sharedPreferences;
Editor editor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requesting to turn the title OFF
requestWindowFeature(Window.FEATURE_NO_TITLE);
// making it full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
// set our MainGamePanel as the View
setContentView(new MainGamePanel(this));
// Restore preferences
this.sharedPreferences = getPreferences(MODE_PRIVATE);
this.editor = sharedPreferences.edit();
try {
int wins = GetPreferences("wins");
int fails = GetPreferences("fails");
gamePanel.winn = wins;
gamePanel.failn = fails;
} catch (NullPointerException npe) {
Log.d(TAG, "Nothing to load");
}
//INIT SOUND
mSoundManager.initSounds(getBaseContext());
//SOUNDS
mSoundManager.addSound(1, R.raw.draw);
mSoundManager.addSound(2, R.raw.cheer);
mSoundManager.addSound(3, R.raw.boo);
}
#SuppressWarnings("deprecation")
#Override
public void onBackPressed()
{
super.onBackPressed();
if (gamePanel.gamei==true) {
gamePanel.back();
} else if (gamePanel.menui==true) {
finish();
System.runFinalizersOnExit(true);
System.exit(0);
}
}
public void onPause()
{
super.onPause();
//KILL ALL
finish();
System.runFinalizersOnExit(true);
System.exit(0);
}
#Override
protected void onStop(){
super.onStop();
//KILL ALL
finish();
System.runFinalizersOnExit(true);
System.exit(0);
}
public int GetPreferences(String key) {
return sharedPreferences.getInt(key, 0);
}
public void SavePreferences(String key, int value) {
editor.putInt(key, value);
editor.apply();
}
public void writeWin () {
SavePreferences("wins", gamePanel.winn);
}
public void writeFail () {
SavePreferences("fails", gamePanel.failn);
}
The editor is what is causing the nullpointerexception: this.editor = sharedPreferences.edit();. EDIT: It's the sharedPreferences that is causing the nullpointerexception, not the editor.
It seems like the editor cannot reach the Preference: this.sharedPreferences = getPreferences(MODE_PRIVATE);.
Any idea on how to fix this?
It look like the declaration
Editor editor;
should be
SharedPreferences.Editor editor;
I finally got it fixed by using a listener! It apparantely was the gamePanel that was null inside of the activity. Go here for more information:
nullpointerexception when trying to reach activity
Related
I have a Floating Action Button in my layout. Users can choose the position of this button, left or right. This can be selected in the preferences.
The code to do this works OK, but a change in the preference is not detected by the listener.
If the app is restarted, the Floating Action Button is displayed according to the new preference, so I know the process with this preference works, but unfortunately the listener seems to fail.
What do I have to do to get the listener firing when the preference has changed?
Listener in my MainActivity:
private final SharedPreferences.OnSharedPreferenceChangeListener
mPositionFabListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.e(TAG,"Are we getting here?");
// We do not get here when preference has changed. Why not??
// Code to update Floating Action Button to new position
}
};
I register the listener in the onResume() method of the MainActivity and unregister in the onPause().
#Override
protected void onResume() {
super.onResume();
PrefUtils.registerOnPrefChangeListener(mPositionFabListener);
}
#Override
protected void onPause() {
PrefUtils.unregisterOnPrefChangeListener(mPositionFabListener);
super.onPause();
}
The registerOnPrefChangeListener method is declared in a seperate class:
public class PrefUtils {
public static boolean getBoolean(String key, boolean defValue) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext());
return settings.getBoolean(key, defValue);
}
public static void putBoolean(String key, boolean value) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit();
editor.putBoolean(key, value);
editor.apply();
}
public static int getInt(String key, int defValue) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext());
return settings.getInt(key, defValue);
}
public static void putInt(String key, int value) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit();
editor.putInt(key, value);
editor.apply();
}
public static void registerOnPrefChangeListener(OnSharedPreferenceChangeListener listener) {
try {
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).registerOnSharedPreferenceChangeListener(listener);
} catch (Exception ignored) {}
}
public static void unregisterOnPrefChangeListener(OnSharedPreferenceChangeListener listener) {
try {
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).unregisterOnSharedPreferenceChangeListener(listener);
} catch (Exception ignored) {}
}
}
UPDATE:
In the GeneralPrefsFragment class I put in this listener for testing purposes. This listener is working. So why does it not work in the MainActivity?
public class GeneralPrefsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Preference preference = findPreference(PrefUtils.POSITION_FLOATING_MENU_BUTTON);
Preference.OnPreferenceChangeListener mListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
PrefUtils.putBoolean(PrefUtils.POSITION_FLOATING_MENU_BUTTON, Boolean.TRUE.equals(newValue));
PreferenceManager.getDefaultSharedPreferences(MainApplication.getContext()).edit().commit(); // to be sure all prefs are written
Log.e(TAG, "The listener in " + TAG + " is listening");
// This listener is fired as soon as changes in the preference are made!
// Why is the same kind of listener not fired in the MainActivity?
return true;
}
};
preference.setOnPreferenceChangeListener(mListener);
}
}
SOLUTION:
I got a fix. I still do not know why the former setup didn't work, but I got it working, thanks to the code in this answer.
In the MainAcivity's onCreate() method I placed the following listener and this one gets triggered when the preferences have changed.
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.OnSharedPreferenceChangeListener mPrefsFabListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (PrefUtils.POSITION_FLOATING_MENU_BUTTON.equals(key)) {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
CoordinatorLayout.LayoutParams paramsFab = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
if (PrefUtils.getBoolean(PrefUtils.POSITION_FLOATING_MENU_BUTTON, false)) {
paramsFab.gravity = Gravity.BOTTOM | Gravity.START;
} else {
paramsFab.gravity = Gravity.BOTTOM | Gravity.END;
}
}
}
};
prefs.registerOnSharedPreferenceChangeListener(mPrefsFabListener);
The OnSharedPreferenceChangeListener gets unregistered in the onPause() method of the MainAcitivity. That is a problem, because the MainActivity gets paused as soon as the General Preferences Activity is started in order to change the preferences. So, the listener is unregistered and therefore not listening right at the point where it is needed!
I removed the unregisterOnPrefChangeListener from the onPause() and put in the following code. This worked perfectly!
#Override
protected void onDestroy() {
PrefUtils.unregisterOnPrefChangeListener(mPositionFabListener);
super.onDestroy();
}
How do I keep button Visibility when returning from another activity?
My Code:
#Override
protected void onStop() {
super.onStop();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
SharedPreferences.Editor edit = btVis.edit();
edit.putString("btS1",btSub1.getVisibility()+"");
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
int btS1 = Integer.parseInt("View." +btVis.getString("btS1",""));
btSub1.setVisibility(btS1);
}
I get an error cause setVisibility needs to be in format View.(VISIBILITY) for example. But I parsed btS1 as an int in the format View.(VISIBILITY) so I dont know why it doesn't work. How do I fix this?
You forgot to call editor.commit(); which means your int was never actually saved.
#Override
protected void onStop() {
super.onStop();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
SharedPreferences.Editor edit = btVis.edit();
edit.putString("btS1",btSub1.getVisibility()+"");
editor.commit();
}
Edit:
I see you also did something wrong
int btS1 = Integer.parseInt("View." +btVis.getString("btS1",""));
While you do get the id via the class View, you don't need to get it from your shared prefs that way. You already just stored the Integer that is referred to in View.GONE and View.Visisble.
To make this work you just need:
int btS1 = Integer.parseInt(btVis.getString("btS1",""));
But I don't see why you would parse it to a String and then parse it back to an int. Also I would do the saving on OnPause instead of OnStop. So completely reworked you should do this:
#Override
protected void onPause() {
super.onPause();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS, 0);
SharedPreferences.Editor edit = btVis.edit();
edit.putInt("btS1", btSub1.getVisibility());
edit.commit();
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS, 0);
int btS1 = btVis.getInt("btS1", 0);
btSub1.setVisibility(btS1);
}
try this one in onResume() method.
#Override
protected void onResume() {
super.onResume();
SharedPreferences btVis = getSharedPreferences(BUTT_VIS,0);
int visibility = Integer.parseInt(btVis.getString("btS1",""));
switch(visibility){
case View.VISIBLE: //make button visible
break;
case View.INVISIBLE: //make button invisible
break;
}
}
Make sure to commit editor at the end of onStop() method
I have a method to validate a EditTextPreference. My method is executed after the confirmation of data by implementing the onSharedPreferenceChanged class.
However, only occurs after you confirm the information. I would perform the check without closing the dialog box. And if ok then close or keep open for user to enter the data correctly.
If it's not possible, I would reopen the dialog box if the validation is false.
SettingsActivity.java
class SettingsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
protected static final String TAG = "SettingsActivity";
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
SharedPreferences.Editor prefEditor = prefs.edit();
if(key.equals("pref_Url")){
String url = prefs.getString(key, "");
boolean response = (!new ConnectUtils().isConnected(this, url));
if(!response){
prefEditor.putString(key, Config.SERVER_URL_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(this,R.string.msgToast_server_url_invalid,Toast.LENGTH_SHORT).show();
}
}else if (key.equals("pref_Id")){
String url = Config.SERVER_URL_ID;
boolean reponse = (!new ConnectUtils().isConnected(this,url));
if(!reponse){
prefEditor.putString(key,Config.ID_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(Config.getContext(), R.string.msgToast_Id_invalid, Toast.LENGTH_SHORT).show();
}
}
}
private void reload(){
startActivity(getIntent());
finish();
}
}
'onPreferenceChangeListener' is a listener that is executed every time a preference is changed by the user. You can return true if data complains validation or false otherwise.
For example:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
findPreference("pre_mail").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return Pattern.matches(Constants.MAILPATTERN, (String) newValue);
}
});
}
}
Hope this help!
I want to save 2 variable when application stopped and I want to use these variables when application restarted.I'm using sharedpreferences but I couldnt solve.
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
for(int k=0;k<=secili.length;k++){
if(secili[k]!=0)
cevapdizisi[k]=secili[k];
}
for(int m=100;m>=0;m--){
if(m!=0){
sonsoru=m;
break;
}
in onStop there isnt problem
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
setContentView(R.layout.answerpage);
txtquestion.setText(questions[sonsoru]);
rdiogroup.check(secili[sonsoru]);
}
in onRestart can't accessing txtquestion and rdiogroup.I'm created them on OnCreate.What should I do.I cant created them again onRestart.it will absurd.there must be another way.I need a help
To store values in shared preferences you may use following code:
public class MainActivity extends Activity{
SharedPreferences prefs;
EditText edTextName,edTextPassword,edTextServer;
protected void onCreate(Bundle arg0) {
.
.
//do your stuff...
.
prefs= this.getSharedPreferences("UserInfo", MODE_PRIVATE);
String hostname = prefs.getString("HostName", null);
String name = prefs.getString("UserName", null);
String password = prefs.getString("Password", null);
}
protected void onStop() {
.
//do your stuff...
.
SharedPreferences.Editor editor = prefs.edit();
editor.putString("HostName", edTextName.getText().toString());
editor.putString("UserName", edTextPassword.getText().toString());
editor.putString("Password", edTextServer.getText().toString());
editor.commit();
}
}
From last one week I am facing a strange problem with saved preferences.
I am working on a board which is android compatable.
The actual problem i am facing is,
I have 4 buttons and on the button click I am changing the background images of the button
Onfirstclick -> change the background image of the button to highlited -> second click ->change to normal background image and on first run I am keeping the normal background button image
but on reboot the button background images are not getting saved in my working board though I am using shared preferences.
I have a power button for on and off with which I am rebooting my board.
whatever Image(normal/highlited) I have in onclick that image I should get after rebooting the board
The good thing is that
the code is working perfectly in android mobile but not in my board
this is my code.
Any help is always appreciated.
public class SharedprefsActivity extends Activity {
protected static final String TAG = "HvacActivity";
/** Called when the activity is first created. */
private Button seatdirnbtn;
private SharedPreferences prefs;
private String prefName = "MyPref";
private SharedPreferences.Editor editor;
private boolean isclick;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
seatdirnbtn = (Button) findViewById(R.id.seatdirnbtn);
seatdirnbtn.setOnClickListener(listner1);
}
public void onResume() {
super.onResume();
getPrefAndButtonState();
}
public void onPause() {
super.onPause();
setPrefAndButtonState();
}
#Override
public void onRestart() {
super.onRestart();
getPrefAndButtonState();
}
#Override
public void onStop() {
super.onStop();
setPrefAndButtonState();
}
public void getPrefAndButtonState(){
prefs = this.getSharedPreferences(prefName, MODE_PRIVATE);
isclick = prefs.getBoolean("prefName", false);
System.out.println("bool? " + isclick);
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else if (!isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
}
public void setPrefAndButtonState(){
editor = prefs.edit();
editor.putBoolean("prefName", isclick);
editor.commit();
getPrefAndButtonState();
}
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
isclick = false;
setPrefAndButtonState();
} else if (!isclick) {
isclick = true;
setPrefAndButtonState();
}
}
};
}
try using getApplicationContext() instead of this as:
in setPrefAndButtonState method :
public void setPrefAndButtonState(){
prefs = getApplicationContext().
getSharedPreferences(prefName, MODE_PRIVATE); <<missing this line
editor = prefs.edit();
editor.putBoolean("prefName", isclick);
editor.commit();
getPrefAndButtonState();
}
and in getPrefAndButtonState method
public void getPrefAndButtonState(){
prefs = getApplicationContext().getSharedPreferences(prefName, MODE_PRIVATE);
isclick = prefs.getBoolean("prefName", false);
System.out.println("bool? " + isclick);
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else if (!isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
}