Bundle null onActivityResult

时间:2017-10-19 11:50:09

标签: java android

我已经尝试了几种不同的解决方案,但没有一种方法可行,因为一切似乎在我返回结果的另一个活动中正常工作,这里是代码。

调用城市活动的主要活动:

//this method gets called on a button click and it works as other activity shows up

public void getCity(View v){
    Intent intent = new Intent(getApplicationContext(), City.class);
    startActivityForResult(intent,1); 
}
//receiving the data the first data is ok  but the second one is null although doing the same thing in both files
 protected void onActivityResult(int requestCode, int resultCode, Intent data){

    if(resultCode == RESULT_OK && data != null && requestCode==0){
        initializeUI(data.getExtras());
    }
    if(resultCode == RESULT_OK && data != null && requestCode==1){
          //data is null here
    }
    super.onActivityResult(requestCode, resultCode, data);
}

我的城市活动

 public void addInput(View v){
    Bundle bundle = new Bundle();

    EditText cityBox = (EditText) findViewById(R.id.cityInput);
    String cityName =  cityBox.getText().toString();
    Intent resultIntent = new Intent();
    try {
        EditText longBox = (EditText) findViewById(R.id.longitudeInput);
        String longitude =  longBox.getText().toString();

        double longi =  Double.parseDouble(longitude);

        bundle.putDouble("LONGITUDE", longi);

        EditText latBox = (EditText) findViewById(R.id.latitudeInput);
        String latitude =  latBox.getText().toString();

        double lati =  Double.parseDouble(latitude);

        bundle.putDouble("LATITUDE", lati);

    } catch (NumberFormatException e){

    }
    bundle.putString("CITY_NAME", cityName);
    resultIntent.putExtra("DATA",bundle);
    setResult(RESULT_OK, resultIntent);
    finish(); //calling finish just in case tried without finish aswell
    onBackPressed(); //calling onBackPressed tried without it as well doesn't work 
}

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

试试这个:

然后,在B中,我这样做:

Intent intent = getIntent();
intent.putExtra("Date",dateSelected);
setResult(RESULT_OK, intent);
finish();

而且,在A:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode==RESULT_OK && requestCode==1){
Bundle MBuddle = data.getExtras();
String MMessage = MBuddle .getString("Date");
}
}

我在您的代码中发现的问题是使用了错误的requestCode,您在startActivityForResult中传递了1作为结果代码,而在onActivityResult中您正在检查requestCode==0意味着intializeUI等等。需要做的就是使用下面的代码。

     if(resultCode == RESULT_OK && data != null && requestCode==1){
     //everything works fine 
     initializeUI(data.getExtras());
    }

希望这会对你有所帮助。

答案 1 :(得分:0)

我最近遇到了同样的问题。我错误的是我在startActivity()错误地使用startActivityForResult()然后在我设置结果之前调用onBackPress()finish()的子活动中。我建议您确保在活动finish()之前设置结果,并确保您使用startActivityForResult()开始活动。

以下是我的代码中的代码段。

setResult(RESULT_OK, getIntent().putExtra("country", "some result"));

我确保上述编写的代码在onBackPressed()onFinish()之前得到解决,并且对我有用。

希望这会对你有所帮助。