-2

这是我的代码,它在从 url 获取 json 时抛出 java 空指针异常。我已经在 android manifest 中授予了互联网权限,现在在新线程中获取 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
4

2 回答 2

0

你有这条线

JSONObject json = jParser.getJSONFromUrl(url);

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

于 2013-10-04T06:57:03.603 回答
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 指针异常

于 2013-10-04T06:57:55.293 回答