gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:31:46 25 4
gpt4 key购买 nike

我正在为 Android 创建一个基于 GPS 的应用程序,并且有 2 个 Activity Main 和 LocNames。 Main 显示我的 map ,LocNames 用于获取用户想要的来源和目的地。当用户从菜单中选择它时,我想启动 LocNames,用户在框中输入名称,我希望将结果发送回 Main。但我在这样做时遇到了异常(exception)情况。

这是我的 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 和一个 Intent 作为参数,所以我正在为此创建 Intent ,但我在 LocNames 的 OnClick 中得到 NullPointerException。

问候

最佳答案

您不需要特定组件的 Intent 。你只需要一个空洞的 Intent 。所以替换

Intent result = new Intent(LocNames.this, Main.class);

Intent intent = new Intent();

关于Android:使用 intent setResults 来回传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10158560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com