Sending data back to the Main Activity in Android

后端 未结 12 1955
后悔当初
后悔当初 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 01:59

    In first activity u can send intent using startActivityForResult() and then get result from second activity after it finished using setResult.

    MainActivity.class

    public class MainActivity extends AppCompatActivity {
    
        private static final int SECOND_ACTIVITY_RESULT_CODE = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        // "Go to Second Activity" button click
        public void onButtonClick(View view) {
    
            // Start the SecondActivity
            Intent intent = new Intent(this, SecondActivity.class);
            // send intent for result 
            startActivityForResult(intent, SECOND_ACTIVITY_RESULT_CODE);
        }
    
        // This method is called when the second activity finishes
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            // check that it is the SecondActivity with an OK result
            if (requestCode == SECOND_ACTIVITY_RESULT_CODE) {
                if (resultCode == RESULT_OK) {
    
                    // get String data from Intent
                    String returnString = data.getStringExtra("keyName");
    
                    // set text view with string
                    TextView textView = (TextView) findViewById(R.id.textView);
                    textView.setText(returnString);
                }
            }
        }
    }
    

    SecondActivity.class

    public class SecondActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
        }
    
        // "Send text back" button click
        public void onButtonClick(View view) {
    
            // get the text from the EditText
            EditText editText = (EditText) findViewById(R.id.editText);
            String stringToPassBack = editText.getText().toString();
    
            // put the String to pass back into an Intent and close this activity
            Intent intent = new Intent();
            intent.putExtra("keyName", stringToPassBack);
            setResult(RESULT_OK, intent);
            finish();
        }
    }
    

提交回复
热议问题