当我启动我的应用程序时,它只是崩溃并给我这个错误代码。:
尝试在空对象引用上调用虚方法'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String,int)'
这对我来说都很新鲜,所以请帮帮我。
这是我的主要活动
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;
}
}
}
这是第二项活动
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", ""));
}
}
答案 0 :(得分:9)
一般来说,在Activity
方法内部之前,您无法调用从AppCompatActivity
(或子类,如onCreate()
)继承的方法。在此之前,事情尚未确定。
因此,改变:
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();
}