我正在尝试从 UpdateLocation
Activity 中获取 ScanLocate
Activity 中的数组列表。
我正在使用 startActivityForResult
方法调用填充 ArrayList wifiList
的 scan
方法,然后我想将 ArrayList 发送到更新位置
类。
我首先在更新位置
中调用startActivityForResult
:
private void getScan(){
//Create an intent to start ScanLocate
final Intent i = new Intent(this, ScanLocate.class);
//Start scanLocate with request code
startActivityForResult(i, REQUEST_READINGS);
}
接下来,在 ScanLocate
中,我创建了 sendData
方法(注意:检查确认 ArrayList 数据此时完好无损):
private void sendData(){
//create a new intent as container for the result
final Intent readings = new Intent(this, UpdateLocation.class);
//check that data is in wifiList
for(String s:wifiList){
Log.v(TAG,"List Items: " + s);
}
//create bundle for string array
Bundle b = new Bundle();
b.putStringArrayList(key, wifiList);
//add readings to send to updateLoc
readings.putExtras(b);
//set code to indicate success and attach Intent
setResult(RESULT_OK, readings);
//call finish to return
finish();
}
最后一部分通过 onActivityResult
返回到 UpdateLocation
:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent readings){
super.onActivityResult(requestCode, resultCode, readings);
//check if request code matches the one set above
if(requestCode == REQUEST_READINGS){
//check if sendData() in ScanLocate was successful
if(resultCode == RESULT_OK){
//get the readings from the Intent
Log.v(TAG, "HERE");
result = getIntent().getExtras().getStringArrayList(ScanLocate.key);
Log.v(TAG, "HERE2");
for(String s : result) {
Log.v(TAG, "Location 5: " + s);
}
}else{
//ScanLocate was unsuccessful
}
}
}
显示第一个“Here”
,但它随后落在下一行,getStringArrayList()
抛出空指针异常。
我已经查看了文档和之前的问题,但我看不出出了什么问题。
如有任何建议,我们将不胜感激,谢谢。
之前的问题:
startactivityforResult not working
How to pass an ArrayList to the StartActivityForResult activity
最佳答案
您不需要调用getIntent()
,使用方法提供的参数:
result = readings.getStringArrayListExtra(ScanLocate.key);
关于java - 将字符串 ArrayList 从一个 Activity 传递到另一个 Activity 时,为什么会出现空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41635718/