仅在首次运行时进行Android运行设置活动

cld4siwp  于 2022-12-16  发布在  Android
关注(0)|答案(1)|浏览(153)

我正在开发我的第一个安卓应用程序,我的主活动上有一个微调器,当用户运行应用程序后,着陆屏幕或活动将是一个不同的基础(而不是主)。我存储在一个共享的首选微调器中的选择,如果这是设置,我想在启动时加载一个不同的活动。
代码

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语句做注解,但是这导致了致命的错误。任何帮助都将不胜感激。

nhjlsmyf

nhjlsmyf1#

因为您试图从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 -----------");
    }


如果仍然出现错误,请发布错误日志。

相关问题