Android Intents传递数据

时间:2015-07-18 22:55:41

标签: android android-intent bundle

我不知道为什么,但这不起作用。任何人都可以看到我的代码有任何问题。

我有两个活动,我从两个

传递数据
public class InputActivity extends AppCompatActivity {


    EditText  number1EditText;
    EditText number2EditText;
    Button addButton;

InputActivity代码如下所示

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

    number1EditText = (EditText)findViewById(R.id.editText);
    number2EditText = (EditText)findViewById(R.id.editText2);
    addButton = (Button)findViewById(R.id.button);

    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent mIntent = new Intent(getApplicationContext(), AddActivity.class);
            mIntent.putExtra("number1", number1EditText.getText().toString());
            mIntent.putExtra("number2", number2EditText.getText().toString());
            startActivity(mIntent);

        }
    });
}

AddActivity代码如下所示

public class AddActivity extends AppCompatActivity {

    TextView answer;
    double y=0;


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

        answer =(TextView)findViewById(R.id.textView);

        String value1 = getIntent().getExtras().getString("number1");
        String value2 = getIntent().getExtras().getString("number2");

        answer.setText((int) (Double.parseDouble(value1)+Double.parseDouble(value2)));
    }

1 个答案:

答案 0 :(得分:1)

快看:

answer.setText((int) (Double.parseDouble(value1)+Double.parseDouble(value2)));

您正在将int传递给方法setText(),该方法恰好有一个重载,当您从{{1}传递引用时,会收到int个参数在某些String中。您可能会收到xml

如果要显示包含值之和的文本:

ResourceNotFoundException

请记住,您必须首先执行大量检查,例如 answer.setText(String.valueOf((int) (Double.parseDouble(value1)+Double.parseDouble(value2)))); ,您可能会遇到另一种例外情况,例如NumberFormatException