Sending data back to the Main Activity in Android

后端 未结 12 1925
后悔当初
后悔当初 2020-11-22 01:36

I have two activities: main activity and child activity.
When I press a button in the main activity, the child activity is launched.

Now I want to send some dat

12条回答
  •  抹茶落季
    2020-11-22 02:00

    FirstActivity uses startActivityForResult:

    Intent intent = new Intent(MainActivity.this,SecondActivity.class);
    startActivityForResult(intent, int requestCode); // suppose requestCode == 2
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2)
        {
            String message=data.getStringExtra("MESSAGE");
        }
    }
    

    On SecondActivity call setResult() onClick events or onBackPressed()

    Intent intent=new Intent();
    intent.putExtra("MESSAGE",message);
    setResult(Activity.RESULT_OK, intent);
    

提交回复
热议问题