初始化 SharedPreferences 给出:尝试在空对象引用上调用虚拟方法

Initializing SharedPreferences gives: Attempt to invoke virtual method on a null object reference

当我启动我的应用程序时,它崩溃并给我这个错误代码。:

Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

这是我的主activity:

package com.awplicity.testappshared;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    SharedPreferences sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Button button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private void onClick(View v) {
        switch(v.getId()) {
            case R.id.nextAct:
                editor.putString("mystring", "Hi");
                editor.commit();
                startActivity(new Intent("com.awplicity.testappshared.Main2Activity"));
                break;
        }
    }
}

这是第二个activity:

package com.awplicity.testappshared;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class Main2Activity extends AppCompatActivity {

    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        tv = (TextView) findViewById(R.id.tv_main2);
        setText();
    }

    public void setText() {
        SharedPreferences sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
        tv.setText(sharedPreferences.getString("mystring", ""));
    }
}

一般来说,您不能在 onCreate() 方法内部调用从 Activity(或子类,如 AppCompatActivity)继承的方法。到那时,事情还没有准备好。

因此,更改:

SharedPreferences sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();

至:

SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;

并初始化 onCreate() 中的那些字段:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sharedPreferences = getSharedPreferences("", Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();
}