vico
vico

Reputation: 18171

Passing data as intent result

I create intent to AddDeviceActivity from MainActivity:

    Intent intent = new Intent(this, AddDeviceActivity.class);
    startActivityForResult(intent, REQUEST_CODE_CHECK);

And expecting to get result:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE_CHECK) {
        if (resultCode == RESULT_OK)

                if ( data.getData() !=null ) {
                    Timber.tag(Utils.TIMBER_TAG).v("got result " + data.getData().toString());
                } else
                {
                    Timber.tag(Utils.TIMBER_TAG).v("got null data " );
                }

    }
}

AddDeviceActivity puts some data:

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    getIntent().putExtra("PTREFENCE_CHANGED", "fffff");
    setResult(RESULT_OK, getIntent());

}

When AddDeviceActivity finishes I receive call to onActivityResult, but data.getData() returns null.

How to retrieve data from Intent?

Upvotes: 0

Views: 79

Answers (1)

Blundell
Blundell

Reputation: 76458

Change this

getIntent().putExtra("PTREFENCE_CHANGED", "fffff");
setResult(RESULT_OK, getIntent());

to this:

Intent intent = getIntent().putExtra("PTREFENCE_CHANGED", "fffff");
setResult(RESULT_OK, intent);

You should not rely on whatever is backing that getIntent method, it may not update the underlying object the way you think it does, i.e. getIntent could create a copy each time get is called.


You could also directly get your String as the first test (instead of using getData().

String result = data.getStringExtra("PTREFENCE_CHANGED")
Timber.tag(Utils.TIMBER_TAG).v("Got: " +result);

Lastly, you might want to check your PreferenceChanged method is being called, by using some more logs.

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    Timber.tag(Utils.TIMBER_TAG).v("On Preference Changed. Setting Result OK.");
    Intent intent = getIntent().putExtra("PTREFENCE_CHANGED", "fffff");
    setResult(RESULT_OK, intent);
}

Upvotes: 1

Related Questions