如何将数据从活动A传递/保存到B再到B?

时间:2015-01-17 16:15:22

标签: android eclipse button android-activity

我用eclipse制作了一个应用程序,关于那些按钮,第一个按钮计算我所做的点击,第二个按钮将我发送到活动B和。在活动B中包括第三个按钮我已经让它买了100次点击。我现在遇到的问题是,当我点击按钮购买100点击主要活动的金额从1000开始不是,并且不保存我在购买之前所做的最后点击。

MainActivity:

public class MainActivity extends ActionBarActivity {

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

    Button button2 = (Button) findViewById(R.id.button2);
    button2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getApplicationContext(),MainActivityTwo.class);

            startActivityForResult(intent, count);

        }
    });



final Button button1 = (Button) findViewById(R.id.button1);

final TextView textView1 = (TextView) findViewById(R.id.textView1);

button1.setOnClickListener(new View.OnClickListener()

{

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent in = getIntent();
        int cou = in.getIntExtra("", 1000);
        // Get the extras (if there are any)
        Bundle extras = in.getExtras();
        if (extras != null) {

                // TODO: Do something with the value of isNew.
            count++;
            int sum = cou+ count;

            textView1.setText("Clicked "+ sum +":times");


            } else{
             count++;
             textView1.setText("Clicked"+ count +":times");
         }
    }
});

}

Activity_Two:

public class MainActivityTwo extends ActionBarActivity {


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

    Button btn = (Button) findViewById(R.id.btn);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(getApplicationContext(),MainActivity.class);
            i.putExtra("", 1000);

            startActivity(i);
        }
    });


}
}

1 个答案:

答案 0 :(得分:0)

使用onSaveInstanceState和onRestoreInstanceState

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putInt("clicks", "x") // x is the int that count clicks.
}

并且

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    x = savedInstanceState.getInt("clicks");
    x + y //y is the newly bought clicks if any.

}

onSaveInstanceState在Acitivty暂停时被调用(即当您从活动A移动到活动B时。

当活动A恢复时,将调用

onRestoreInstanceState。也就是说,当你从活动B回到活动A