![](/img/trans.png)
[英]Why am I getting null pointer exception when I add an item to ArrayList
[英]Why am I getting a null pointer exception when passing an ArrayList of strings from one activity to another?
我試圖讓一個ArrayList ScanLocate
從活動UpdateLocation
活動。
我正在使用startActivityForResult
方法調用填充ArrayList wifiList
的scan
方法,然后我想將ArrayList發送到Update Location
類。
我首先在Update Location
調用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();
}
最后一部分是早在UpdateLocation
與onActivityResult
:
@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()
引發空指針異常。
我已經瀏覽了文檔和此處的先前問題,但看不到出了什么問題。
任何建議,將不勝感激,謝謝。
先前的問題:
您不需要調用getIntent()
,使用方法提供的參數:
result = readings.getStringArrayListExtra(ScanLocate.key);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.