onSaveInstanceState无法按预期工作

时间:2017-07-22 03:51:07

标签: android

我有一个从一个活动到另一个活动的按钮,它应该将值保存在Counter中,但每次都不会保存。我究竟做错了什么?我已经看到了其他解决方案,但我检查并且我正在做与它们完全相同的事情。

package com.example.navjeevenmann.mytycoon;

 import android.content.Intent;
 import android.os.Bundle;
 import android.os.Handler;
 import android.support.v7.app.AppCompatActivity;
 import android.view.View;
 import android.widget.Button;
 import android.widget.TextView;


 public class MainActivity extends AppCompatActivity {
private Button myButton;
private int Counter;
private Button myButton2;
private TextView myTextView;
Handler handler = new Handler();
private int add;

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

    if (savedInstanceState != null) {
        add = savedInstanceState.getInt("Count");
        Counter = savedInstanceState.getInt("Add");
    }

    myButton = (Button) findViewById(R.id.button);
    myButton2 = (Button) findViewById(R.id.button2);
    myTextView = (TextView) findViewById(R.id.textView);

    myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Counter = ButtonCounter(Counter);
        }
    });
    myButton2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
            intent.putExtra("Count", Counter);
            startActivity(intent);
        }

    });

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Counter = AutoCounter(Counter, add);
            Display(Counter, myTextView);
            handler.postDelayed(this, 100);
        }
    }, 10);


}

protected void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putInt("Count", Counter);
    savedInstanceState.putInt("Add", add);
}


public int ButtonCounter(int Counter) {
    Counter += 1;
    return Counter;
}

public int AutoCounter(int Counter, int add) {
    Counter += add;
    return Counter;
}

public void Display(int Counter, TextView myTextView) {
    String man = String.valueOf(Counter);
    myTextView.setText("$" + man);
}



 }

1 个答案:

答案 0 :(得分:0)

您没有实施正确的方法

来自文档:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putInt("Count", Counter);
    savedInstanceState.putInt("Add", add);

    // call superclass to save any view hierarchy
    super.onSaveInstanceState(outState);
}

来源:https://developer.android.com/guide/components/activities/activity-lifecycle.html#oncreate