java应用程序在保存到共享首选项时崩溃

egdjgwm8  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(393)

我正在尝试保存到共享首选项。我想能够从共享的首选项加载,但当我保存或加载时,我的应用程序崩溃。
我还希望能够有我的处理程序/运行恢复时,我的应用程序启动。我该怎么做?
这是我的密码:

public class MainActivity extends ActionBarActivity {

    public void save(){
        Editor editor = pref.edit();
        editor.putInt("countertest", counter);
        editor.commit();
    }//end of save

    public void read(){
        counter = pref.getInt("countertest", counter);
    }//end of read

      Handler testHandler = new Handler();
      int counter;
      TextView testView;
      Button testButton;
      Runnable Runnable0;
      SharedPreferences pref;

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

        testView = (TextView) findViewById(R.id.testView);
        testButton = (Button) this.findViewById(R.id.testButton);

     // read();
        testView.setText(Integer.toString(counter));

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

@Override
protected void onResume() {

    //read();

   final Runnable Runnable0 = new Runnable() {
        @Override
        public void run() {
            counter += 1;   
            testView.setText(Integer.toString(counter));
            testHandler.postDelayed(this, 1000);
//          save();
            }// end of if   
    };

    /* button click */
    testButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            /* Start runnable */

                testButton.setEnabled(false);
                counter -= 5;
                //save();
                testView.setText(Integer.toString(counter));
                testHandler.post(Runnable0);

        }// end of onClick
    });// end of blingButton onClickListener    

    super.onResume();

}//end of onResume

@Override
protected void onPause() {
    //save();
    testHandler.removeCallbacks(Runnable0);
    super.onPause();
}//end of onPause
}
kgqe7b3p

kgqe7b3p1#

你还没有初始化你的 pref 对象。你刚刚申报了。所以你得穿上它 onCreate() 通过

pref = getSharedPreferences("MySP", 0);

pref = PreferenceManager.getDefaultSharedPreferences(this);

相关问题