CtheW
CtheW

Reputation: 59

Declaring SharedPreferences.Editor crashes my app

// I declared myPrefs globally in the lass  
SharedPreferences myPrefs = null;

// this is called in my do draw function

public void doDraw() {
myPrefs = this.getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE); SharedPreferences.Editor editor = myPrefs.edit();
editor.putInt("MYHIGHSCORE", score); editor.commit();
}

Whenever I call SharedPreferences.Editor editor = myPrefs.edit();, my program crashes. What I'm doing wrong? I'm trying to store an int for a high score system. And SharedPreferences was suggested a lot for a mini high score system like mine.

Upvotes: 2

Views: 1173

Answers (3)

MysticMagicϡ
MysticMagicϡ

Reputation: 28823

Edit:

package com.example.logindemo;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class LoginPage extends Activity {

    EditText name = null, pwd = null;
    SharedPreferences login_pref = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_page);
        name = (EditText) findViewById(R.id.name_edt);
        pwd = (EditText) findViewById(R.id.pwd_edt);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_login_page, menu);
        return true;
    }

    public void loginMethod(View v) {
        login_pref = this.getSharedPreferences("login_pref",
                MODE_WORLD_READABLE);
        SharedPreferences.Editor login_pref_editor = login_pref.edit();
        login_pref_editor.putString("Name", name.getText().toString());

        login_pref_editor.commit();
        startActivity(new Intent(this, WelcomeScreen.class));
    }
}

Try this. I think your shared pref object was not fetched properly. Note: Edited post to add whole class's code.

Upvotes: 1

Lawrence Choy
Lawrence Choy

Reputation: 6108

If you intend to have only one preference file, try to use this code to retrieve the SharedPreference.

myPrefs = PreferenceManager.getDefaultSharedPreferences(this);

Upvotes: 1

PC.
PC.

Reputation: 7024

I guess the problem is not at edit() but when u apply() your changes. Look at the solution here

Upvotes: 0

Related Questions