AsyncTask NullPointerException onPostExecute,调用ListView适配器时出错

时间:2013-09-08 20:21:11

标签: android android-listview android-asynctask nullpointerexception listview-adapter

我在扩展ListFragment的类中有一个AsyncTask。在课程中,任务会查询谷歌附近的地方,并成功返回值。在我的onCreateView中,我创建了一个视图,使用我在本地实例化的变量。在我的onPostExecute方法中,我有一个“循环和日志”段,以及一个空检查来验证我有数据。我发现我的自定义适配器为null,尽管已实例化它。我想我在这里缺少一些基本的东西,任何帮助都会受到赞赏。我在这个问题上搜索了大约35篇其他帖子,但无济于事。 编辑:我还重新观看了Romain Guy关于适配器/列表视图的演示,并重新阅读了开发。关于developer.android的文档。

My Code
        package com.example.twigglebeta4;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.twigglebeta4.PlaceItem;
//import com.google.android.gms.maps.model.LatLng;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ListView;

//This class is intended to retrieve data, 
//and place it into an array for a custom adapter to set the results to listview

public class NearbyPlaceFragment extends ListFragment{
    //private int MAX_PLACES=20;
    static LocationManager systemLocation;

LayoutInflater inflater;
ViewGroup container;

ArrayList<PlaceItem> placeItems;
//Moving ListView_Adapter out here gives NPE error :
    //09-08 15:03:52.190: E/AndroidRuntime(30422):  at com.example.twigglebeta4.NearbyPlaceFragment.<init>(NearbyPlaceFragment.java:42)
//ListView_Adapter listViewAdapter = new ListView_Adapter(getActivity().getBaseContext());
ListView_Adapter listViewAdapter;

public NearbyPlaceFragment() {
}

@Override
public ListView onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //Layout containing listView
    ListView rootListView = (ListView) inflater.inflate(R.layout.nearby_list, container, false);

    //ID of listView within layout
    ListView listView = (ListView) rootListView.findViewById(android.R.id.list);

    //Adapter to control cell items
    ListView_Adapter listViewAdapter = new ListView_Adapter(getActivity().getBaseContext());
    listView.setAdapter(listViewAdapter);

    //Start to get places
    GetNearbyPlaces();
    return rootListView;
}

//Need to retrieve nearby places
private void GetNearbyPlaces() {
    //Instantiate wrapper for latitude and longitude
    systemLocation = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

    //Get last location
    Location lastKnownLocation = systemLocation.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    //Get latitude and longitude
    double lastLatitude = lastKnownLocation.getLatitude();
    double lastLongitude = lastKnownLocation.getLongitude();

    //Construct URL for places request
    String nearbySearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
    "json?location="+lastLatitude+","+lastLongitude+
    "&radius=1000&sensor=true" + "&types=food%7Crestaurant%7Cbar%7Cstore"+
    "&key=AIzaSyC6KLby3iLblyuQY%5Fy%2DoXEvrZyuAZk9OWc";

    //Execute request
    new ExecuteQuery().execute(nearbySearchURL);
}

//This method is used to execute the query
private class ExecuteQuery extends AsyncTask<String, Void, ArrayList<PlaceItem>> {

