startActivityForResult and Intents Extras, it seems extras are not pushed back

元气小坏坏 提交于 2019-11-27 05:51:41

问题


I have this code:

Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setData(ContactsContract.Contacts.CONTENT_URI);
        intent.putExtra(EXTRA_ONLINE_ID, (String) v.getTag());
        startActivityForResult(intent, PICK_CONTACT);

Then on response:

public void onActivityResult(int reqCode, int resultCode, Intent data) {


        switch (reqCode) {
            case (PICK_CONTACT):
                if (resultCode == Activity.RESULT_OK) {
                    try {
                        Uri contactData = data.getData();
                        String onlineid = data.getStringExtra(EXTRA_ONLINE_ID);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
        super.onActivityResult(reqCode, resultCode, data);
    }

the onlineid variable is null. How can I pass a value and then to receive it back?

EDIT

I even tried,

Bundle extras = data.getExtras(); // returns null

回答1:


This is done by design; system activities will not send back the extras with which they're called, so you have to manage the data elsewhere.

Luckily, the resultCode parameter is fully controlled by yourself, which means that you can use it to index your data.

private final int PICK_CONTACT = 0;
private Bundle[] myDataTransfer = { null };

...

Bundle myData = new Bundle();
myData.putString(EXTRA_ONLINE_ID, (String) v.getTag());
myDataTransfer[PICK_CONTACT] = myData;
// create intent and all
startActivityForResult(intent, PICK_CONTACT);

...

public void onActivityResult(int reqCode, int resultCode, Intent data) {
    if (resultCode == PICK_CONTACT) {
        Bundle myData = myDataTransfer[resultCode];
        String onlineid = myData.getString(EXTRA_ONLINE_ID);
    }
}

I'm not a Java programmer, there must be a nicer way to implement a map of Bundles, but this works :)




回答2:


ok Check if your Activity android:launchMode is configured as SingleTask or SingleInstance! that must be the problem :)




回答3:


I was running into some problems with this as well.

Instead of this line

 intent.putExtra(EXTRA_ONLINE_ID, (String) v.getTag());

Try

 intent.putExtra(EXTRA_ONLINE_ID, "" + v.getTag());



回答4:


The EXTRA_ONLINE_ID field will have to be set in the activity that you launched using setResult. If it's not setting that value in the returned Intent (which is different from what you sent) then you will get a null value.



来源:https://stackoverflow.com/questions/2859831/startactivityforresult-and-intents-extras-it-seems-extras-are-not-pushed-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!