调用共享首选项对象时出现空指针异常

时间:2017-04-14 07:52:29

标签: android nullpointerexception sharedpreferences

编译我的代码时,我收到此错误

java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()'

我仍然无法理解为什么。对于这些错误我的应用程序崩溃。请帮助我,我无法找到我所犯的确切错误。

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences.edit()' on a null object reference
                      at com.chatbook.loki.chatbook.SessionManger.<init>(SessionManger.java:16)
                      at com.chatbook.loki.chatbook.Login.onCreate(Login.java:44)
                      at android.app.Activity.performCreate(Activity.java:6001)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368) 
Here is my code

SessionManager.java

public class SessionManger {


    SharedPreferences pref;
    SharedPreferences.Editor editor = pref.edit();
    Context _context;

    int PRIVATE_MODE = 0;
    private static final String PREF_NAME = "exmaple";

    private static final String IS_LOGIN = "IsLoggedIn";

    public static final String KEY_EMAIL = "email";

    public static final String KEY_PASSWORD = "password";

    public SessionManger(Context context){
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
        editor = pref.edit();
        editor.apply();
    }


    public void createLoginSession(String email, String password){
        editor.putBoolean(IS_LOGIN,true);
        editor.putString(KEY_EMAIL, email);
        editor.putString(KEY_PASSWORD, password);
        editor.commit();
    }

    public boolean isLoggedIn(){

        return  pref.getBoolean(IS_LOGIN,true);
    }

    public void checkLogin(){
        if(!this.isLoggedIn()){

            Intent in = new Intent(_context,Login.class);

            in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            _context.startActivity(in);
        }
    }


    public HashMap<String, String> getUserDetails(){
        HashMap<String,String> user = new HashMap<String, String>();
        user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
        user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
        return user;
    }

        public void logout(){

        editor.clear();
        editor.commit();

        Intent in = new Intent(_context,Login.class);

        in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        _context.startActivity(in);
    }
}

和我的登录活动文件

public class Login extends AppCompatActivity {
    Button b1,b2,b3;
    EditText e1,e2;
    FirebaseAuth auth;
    ProgressBar pgbar;
    SessionManger session;
    Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        auth = FirebaseAuth.getInstance();
        b1 = (Button) findViewById(R.id.logBsign);
        b2 = (Button) findViewById(R.id.logBlog);
        b3 = (Button) findViewById(R.id.logBreset);
        e1 = (EditText) findViewById(R.id.logeditemail);
        e2 = (EditText) findViewById(R.id.logeditpass);
        pgbar = (ProgressBar) findViewById(R.id.progressBar);
        session = new SessionManger(context.getApplicationContext());
    }

public void signup(View v) {
    Intent in = new Intent(Login.this, SignUp.class);
    startActivity(in);
}
public void login(View v){
    /*Intent in = new Intent(Login.this, MainActivity.class);
    startActivity(in);*/
    final String email = e1.getText().toString().trim();
    final String password = e2.getText().toString().trim();
    if(TextUtils.isEmpty(email)){
        Toast.makeText(getApplicationContext(),"Enter email address", Toast.LENGTH_SHORT).show();
        return;
    }
    if(TextUtils.isEmpty(password)){
        Toast.makeText(getApplicationContext(), "Enter password", Toast.LENGTH_SHORT).show();
        return;
    }
    pgbar.setVisibility(View.VISIBLE);
    auth.signInWithEmailAndPassword(email,password).addOnCompleteListener(Login.this, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            pgbar.setVisibility(View.GONE);
            if(!task.isSuccessful()){
                if(password.length() < 6){
                    e1.setError(getString(R.string.minimum_password));
                }else{
                    Toast.makeText(Login.this, getString(R.string.auth_failed),Toast.LENGTH_SHORT).show();

                }
            }else{

                    session.createLoginSession(email, password);
                    Intent in = new Intent(Login.this, MainActivity.class);
                    startActivity(in);
                    //finish();
            }
        }
    });
}
public  void reset(View v){
    Intent in = new Intent(Login.this, ResetPassword.class);
    startActivity(in);
}

    //To exit from App
public boolean exit = false;
@Override
public void onBackPressed() {
    if(exit){
        finish();;
    }
    else{
        Toast.makeText(this,"Press again to exit",Toast.LENGTH_SHORT).show();
        exit = true;
    }
}
}

5 个答案:

答案 0 :(得分:1)

不要

session = new SessionManger(context.getApplicationContext());

<强>不要

session = new SessionManger(Login.this);

SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;

然后

// Constructor
public SessionManager(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

答案 1 :(得分:0)

可以像下面一样编辑共享首选项,传递正确的名称

SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        Editor editor = sharedPreferences.edit();
        editor.putString(key, name);
        editor.apply();



SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        String name = sharedPreferences.getString(key, "default value");

答案 2 :(得分:0)

修复全局变量cause null

SharedPreferences.Editor editor = pref.edit();  <-- wrong pref cause null
SharedPreferences.Editor editor;  <-- just this

可选

@SuppressLint("CommitPrefEdits")
public SessionManger(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
    editor = pref.edit();
    //editor.apply(); //no need for apply 
}

答案 3 :(得分:0)

这是因为你的pref是null ... SharedPreferences pref = getApplicationContext()。getSharedPreferences(“MyPref”,MODE_PRIVATE);

答案 4 :(得分:0)

SharedPreferences pref;
SharedPreferences.Editor editor = pref.edit();

pref为null;