安卓:传递数据来回使用意图setResults [英] Android: passing data back and forth using intent setResults
问题描述
我创建为Android基于GPS的应用程序,并有2个主要活动和LocNames。主要展示我的地图和LocNames是获得源和用户想要的目的地。我想开始LocNames当用户从菜单中选择它,用户在输入框的名字,我想结果被发送回主。但我得到的例外这样做。
I am creating a GPS based app for Android and there are 2 activities Main and LocNames. Main shows my map and LocNames is to get source and destination that user wants. I want to start LocNames when user selected it from menu, user enters names in boxes and I want result to be send back to Main. But I am getting exceptions in doing so.
下面是我的主要是如何调用LocNames:
Here is how my Main calls 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设置的结果:
Here is how I am trying to set results in onClick of LocNames:
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返回的结果。
But my application crashed when I try to use result returned by 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异常。
I have no prior experience in using setResults but documentation says it takes an int and an intent as argument so I am creating intent for that but I get NullPointerException in OnClick of LocNames.
问候
推荐答案
您不需要特定组件的意图。你只需要一个空的意图。因此,替换
You do not need an intent for a specific component. You only need an empty intent. So replace
Intent result = new Intent(LocNames.this, Main.class);
与
Intent intent = new Intent();
这篇关于安卓:传递数据来回使用意图setResults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!