使用共享首选项时应用程序崩溃

时间:2017-05-11 21:44:17

标签: java android crash sharedpreferences

我正在创建一个简单的应用程序,它会计算按钮的点击次数并使用共享首选项保存整数。我尝试使用以下代码,但是如果我尝试打开"单人游戏"

,应用程序会一直崩溃
public class Singleplayer extends AppCompatActivity {

private int sp1;
private int record;


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_singleplayer);


    final Button button1 = (Button) findViewById(R.id.buttonspieler1);
    final TextView lbl1 = (TextView)findViewById(R.id.lblspieler1);
    final TextView lbl2 = (TextView)findViewById(R.id.lblrekord);

    SharedPreferences data_record = getSharedPreferences("savegame", 0);
    record = data_record.getInt("myKey1", 0);
    lbl2.setText(String.valueOf(record));

    button1.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(final View v)
        {


            if(sp1< record) {
                sp1++;
                lbl1.setText(String.valueOf(sp1));
            }
            else if(sp1>= record)
            {
                sp1++;
                record++;
                lbl1.setText(String.valueOf(sp1));
                lbl2.setText(String.valueOf(record));

            }


        }
    });


}

@Override
protected void onStop() {
    super.onStop();

    SharedPreferences data_record = getSharedPreferences("savegame", 0);
    SharedPreferences.Editor editor = data_record.edit();
    editor.putString("myKey1", String.valueOf(record));
    editor.commit();
}

}

1 个答案:

答案 0 :(得分:0)

您在onStop()中使用的是sharedPrefrence,因此您将面临许多问题,我建议在点击方法结束时使用它

 button1.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(final View v)
        {


            if(sp1< record) {
                sp1++;
                lbl1.setText(String.valueOf(sp1));
            }
            else if(sp1>= record)
            {
                sp1++;
                record++;
                lbl1.setText(String.valueOf(sp1));
                lbl2.setText(String.valueOf(record));

            }

SharedPreferences data_record = getSharedPreferences("savegame", 0);
    SharedPreferences.Editor editor = data_record.edit();
    editor.putString("myKey1", String.valueOf(record));
    editor.commit();
        }
    });

那么为什么应用程序崩溃,因为sharedPref没有任何值,它 null

请检查this