Android:使用intent setResults来回传递数据

Yog*_*esh 4 android android-intent

我正在为Android创建一个基于GPS的应用程序,主要和LocNames有2个活动.Main显示我的地图和LocNames是获取用户想要的源和目的地.我想在用户从菜单中选择LocNames时启动LocNames,用户在框中输入名称,我希望将结果发送回Main.但我这样做会有例外.

以下是我的Main调用LocNames的方式:

    public boolean onOptionsItemSelected(MenuItem item) 
{
    switch (item.getItemId()) 
    {
        case R.id.showMyLocation:
            showCurrentLocation();
            break;
        case R.id.showRoute:
            Intent getLocationsIntent = new Intent(Main.this, LocNames.class);
            startActivityForResult(getLocationsIntent, 1);
            break;
    }
Run Code Online (Sandbox Code Playgroud)

以下是我尝试在LocNames的onClick中设置结果的方法:

public void onClick(View v) 
{
    // TODO Auto-generated method stub
    source = sourceText.getText().toString();
    destination = destinationText.getText().toString();     
    Intent result = new Intent(LocNames.this, Main.class);
    result.putExtra("src", source);
    result.putExtra("dest", destination);
    setResult(RESULT_OK, result);
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用LocNames返回的结果时,我的应用程序崩溃了

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
 if(requestCode == 1 && resultCode == RESULT_OK)
    {
        source = data.getStringExtra("src");
        destination = data.getStringExtra("destination");           
    }
}
Run Code Online (Sandbox Code Playgroud)

我之前没有使用setResults的经验,但是文档说它需要一个int和一个intent作为参数,所以我为它创建了intent,但是我在OnClick of LocNames中得到了NullPointerException.

问候

207*_*207 7

您不需要特定组件的意图.你只需要一个空的意图.所以更换

Intent result = new Intent(LocNames.this, Main.class);
Run Code Online (Sandbox Code Playgroud)

Intent intent = new Intent();
Run Code Online (Sandbox Code Playgroud)