使用JSON填充listView时的NPE

时间:2013-05-12 04:48:14

标签: json parsing listview exception android-asynctask

public class DisplayServiceActivity extends ListActivity {
private ListView listOfServices;

//JSONArrays?
JSONArray directory = null; 

//JSON Node names
private static String TAG_ID = "id";
private static String TAG_NAME= "name";
private static String TAG_DIRECTORY = "Categories";
private final static String url;
JSONObject json;
jsonParser jParser = new jsonParser();

@SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Request request = new Request();
    request.execute();

    listOfServices =getListView(); //get builtin listView


    ArrayList<HashMap<String, String>> directoryList = new ArrayList<HashMap<String, String>>();

    try{
        //getting Array
        directory = json.getJSONArray(TAG_DIRECTORY);

        for(int i= 0; i<directory.length(); i++){
            JSONObject addItem =directory.getJSONObject(i);

            //store each item in variable 
            String id = addItem.getString(TAG_ID);
            String name= addItem.getString(TAG_NAME);

            //create new HashMap
            HashMap<String,String> map = new HashMap<String, String>();

            //add each child node to HashMap key
            map.put(TAG_ID, id);
            map.put(TAG_NAME, name);

            //adding HashList to ArrarList
            directoryList.add(map);
        }

    } catch (JSONException e){
        e.printStackTrace();
    }

    ListAdapter adapter = new SimpleAdapter(this,
            directoryList, 
            R.layout.list_item, 
            new String[] { TAG_ID,TAG_NAME }, 
            new int[] { android.R.id.text1,android.R.id.text2 });

    setListAdapter(adapter);
    setContentView(R.layout.service);
    // Make sure we're running on Honeycomb or higher to use ActionBar APIs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // Show the Up button in the action bar.
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }
}// end of onCreate Method

public class Request extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params) {
        json = jParser.getJSONfromURL(url);
        return null;
    }
    @Override
    protected void onPostExecute(Void v) {          
        super.onPostExecute(v);
    }

}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

我正在尝试使用Json在从按钮开始新活动时填充listView。在调试时我收到了NPE。 这是我启动活动时的日志猫,然后单击按钮以启动displayServicesActivity

----------
05-12 00:36:57.012: I/Adreno200-EGLSUB(18696): <ConfigWindowMatch:2081>: Format RGBA_8888.

05-12 00:36:57.022: D/memalloc(18696): /dev/pmem: Mapped buffer base:0x50755000 size:3112960 offset:2498560 fd:54

05-12 00:36:57.243: D/memalloc(18696): /dev/pmem: Mapped buffer base:0x50c44000 size:4956160 offset:4341760 fd:57

05-12 00:37:05.511: D/memalloc(18696): /dev/pmem: Mapped buffer base:0x511fe000 size:2416640 offset:1802240 fd:60

05-12 00:37:07.853: W/dalvikvm(18696): threadid=1: thread exiting with uncaught exception (group=0x40a601f8)

05-12 00:37:07.863: E/AndroidRuntime(18696): FATAL EXCEPTION: main

05-12 00:37:07.863: E/AndroidRuntime(18696): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hstnc_activity/com.example.hstnc_activity.DisplayServiceActivity}: java.lang.NullPointerException

05-12 00:37:07.863: E/AndroidRuntime(18696):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at android.app.ActivityThread.access$600(ActivityThread.java:123)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at android.os.Handler.dispatchMessage(Handler.java:99)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at android.os.Looper.loop(Looper.java:137)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at android.app.ActivityThread.main(ActivityThread.java:4424)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at java.lang.reflect.Method.invokeNative(Native Method)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at java.lang.reflect.Method.invoke(Method.java:511)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:812)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:579)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at dalvik.system.NativeStart.main(Native Method)

05-12 00:37:07.863: E/AndroidRuntime(18696): Caused by: java.lang.NullPointerException

05-12 00:37:07.863: E/AndroidRuntime(18696):    at com.example.hstnc_activity.DisplayServiceActivity.onCreate(DisplayServiceActivity.java:59)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at android.app.Activity.performCreate(Activity.java:4465)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)

05-12 00:37:07.863: E/AndroidRuntime(18696):    at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)

05-12 00:37:07.863: E/AndroidRuntime(18696):    ... 11 more

05-12 00:37:08.193: E/JSON Parser Error(18696): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

1 个答案:

答案 0 :(得分:0)

在您调用方法JSONArray之前,AsyncTask似乎没有填充length(),因此它会返回null,因此您NPE 1}}。

将该代码放入onPostExecute(),以便在doInBackground()完成后才会运行,并且会在UI Thread上运行