1

我有这个问题:当我启动我的活动时,由于 NullPointerException,它无法访问 doInBackground 方法。但是指针存在,我可以访问它并在 System.out 中显示它有没有人看到这里有什么样的问题?谢谢。

有我的代码

public class Request extends ListActivity{

private static String DEBUG_TAG = "Request";
private ArrayList<HashMap<String, String>> contactList;
private ProgressDialog pDialog;

// url to make request
private static String url = "http://10.0.2.2:1234/?query=ma";
private InputStream is=null;

// 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";

// contacts JSONArray
JSONArray contacts = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.response_display);

    contactList = new ArrayList<HashMap<String, String>>();
    new LoadAllData().execute(url);

    ListView lv = getListView();

}

class LoadAllData extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.i("MyAsyncTask","MyAsyncTask Started");
        pDialog = new ProgressDialog(Request.this);
        pDialog.setMessage("Loading Data. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        Log.i("MyAsyncTask",args[0] + " in background.");
        GetJSONFromUrl instance = new GetJSONFromUrl();
        JSONObject jsonObj = instance.getJSONobjectFromURL(args[0]);
        try {
            contacts = jsonObj.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);
                c.getString(TAG_ADDRESS);
                c.getString(TAG_GENDER);

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

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

    }

    protected void onPostExecute() {
        Log.i("MyAsyncTask","onPostExecute ");
        pDialog.dismiss();
        runOnUiThread(new Runnable() {
        public void run() {
            ListAdapter adapter = new SimpleAdapter(Request.this,contactList, 
                                                    R.layout.list_item, 
                                                    new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE },
                                                    new int[]{R.id.name, R.id.email, R.id.mobile });
            setListAdapter(adapter);
            }
        });

    }   
}

我在一个单独的类中的方法

public class GetJSONFromUrl {

private static final String DEBUG_TAG = "GetJSONFromUrl";
private static InputStream myinputstream; 
private InputStream is = null;
private JSONObject jObj;
private String jsonString="";

//Constructor 
public GetJSONFromUrl(){
}

public JSONObject getJSONobjectFromURL(String url){ 
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.i(DEBUG_TAG,"Connection established");
        ObjectMapper anObjectMapper = new ObjectMapper(); 
        JsonParser parser;
        JsonNode node;
        Log.i(DEBUG_TAG,"Initializing catchJSON");
        try {
            JsonFactory jsonfactory = anObjectMapper.getFactory();
            parser = jsonfactory.createParser(is);
            node = parser.readValueAsTree();
            jsonString = anObjectMapper.writeValueAsString(node);
            JSONObject jObj = new JSONObject(jsonString);
            System.out.println("Result = " + jObj.toString());          

        } catch (JsonProcessingException e) {
            Log.i(DEBUG_TAG,"JsonProcessingException " + e);
        } catch (IOException e) {
            Log.i(DEBUG_TAG,"IOException " + e);
        } catch (JSONException e) {
            Log.i(DEBUG_TAG,"JSONException " + e);
        }
        is.close();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }
    return jObj;
}

public void catchValueFromJson(String url){
    JsonFactory jsonfactory = new JsonFactory();
    JsonParser jParser;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        jParser = jsonfactory.createParser(myinputstream);
        //loop
        while (jParser.nextToken() != JsonToken.END_ARRAY){
            while (jParser.nextToken() != JsonToken.END_OBJECT){
            String fieldname = jParser.getCurrentName();
            if("id".equals(fieldname)){
                // current token is "id",
                // move to next, which is "name"'s value
                jParser.nextToken();
                System.out.println(jParser.getText());
            }
            if ("name".equals(fieldname)) {
                  jParser.nextToken();
                  System.out.println(jParser.getText()); 
                }
            if ("email".equals(fieldname)) {
                  jParser.nextToken();
                  System.out.println(jParser.getText()); 
                }
            if ("address".equals(fieldname)) {
                  jParser.nextToken();
                  System.out.println(jParser.getText());
                }
            if ("gender".equals(fieldname)) {
                  jParser.nextToken();
                  System.out.println(jParser.getText());
                }

                if ("phone".equals(fieldname)) {
                  jParser.nextToken(); // current token is "{", move next
                  // messages is array, loop until token equal to "]"
                  while (jParser.nextToken() != JsonToken.END_OBJECT) {
                    String phonetype = jParser.getCurrentName();
                    if ("mobile".equals(phonetype)) {
                      jParser.nextToken();
                      System.out.println(jParser.getText()); 
                    }
                    if ("home".equals(phonetype)) {
                      jParser.nextToken();
                      System.out.println(jParser.getText());
                    }
                    if ("office".equals(phonetype)) {
                      jParser.nextToken();
                      System.out.println(jParser.getText());
                    }
                  }
                }
                }/* fin du deuxième while*/
        }/* fin du premier while*/

    } catch (JsonParseException e) {
        Log.e("log_tag", "Error JSONParse " + e.toString());
    } catch (IOException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }
}

}

这是我的 LogCat

