为什么onActivityResult总是为Intent extra返回null值

时间:2017-04-20 18:09:00

标签: android android-intent

我的onActivityResult方法on activity总是为Intent extra返回null。我直接在活动上调用这些方法。请帮助找到解决方案。

 private void onClickShopNameLayout() {
    shopNameLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(OrderActivity.this,CustomerListActivity.class);
            startActivityForResult(i,CUSTOMER_REQUEST_CODE);
        }
    });
}

从OrderActivity启动CustomerListActivity

@Override
public void onItemClick(View v, int position) {
    Customers customers = customersData.get(position);
    Intent intent = new Intent();
    intent.putExtra("testing","String value");
    intent.putExtra("selected_customer",customers);
    setResult(Activity.RESULT_OK,intent);
    finish();
}

这是来自Recycler视图适配器类的接口方法,它触发列表项单击列表器。在CustomerListActivity中实现

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case CUSTOMER_REQUEST_CODE:
            if (resultCode == Activity.RESULT_OK) {
                String testing = getIntent().getStringExtra("testing");
                Customers customers = getIntent().getParcelableExtra("selected_customer");
                String businessName = customers.getBusinessName();
                Log.d(TAG,"customer name "+businessName +" testing "+testing);

            }
    }
}

OrderActivity中的onActivityResult覆盖方法。

2 个答案:

答案 0 :(得分:2)

您的onActivityResult()在代码中提供Intent,其名称为data。您应该使用此data代替getIntent()来获取意图extra值。

试试这个:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case CUSTOMER_REQUEST_CODE:
            if (resultCode == Activity.RESULT_OK) {

                String testing = data.getStringExtra("testing");
                Customers customers = data.getParcelableExtra("selected_customer");
                String businessName = customers.getBusinessName();

                Log.d(TAG,"customer name " + businessName +" testing "+testing);
            }
        break; // Don't forget to use break for multiple cases
    }
}

答案 1 :(得分:1)

您正在从活动意图中获取额外内容,而不是活动结果意图。

而不是

String testing = getIntent().getStringExtra("testing");
Customers customers = getIntent().getParcelableExtra("selected_customer");

DO

String testing = data.getStringExtra("testing");
Customers customers = data.getParcelableExtra("selected_customer");