Sending data back to the Main Activity in Android

后端 未结 12 1941
后悔当初
后悔当初 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:07

    I have created simple demo class for your better reference.

    FirstActivity.java

     public class FirstActivity extends AppCompatActivity {
    
        private static final String TAG = FirstActivity.class.getSimpleName();
        private static final int REQUEST_CODE = 101;
        private Button btnMoveToNextScreen;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            btnMoveToNextScreen = (Button) findViewById(R.id.btnMoveToNext);
            btnMoveToNextScreen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent mIntent = new Intent(FirstActivity.this, SecondActivity.class);
                    startActivityForResult(mIntent, REQUEST_CODE);
                }
            });
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            if(resultCode == RESULT_OK){
                if(requestCode == REQUEST_CODE && data !=null) {
                    String strMessage = data.getStringExtra("keyName");
                    Log.i(TAG, "onActivityResult: message >>" + strMessage);
                }
            }
    
        }
    }
    

    And here is SecondActivity.java

    public class SecondActivity extends AppCompatActivity {
    
        private static final String TAG = SecondActivity.class.getSimpleName();
        private Button btnMoveToPrevious;
        private EditText editText;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
    
            editText = (EditText) findViewById(R.id.editText);
    
            btnMoveToPrevious = (Button) findViewById(R.id.btnMoveToPrevious);
            btnMoveToPrevious.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    String message = editText.getEditableText().toString();
    
                    Intent mIntent = new Intent();
                    mIntent.putExtra("keyName", message);
                    setResult(RESULT_OK, mIntent);
                    finish();
    
                }
            });
    
        }
    }
    

提交回复
热议问题