将数据作为意图结果传递

I create intent to AddDeviceActivity from MainActivity:

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

并期望得到结果:

@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.

如何从Intent检索数据?

评论
  • tin
    tin 回复

    改变这个

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

    对此:

    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);
    

    最后,您可能希望通过使用更多日志来检查您的PreferenceChanged方法是否正在被调用。

    @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);
    }