我正在为 Android 创建一个基于 GPS 的应用程序,有 2 个活动 Main 和 LocNames。 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;
}
以下是我尝试在 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);
}
但是当我尝试使用 LocNames 返回的结果时,我的应用程序崩溃了
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == 1 && resultCode == RESULT_OK)
{
source = data.getStringExtra("src");
destination = data.getStringExtra("destination");
}
}
我以前没有使用 setResults 的经验,但文档说它需要一个 int 和一个意图作为参数,所以我为此创建意图,但我在 LocNames 的 OnClick 中得到 NullPointerException 。
Regards