Android将值返回给MainActivity

时间:2015-10-15 13:10:51

标签: java android android-studio

我有一个带有editText,文本视图和按钮的mainActivity。用户输入一个数字,单击另一个活动打开的按钮并转换用户输入(通过一些随机计算,并不重要)并将其返回到mainView,它将在TextView中显示。 但无论它是什么,都不会在MainView中显示textView中的值。我不知道我做错了什么

MainActivity

 public void sendMessage(View view) {
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    Intent third = new Intent(this, ThirdActivity.class);
    third.putExtra(EXTRA_MESSAGE, message);
    startActivityForResult(third, 1);
}



 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
     if(requestCode == 1){
        if(resultCode == Activity.RESULT_OK){
            String msg = data.getStringExtra("result");

            converted.setText(msg);

        }if(resultCode == Activity.RESULT_CANCELED){
            String msg = ("something went wrong");
            converted.setText(msg);
        }

     }
}

SecondActivity

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

    Intent get = getIntent();
    String msg = get.getStringExtra(MainActivity.EXTRA_MESSAGE);
    int result = Integer.parseInt(msg) +2;
    //String j = Double.toString(a);
        get.putExtra("result", result);
        setResult(RESULT_OK, get);
        finish();


}

2 个答案:

答案 0 :(得分:0)

检查您是否在SecondActivity中执行此操作

getIntent().putExtra("data", "your data");
setResult(RESULT_OK, getIntent());
finish();

答案 1 :(得分:-1)

ThirdActivity

制作:

Intent resultIntent = getIntent();
resultIntent.putExtra("result","msg");
setResult(Activity.RESULT_OK, resultIntent)
finish();