我正在开发我的第一个Android应用程序,我的主要活动有一个微调器,当用户在登陆屏幕或活动之后运行应用程序将是另一个(不是主要的)。我将选择器从微调器存储在共享的优先级中,如果设置了这个,我想在启动时加载不同的活动。
代码
private Spinner spinner;
private SharedPreferences favTeam;
//private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
if (favTeam.contains("team") && favTeam != null) {
Intent intent = new Intent(this, MyTeamActivity.class);
startActivity(intent);
} else {
System.out.println("-------- cant read from shared pref -----------");
}
*/
spinner = (Spinner) findViewById(R.id.selectTeam);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.teams_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
public void submitMyTeam(View v){
favTeam = this.getSharedPreferences("com.lonerganonline.league_of_ireland", Context.MODE_PRIVATE);
//SharedPreferences favTeam = this.getSharedPreferences("com.lonerganonline.league_of_ireland", Context.MODE_PRIVATE);
TextView txt = (TextView) findViewById(R.id.textView);
String selectedTeam = spinner.getSelectedItem().toString();
SharedPreferences.Editor editor = favTeam.edit();
editor.putString("team", selectedTeam);
editor.apply();
Intent intent = new Intent(this, MyTeamActivity.class);
txt.setText(favTeam.getString("team","Not Defined"));
startActivity(intent);
}
我尝试通过上面代码中注释掉的if语句来执行此操作,但这会导致致命错误。 任何帮助将不胜感激。
答案 0 :(得分:2)
因为您试图在不初始化的情况下从favTeam
读取值。这就是为什么它不起作用而你得到 NullPointerException 。
在从中读取值之前,您必须先初始化favteam ShardePreference
,
favTeam = this.getSharedPreferences("com.lonerganonline.league_of_ireland", Context.MODE_PRIVATE);
onCreate()
中的所以你的代码看起来像,
favTeam = this.getSharedPreferences("com.lonerganonline.league_of_ireland", Context.MODE_PRIVATE);
if (favTeam.contains("team") && favTeam != null) {
Intent intent = new Intent(this, MyTeamActivity.class);
startActivity(intent);
} else {
System.out.println("-------- cant read from shared pref -----------");
}
如果仍然出现错误,请发布错误日志。