onActivityResult没有得到结果

时间:2016-12-31 08:48:50

标签: android listview android-intent onactivityresult

我有一个Android活动,它启动另一个以获得结果。第二个Activity有一个自定义列表视图,它应该根据对父Activity的选择返回一个值。问题是在onActivityResult中我会得到一个RESULT_OK = -1但我的返回值总是0; 在第一个Activity中,我在optionsMenu中调用第二个:

@Override
    public boolean onOptionsItemSelected(MenuItem item){

        int id = item.getItemId();
        if (id == R.id.action_settings){
            Intent i = new Intent(MainActivity.this, SecondActivity.class);
            startActivityForResult(i, REQUEST_CODE );
            return false;
        }

        return super.onOptionsItemSelected(item);
    }

我的onActivityResult是:

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent i){
    if(resultCode == RESULT_OK && requestCode == REQUEST_CODE){
        workTime = i.getIntExtra("workTime", 0);            
    }
}

在第二个活动中:

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            Profile selected = (Profile) adapterView.getItemAtPosition(position);
            Intent i = new Intent(view.getContext(),  MainActivity.class);
            long w = selected.getWorkTime; //has the correct value.
            i.putExtra("workTime", w);
            setResult(RESULT_OK, i);
            finish();
        }
    });

3 个答案:

答案 0 :(得分:0)

我发现问题是我在意图中发送了long但要求在int中获得onActivityResult,因此我需要将workTime定义为longonActivityResult应为:

protected void onActivityResult (int requestCode, int resultCode, Intent i){
if(resultCode == RESULT_OK && requestCode == REQUEST_CODE){
    workTime = i.getLongExtra("workTime", 0);            
}

}

答案 1 :(得分:0)

在第二个活动中,只需使用此代码:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            Profile selected = (Profile) adapterView.getItemAtPosition(position);
            Intent i = new Intent();
            long w = selected.getWorkTime; //has the correct value.
            i.putExtra("workTime", w);
            setResult(RESULT_OK, i);
            finish();
        }
    });

在onActivityResult的第一个活动中:

@Override
protected void onActivityResult (int requestCode, int resultCode, Intent i){
    if(resultCode == RESULT_OK && requestCode == REQUEST_CODE){
       workTime = (int)i.getLongExtra("workTime", 0);            
    }
}

答案 2 :(得分:0)

我觉得你的理解有问题。 RESULT_OK值为-1,不是0。因此,您的result代码为-1 Check this screenshot.