What is Intent from onActivityResult Parameters

后端 未结 2 1310
一个人的身影
一个人的身影 2021-02-05 18:37

Here is my first activity code from where I call the second Activity:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {         


        
相关标签:
2条回答
  • 2021-02-05 18:40

    Third parameter is Intent, which you sent from the sub-Activity(Second Activity, which is going to finish).

    If you want to perform some calculations or fetch some username/password in sub-activity and you want to send the result to the main activity, then you place the data in the intent and will return to the Main activity before finish().

    After that you will check in onActivityResult(int, int, Intent) in main activity for the result with Intent parameter.

    Example:: MainActivity:

    public void onClick(View view) {
      Intent i = new Intent(this, subActivity.class);
      startActivityForResult(i, REQUEST_CODE);
    } 
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
        if (data.hasExtra("username") && data.hasExtra("password")) {
          String username =  data.getExtras().getString("username");
          String password =  data.getExtras().getString("password");
    
        }
      }
    

    subActivity::

    @Override
    public void finish() {
      // Create one data intent 
      Intent data = new Intent();
      data.putExtra("username", "Bla bla bla..");
      data.putExtra("password", "*****");
      setResult(RESULT_OK, data);
      super.finish();
    } 
    
    0 讨论(0)
  • 2021-02-05 18:54

    When you call Activity.startActivityForResult(), you set the requestCode. Later, this request code is needed by onActivityResult() in order to determine what Activity is sending data to it. We don't need to supply requestCode again on setResult() because the requestCode is carried along.

    The data is intent data returned from launched intent. We usually use this data when we set extras on the called intent.

    Consider this example:

    CALL SECOND ACTIVITY

    Intent i = new Intent(MainActivity.this, CheckActivity.class);
    startActivityForResult(i, REQUEST_CODE_CHECK);
    

    ON SECOND ACTIVITY, SET INTENT RESULT

    getIntent().putExtra("TADA", "bla bla bla");
    setResult(RESULT_OK, getIntent());
    finish();
    

    BACK TO FIRST ACTIVITY, ONACTIVITYRESULT()

    if(requestCode == REQUEST_CODE_CHECK && resultCode == RESULT_OK){
        text1.setText(data.getExtras().getString("TADA") );
    }
    

    There you go. You should now understand what is Intent data and how to set and fetch the value.

    0 讨论(0)
提交回复
热议问题