data in onActivityResult is null

前端 未结 3 627
独厮守ぢ
独厮守ぢ 2020-12-03 10:37

I am trying do a simple application for Android. I have two Activities (A and B). In B I only want select a date

相关标签:
3条回答
  • 2020-12-03 11:04

    in A onActivityResult method

       if(null!=data){
    
        Bundle bundle = data.getExtras();
        String mydate = bundle.getString("Date");
    
       }
    

    and in B

    Intent returnIntent = new Intent();
    returnIntent.putExtra("Date",dateSelected);
    setResult(RESULT_OK,returnIntent);      
    finish();
    
    0 讨论(0)
  • 2020-12-03 11:10

    I know this is answered, but just to give more explanation on the error, you were using getIntent() instead of the data element received on the callback.

    getIntent() returns the Intent that was originally used to open Activity A (maybe when you opened the app or from another activity), and data is the intent that Activity B returned as response parameters.

    Also, you were using getIntent() in Activity B instead of creating a new Intent that would be returned to Activity A.

    Intent returnIntent = new Intent();
    

    Finally, the created intent must be added in setResult

    setResult(RESULT_OK,returnIntent);  
    
    0 讨论(0)
  • 2020-12-03 11:15

    try this:

    Then, in B, I do:

    Intent intent = getIntent();
    intent.putExtra("Date",dateSelected);
    setResult(RESULT_OK, intent);
    finish();
    

    And, in A:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK && requestCode==1) {
            Bundle MBuddle = data.getExtras();
            String MMessage = MBuddle.getString("Date");
        }
    }
    
    0 讨论(0)
提交回复
热议问题