java Null指针获取JSON时的异常

时间:2013-10-04 06:45:08

标签: java android json

这是我的代码它从url.i获取json时抛出java null指针异常已经在android清单中给出了Internet权限,现在在新线程中获取url,因为它不允许在主要线程中进行网络活动

 package com.example.usa;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

public class Home extends Activity {
    // url to make request
    private static String url = "http://api.androidhive.info/contacts/";

    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";


    JSONArray contacts = null;



    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        final ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        final JSONParser jParser = new JSONParser();
        final JSONObject json = null ;
        // getting JSON string from URL
        new Handler().postDelayed(new Runnable() {



            @Override
            public void run() {

                Thread thread = new Thread()
                {
                    @Override
                    public void run() {
                        try {
                            while(true) {
                                JSONObject json = jParser.getJSONFromUrl(url);
                                sleep(1000);

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

                thread.start();




                //
                finish();
            }
        }, 5000);






       // JSONObject json = jParser.getJSONFromUrl(url);









new Handler().postDelayed(new Runnable() {



            @Override
            public void run() {

                 try {
                        // Getting Array of Contacts
                        contacts = json.getJSONArray(TAG_CONTACTS);

                        // looping through All Contacts
                        for(int i = 0; i < contacts.length(); i++){
                            JSONObject c = contacts.getJSONObject(i);

                            // Storing each json item in variable
                            String id = c.getString(TAG_ID);
                            String name = c.getString(TAG_NAME);
                            String email = c.getString(TAG_EMAIL);
                            String address = c.getString(TAG_ADDRESS);
                            String gender = c.getString(TAG_GENDER);

                            // Phone number is agin JSON Object
                            JSONObject phone = c.getJSONObject(TAG_PHONE);
                            String mobile = phone.getString(TAG_PHONE_MOBILE);
                            String home = phone.getString(TAG_PHONE_HOME);
                            String office = phone.getString(TAG_PHONE_OFFICE);

                            /////////////////////////// 
                            Log.w("ID",id);
                            Log.w("Name",name);
                            Log.w("Email",email);
                            Log.w("Gender",gender);
                            Log.w("mobile",mobile);
                            Log.w("home",home);
                            Log.w("office",office);
                            Log.w("address",address);

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

                            // adding each child node to HashMap key => value
                            map.put(TAG_ID, id);
                            map.put(TAG_NAME, name);
                            map.put(TAG_EMAIL, email);
                            map.put(TAG_PHONE_MOBILE, mobile);

                            // adding HashList to ArrayList
                            contactList.add(map);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                //
                finish();
            }
        }, 5000);



        // TODO Auto-generated method stub
    }

}

这是堆栈跟踪

10-04 06:39:24.830: D/dalvikvm(777): GC_FOR_ALLOC freed 15K, 4% free 4156K/4288K, paused 42ms, total 45ms
10-04 06:39:24.850: I/dalvikvm-heap(777): Grow heap (frag case) to 5.635MB for 1536016-byte allocation
10-04 06:39:25.040: D/dalvikvm(777): GC_FOR_ALLOC freed <1K, 3% free 5655K/5792K, paused 180ms, total 180ms
10-04 06:39:30.280: D/AndroidRuntime(777): Shutting down VM
10-04 06:39:30.280: W/dalvikvm(777): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
10-04 06:39:30.290: E/AndroidRuntime(777): FATAL EXCEPTION: main
10-04 06:39:30.290: E/AndroidRuntime(777): java.lang.NullPointerException
10-04 06:39:30.290: E/AndroidRuntime(777):  at com.example.usa.Home$2.run(Home.java:105)
10-04 06:39:30.290: E/AndroidRuntime(777):  at android.os.Handler.handleCallback(Handler.java:730)
10-04 06:39:30.290: E/AndroidRuntime(777):  at android.os.Handler.dispatchMessage(Handler.java:92)
10-04 06:39:30.290: E/AndroidRuntime(777):  at android.os.Looper.loop(Looper.java:137)
10-04 06:39:30.290: E/AndroidRuntime(777):  at android.app.ActivityThread.main(ActivityThread.java:5103)
10-04 06:39:30.290: E/AndroidRuntime(777):  at java.lang.reflect.Method.invokeNative(Native Method)
10-04 06:39:30.290: E/AndroidRuntime(777):  at java.lang.reflect.Method.invoke(Method.java:525)
10-04 06:39:30.290: E/AndroidRuntime(777):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-04 06:39:30.290: E/AndroidRuntime(777):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-04 06:39:30.290: E/AndroidRuntime(777):  at dalvik.system.NativeStart.main(Native Method)
10-04 06:39:34.957: D/dalvikvm(777): GC_FOR_ALLOC freed 261K, 6% free 6445K/6824K, paused 81ms, total 98ms
10-04 06:40:00.868: D/dalvikvm(777): GC_FOR_ALLOC freed 2688K, 36% free 5075K/7880K, paused 39ms, total 43ms
10-04 06:44:25.888: I/Process(777): Sending signal. PID: 777 SIG: 9

2 个答案:

答案 0 :(得分:0)

你有这一行

JSONObject json = jParser.getJSONFromUrl(url);

但你也有一个方法变量json,我认为你打算稍后使用它。

答案 1 :(得分:0)

问题在于:

JSONObject json = jParser.getJSONFromUrl(url);

在第一个线程中,您正在从URL中检索数据并将其解析为json,在第一个线程之后不久,您尝试从JSON对象 检索数据,其中很可能没有任何数据,因为它仍然忙于检索数据。

所以这不是一个好主意。 Retrieve and get data from JSON array in the same thread. This will save you alot of trouble.

其次,您将json解析的数据存储在第一个线程中的 本地json对象中,而不是全局的 ,并尝试使用null json对象来获取TAG_CONTACT数据。 这会导致NULL指针异常