    @Override
    protected ArrayList<PlaceItem> doInBackground(String... nearbyURL) {
        // TODO Auto-generated method stub
        StringBuilder nearbyPlacesBuilder = new StringBuilder();
        //Need to execute query
        for(String nearbySearchURL : nearbyURL) {
            //Instantiate default Http Client
            //This is the container that will execute our query
            HttpClient nearbyClient = new DefaultHttpClient();

            try {
                //Create a new get method to retrieve the data
                //This method is the request builder
                HttpGet nearbyGet = new HttpGet(nearbySearchURL);

                //Get the data from our get
                HttpResponse nearbyGetResponse = nearbyClient.execute(nearbyGet);
                //Check the status to find whether response was successful or not
                if(nearbyGetResponse.getStatusLine().getStatusCode()==200) {

                    //Create Http Entity of the response to read
                    HttpEntity nearbyEntity = nearbyGetResponse.getEntity();
                    //Store the content of our entity, by using an input stream
                    InputStream nearbyEntityContent = nearbyEntity.getContent();
                    //Read the content of the input stream to create the input 
                    InputStreamReader nearbyInput = new InputStreamReader(nearbyEntityContent);
                    //Read the information from the input stream data
                    BufferedReader nearbyReader = new BufferedReader(nearbyInput);

                    String lineIn;

                    while((lineIn = nearbyReader.readLine()) != null) {
                        //Log.i("com.example.twigglebeta4",lineIn);
                        nearbyPlacesBuilder.append(lineIn);
                    }

                }
            }
            catch (Exception err) {

                err.printStackTrace();
            }
        }
        placeItems = new ArrayList<PlaceItem>();

        try {
            //Parse JSON object to format results
            JSONObject nearbyResultObject = new JSONObject(nearbyPlacesBuilder.toString());

            //Create an array from the JSON Object
            JSONArray placesArray = nearbyResultObject.getJSONArray("results");

            for(int placeCount=0;placeCount < placesArray.length();placeCount++){
                //LatLng thisLocation = null;
                String thisName = "";
                String thisAddress = "";

                //Grab the current JSON object
                JSONObject thisNearbyObject = placesArray.getJSONObject(placeCount);
                //Grab the current name
                thisName = thisNearbyObject.getString("name");
                //Grab the current address
                thisAddress = thisNearbyObject.getString("vicinity");
                //Grab this latitude longitude from the object
                //JSONObject thisLatLng = thisNearbyObject.getJSONObject("geometry").getJSONObject("location");
                //thisLocation = new LatLng(Double.valueOf(thisLatLng.getString("lat")),Double.valueOf(thisLatLng.getString("lng")));

                PlaceItem thisPlace = new PlaceItem(R.id.list_cell_icon,thisName,thisAddress);

                placeItems.add(thisPlace);
            }
        }
        catch (Exception err) {
            err.printStackTrace();
        }
        return placeItems;
    }

    protected void onPostExecute(final ArrayList<PlaceItem> placeItems) {
        Log.i("onPostExecute", "Starting onPostExecute");
        //listViewAdapter.notifyDataSetChanged();
        //Layout containing listView

        for(int i=0;i<placeItems.size();i++) {
            Log.i("onPostExecute Loop", placeItems.get(i).name);
            //Problem section start
            if(placeItems.get(i).name != null /*&& listViewAdapter != null*/) {//If I remove this condition
                Log.i("onPostExecute Loop", "I'm in here now");
                listViewAdapter.add(placeItems.get(i).name);    //then error here, listViewAdapter is null
            }
            //Problem section end
        }
    }
}

}

我的堆栈跟踪:

    09-08 15:07:17.290: I/endeffect(31947): AbsListView.onMeasure(), getWidth()=1080, getHeight()=1557, this=android.widget.ListView{4240f490 V.ED.VC. ......I. 0,0-1080,1557 #102000a android:id/list}
    09-08 15:07:17.290: D/AbsListView(31947): unregisterIRListener() is called 
    09-08 15:07:17.290: I/endeffect(31947): AbsListView.onLayout(), getWidth()=1080, getHeight()=1557, this=android.widget.ListView{4240f490 V.ED.VC. ......ID 0,0-1080,1557 #102000a android:id/list}
    09-08 15:07:17.650: I/onPostExecute(31947): Starting onPostExecute
    09-08 15:07:17.650: I/onPostExecute Loop(31947): Admiral Theatre
    09-08 15:07:17.650: I/onPostExecute Loop(31947): I'm in here now
    09-08 15:07:17.650: D/AndroidRuntime(31947): Shutting down VM
    09-08 15:07:17.650: W/dalvikvm(31947): threadid=1: thread exiting with uncaught exception (group=0x4127fac8)
    09-08 15:07:17.660: E/AndroidRuntime(31947): FATAL EXCEPTION: main
    09-08 15:07:17.660: E/AndroidRuntime(31947): java.lang.NullPointerException
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at com.example.twigglebeta4.NearbyPlaceFragment$ExecuteQuery.onPostExecute(NearbyPlaceFragment.java:180)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at com.example.twigglebeta4.NearbyPlaceFragment$ExecuteQuery.onPostExecute(NearbyPlaceFragment.java:1)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at android.os.AsyncTask.finish(AsyncTask.java:631)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at android.os.Handler.dispatchMessage(Handler.java:99)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at android.os.Looper.loop(Looper.java:137)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at android.app.ActivityThread.main(ActivityThread.java:5328)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at java.lang.reflect.Method.invokeNative(Native Method)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at java.lang.reflect.Method.invoke(Method.java:511)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
    09-08 15:07:17.660: E/AndroidRuntime(31947):    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:2)

尝试:

//Adapter to control cell items
listViewAdapter = new ListView_Adapter(getActivity().getBaseContext());