Search code examples
androidandroid-activityonactivityresult

Why does onActivityResult fail to enter method?


I have an activity B called by an activity A.

In activity A:

intent = new Intent (MainActivity.this, SelectionActivity.class);
startActivityForResult(intent, RESULT_OK);

In activity B (it's about a ListView when items are clicked):

@Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
    long arg3) {
                // TODO Auto-generated method stub
                TextView tv = (TextView)arg0.getChildAt(arg2);
                String key = tv.getText().toString();
                Intent myIntent = new Intent();
                myIntent.putExtra("genre", key);
                setResult(RESULT_OK,myIntent);
                finish();
            }

And I override the onActivityResult method like this in A:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
           super.onActivityResult(requestCode, resultCode, data);
           if (resultCode == RESULT_OK) {
              if (data != null) {
                 Bundle b = data.getExtras(); 
                 String str = b.getString("genre");
                 Log.v("nope","loaded ! " + str);
                 r.LoadGenre(str);
              }
              Log.v("nope"," not loaded ! ");
           }
        } 

But I'm never reaching any of these Log.v messages.

LogCat is clear, no errors. When running, A, it starts B perfectly, when items are clicked on B, B closes perfectly to get back to A.


Solution

  • You do need to pass request code to the startActivityForResult() method.
    The "request code" identifies your request. When you receive the result Intent, the callback provides the same request code so that your app can properly identify the result and determine how to handle it.

    In your case you didn't checking received result with requestcode

    So check requestCode also in your onActivityResult method.So Change

    startActivityForResult(intent, RESULT_OK);
    

    to

    startActivityForResult(intent, 200);
    

    and

    if (resultCode == RESULT_OK) {
    

    to

    if (requestCode == 200 && resultCode == RESULT_OK) {