10-30 12:26:24.474: I/MyAsyncTask(1712): MyAsyncTask Started
10-30 12:26:24.693: I/MyAsyncTask(1712): http://10.0.2.2:1234/?query=ma in background.
10-30 12:26:24.893: W/EGL_emulation(1712): eglSurfaceAttrib not implemented
10-30 12:26:24.998: W/EGL_emulation(1712): eglSurfaceAttrib not implemented
10-30 12:26:25.154: D/dalvikvm(1712): GC_CONCURRENT freed 121K, 2% free 8236K/8391K,         paused 20ms+6ms, total 84ms
10-30 12:26:25.254: I/GetJSONFromUrl(1712): Connection established
10-30 12:26:25.664: I/GetJSONFromUrl(1712): Initializing catchJSON
10-30 12:26:26.443: D/dalvikvm(1712): GC_CONCURRENT freed 268K, 5% free 8415K/8775K, paused 15ms+23ms, total 160ms
10-30 12:26:26.623: I/System.out(1712): Result = {"contacts":   [{"id":"c200","gender":"male","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"ravi@gmail.com","name":"Ravi Tamada"},{"id":"c201","gender":"male","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"johnny_depp@gmail.com","name":"Johnny Depp"},{"id":"c202","gender":"male","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"leonardo_dicaprio@gmail.com","name":"Leonardo Dicaprio"},{"id":"c203","gender":"male","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"john_wayne@gmail.com","name":"John Wayne"},{"id":"c204","gender":"female","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"angelina_jolie@gmail.com","name":"Angelina Jolie"},{"id":"c205","gender":"female","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"dido@gmail.com","name":"Dido"},{"id":"c206","gender":"female","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"adele@gmail.com","name":"Adele"},{"id":"c207","gender":"male","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"hugh_jackman@gmail.com","name":"Hugh Jackman"},{"id":"c208","gender":"male","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"will_smith@gmail.com","name":"Will Smith"},{"id":"c209","gender":"male","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"clint_eastwood@gmail.com","name":"Clint Eastwood"},{"id":"c2010","gender":"male","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"barack_obama@gmail.com","name":"Barack Obama"},{"id":"c2011","gender":"female","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"kate_winslet@gmail.com","name":"Kate Winslet"},{"id":"c2012","gender":"male","phone":{"office":"00 000000","home":"00 000000","mobile":"+91 0000000000"},"address":"xx-xx-xxxx,x - street, x - country","email":"eminem@gmail.com","name":"Eminem"}]}
10-30 12:26:26.633: W/dalvikvm(1712): threadid=12: thread exiting with uncaught exception (group=0xb4e61288)
10-30 12:26:26.663: E/AndroidRuntime(1712): FATAL EXCEPTION: AsyncTask #1
10-30 12:26:26.663: E/AndroidRuntime(1712): java.lang.RuntimeException: An error occured while executing doInBackground()
10-30 12:26:26.663: E/AndroidRuntime(1712):     at   android.os.AsyncTask$3.done(AsyncTask.java:299)
10-30 12:26:26.663: E/AndroidRuntime(1712):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-30 12:26:26.663: E/AndroidRuntime(1712):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-30 12:26:26.663: E/AndroidRuntime(1712):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
10-30 12:26:26.663: E/AndroidRuntime(1712):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-30 12:26:26.663: E/AndroidRuntime(1712):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-30 12:26:26.663: E/AndroidRuntime(1712):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-30 12:26:26.663: E/AndroidRuntime(1712):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-30 12:26:26.663: E/AndroidRuntime(1712):     at java.lang.Thread.run(Thread.java:856)
10-30 12:26:26.663: E/AndroidRuntime(1712): Caused by: java.lang.NullPointerException
10-30 12:26:26.663: E/AndroidRuntime(1712):     at com.example.test_bug.Request$LoadAllData.doInBackground(Request.java:94)
10-30 12:26:26.663: E/AndroidRuntime(1712):     at com.example.test_bug.Request$LoadAllData.doInBackground(Request.java:1)
10-30 12:26:26.663: E/AndroidRuntime(1712):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-30 12:26:26.663: E/AndroidRuntime(1712):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-30 12:26:26.663: E/AndroidRuntime(1712):     ... 5 more
10-30 12:26:27.114: I/MainActivity(1712): OnCreate_initialize_buttons_and_fields
10-30 12:26:27.114: I/MainActivity(1712): autoCompleteEnd
10-30 12:26:27.204: W/EGL_emulation(1712): eglSurfaceAttrib not implemented
4

2 回答 2

0

我认为这是您的问题,您的 HashMap 为空

   phone.getString(TAG_PHONE_OFFICE);

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

只需初始化上面的 Activity 类的 onCreate 方法

change it to -> HashMap<String,String> map=new HashMap<String, String>();  

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
于 2013-10-30T14:01:51.347 回答
0

正如评论中所讨论的:您的方法 ,getJSONobjectFromURL具有以下代码:JSONObject jObj = new JSONObject(jsonString); 问题是这与在类顶部声明的方法不同。 jObj因此,当您return jObj在函数结束时,实际上返回的是一个空白(null)对象,导致jsonObj在您的其他类中为 null。

最简单的解决方法是JSONObject jObj = new JSONObject(jsonString);变成jObj = new JSONObject(jsonString);

以防万一您看不到它,这是一个非常简单的示例,说明您的范围界定为何不起作用:http: //ideone.com/3oJudR

于 2013-10-30T14:08:19.607 回答