简体   繁体   中英

Why am I getting a null pointer exception when passing an ArrayList of strings from one activity to another?

I am trying to get an arraylist in ScanLocate activity from an UpdateLocation activity.

I'm using startActivityForResult method to call the scan method which populates the ArrayList wifiList , I then want to send the ArrayList to the Update Location class.

I start by calling startActivityForResult in Update Location :

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);
}

Next, in ScanLocate I created the sendData method (note: the check confirms that the ArrayList data is intact at that point):

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();
}

The final part is back in UpdateLocation with the 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
        }
    }
}

The first "Here" is displayed however it then falls down on the next line, getStringArrayList() throws a null pointer exception.

I have looked through the documentation and at previous questions on here and I cannot see what is going wrong.

Any advice would be appreciated, thanks.

Previous questions:

startactivityforResult not working

How to pass an ArrayList to the StartActivityForResult activity

您不需要调用getIntent() ,使用方法提供的参数:

result = readings.getStringArrayListExtra(ScanLocate.key);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM