如何在Android中将数据从一个活动传递到另一个活动

时间:2016-01-26 18:53:10

标签: android

这是我的第一个名为CreateMessageActivity的活动,用户被要求检查ckeckbox,以便它可以计算总数。

  public void myClickHandler(View view) {
    double fish1 = 0;
    double chicken1 = 0;
    double steak1 = 0;
    double total;
    String total1;

    CheckBox fish = (CheckBox) findViewById(R.id.checkFish);
    CheckBox chicken = (CheckBox) findViewById(R.id.checkChicken);
    CheckBox steak = (CheckBox) findViewById(R.id.checkSteak);

    //switch (view.getId()) {
       // case R.id.checkFish:
            if (fish.isChecked()) {
                fish1 = 5;

            } else {
                fish1 = 0;
            }
           // break;
       // case R.id.checkChicken:
            if (chicken.isChecked()) {
                chicken1 = 2;

            } else {
                chicken1 = 0;
            }
            // R.id.checkSteak:
            if (steak.isChecked()) {
                steak1 = 10;
            } else {
                steak1 = 0;
            }
            //break;
   // }
    total = fish1 + chicken1 + steak1;
    total1 = Double.toString(total);
    i need to pass total1 to the other activity call ReceiveMessageActivity.
    Intent intent = new Intent(CreateMessageActivity.this, ReceiveMessageActivity.class);
    intent.putExtra("message", total1);               
    startActivity(intent);

}

这是我的第二个活动,必须在textview中显示总数。

   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_receive_message);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    TextView TXT = new TextView(this);


    Bundle bundle = getIntent().getExtras();
    String status = bundle.getString("message");
    TXT = (TextView)findViewById(R.id.textViewactivity2);
    TXT.setText(status);

1 个答案:

答案 0 :(得分:-1)

方法getExtras()返回一个包,但是你需要获取一个String。 试试这个。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_receive_message);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //Fetch message
    String status = getIntent().getStringExtra("message");
    TXT = (TextView)findViewById(R.id.textViewactivity2);
    TXT.setText(status);