从其他活动中读取SharedPreferences

时间:2019-06-11 21:27:22

标签: java android sharedpreferences

我正在尝试将值从一类传递到另一类,但是我的sharedpreferences上下文可能无法正常工作,当我初始化共享首选项时,我得到了NullPointerExcepiton吗?我应该将上下文更改为什么?

CustomOnItemSelected.java :(初始化sharedpref)

 public class CustomOnItemSelectedListener extends Activity implements AdapterView.OnItemSelectedListener {

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    Toast.makeText(parent.getContext(),
            "Wybrano : " + parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();

    SharedPreferences preferences = getSharedPreferences("session", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("sessionId", parent.getItemAtPosition(position).toString());
    editor.commit();
}

tworzeniekonta.java :(正在读取sharedpref)

       TextView tv6 = findViewById(R.id.textView6);
    SharedPreferences preferences = getSharedPreferences("session", CustomOnItemSelectedListener.MODE_PRIVATE);
    String sessionId = preferences.getString("sessionId", null);
    tv6.setText(sessionId);

空指针异常:

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

1 个答案:

答案 0 :(得分:0)

您将SharedPreferences preferences = getSharedPreferences("session", CustomOnItemSelectedListener.MODE_PRIVATE);放在哪里?创建活动后尝试调用此方法。首选项应在onCreate()中初始化。 例如:

public class MainActivity extends AppCompatActivity {

   TextView tv6 = findViewById(R.id.textView6);
   SharedPreferences sharedPreferences;

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

      sharedPreferences = getSharedPreferences("session", Context.MODE_PRIVATE);
      String sessionId = preferences.getString("sessionId", null);
      tv6.setText(sessionId);
   }

}