Note that there are some explanatory texts on larger screens.

plurals
  1. POSharedPreferences troublesome nullpointerexception
    primarykey
    data
    text
    <p>(REMOVED THE OLD CONTENT OF THE POST)</p> <p>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?</p> <p>Here is the updated activity:</p> <pre><code> 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); } </code></pre> <p><em>The editor is what is causing the nullpointerexception: <code>this.editor = sharedPreferences.edit();</code>.</em> EDIT: It's the sharedPreferences that is causing the nullpointerexception, not the editor.</p> <p>It seems like the editor cannot reach the Preference: <code>this.sharedPreferences = getPreferences(MODE_PRIVATE);</code>.</p> <p>Any idea on how to fix this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload