2015-11-04 100 views
0

我一直有這個問題一段時間了,我不明白爲什麼它沒有得到JSON .. It should display the info from here..。該應用程序崩潰,出現以下錯誤,我無法弄清楚。錯誤是什麼意思? DoInBackground錯誤?沒有得到JSON到列表視圖

錯誤

11-04 14:21:27.437 1356-1541/me.janvandijk.receptenapp E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2 
Process: me.janvandijk.receptenapp, PID: 1356 
java.lang.RuntimeException: An error occured while executing doInBackground() 
     at android.os.AsyncTask$3.done(AsyncTask.java:304) 
     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 
     at java.util.concurrent.FutureTask.setException(FutureTask.java:222) 
     at java.util.concurrent.FutureTask.run(FutureTask.java:242) 
     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
     at java.lang.Thread.run(Thread.java:818) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference 
     at me.janvandijk.receptenapp.Recept$retrievedata.doInBackground(Recept.java:62) 
     at me.janvandijk.receptenapp.Recept$retrievedata.doInBackground(Recept.java:54) 
     at android.os.AsyncTask$2.call(AsyncTask.java:292) 
     at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
     at java.lang.Thread.run(Thread.java:818) 

package me.janvandijk.receptenapp; 


public class Recept extends Activity { 

String receptid; 
private ProgressDialog pDialog; 
private static String url = "http://janvandijk.me/zooi/receptenapp/getrecipes.php?type=request&datatype=recept&id="; 

ListView lv=(ListView)findViewById(R.id.receptList); 

// JSON Node names 
private static final String TAG_NAAM = "naam"; 
private static final String TAG_AUTEUR = "unaam"; 
private static final String TAG_BESCHRIJVING = "beschrijving"; 
private static final String TAG_INGREDIENTEN = "ingredienten"; 
private static final String TAG_BEREIDING = "bereiding"; 
private static final String TAG_RATING = "id"; 

// contacts JSONArray 
JSONArray recept = null; 

// Hashmap for ListView 
ArrayList<HashMap<String, String>> receptList; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_recept); 
    //showToast(); 
    //new ReceptAsynTask().execute("http://janvandijk.me/zooi/receptenapp/getrecipes.php?type=request&datatype=recept&id=" + receptid); 

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


    new GetRecept().execute(); 
} 



private class GetRecept extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // Showing progress dialog 
     pDialog = new ProgressDialog(Recept.this); 
     pDialog.setMessage("Please wait..."); 
     pDialog.setCancelable(false); 
     pDialog.show(); 

    } 

    @Override 
    protected Void doInBackground(Void... arg0) { 
     // Creating service handler class instance 
     ServiceHandler sh = new ServiceHandler(); 

     // Making a request to url and getting response 
     String finalurl = url+"1"; 
     String jsonStr = sh.makeServiceCall(finalurl, ServiceHandler.GET); 

     Log.d("Response: ", "> " + jsonStr); 

     if (jsonStr != null) { 
      try { 
       JSONObject jsonObj = new JSONObject(jsonStr); 

       // Getting JSON Array node 
       recept = jsonObj.getJSONArray("0"); 

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

        String naam = c.getString(TAG_NAAM); 
        String auteur = c.getString(TAG_AUTEUR); 
        String bereiding = c.getString(TAG_BEREIDING); 
        String beschrijving = c.getString(TAG_BESCHRIJVING); 
        String ingredienten = c.getString(TAG_INGREDIENTEN); 
        String rating = c.getString(TAG_RATING); 



        // tmp hashmap for single contact 
        HashMap<String, String> receptje = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 
        receptje.put(TAG_NAAM, naam); 
        receptje.put(TAG_AUTEUR, auteur); 
        receptje.put(TAG_BEREIDING, bereiding); 
        receptje.put(TAG_BESCHRIJVING, beschrijving); 
        receptje.put(TAG_INGREDIENTEN, ingredienten); 
        receptje.put(TAG_RATING, rating); 


        // adding contact to contact list 
        receptList.add(receptje); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } else { 
      Log.e("ServiceHandler", "Couldn't get any data from the url"); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     super.onPostExecute(result); 
     // Dismiss the progress dialog 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 
     /** 
     * Updating parsed JSON data into ListView 
     * */ 
     ListAdapter adapter = new SimpleAdapter(
       Recept.this, receptList, 
       R.layout.recept_item, new String[] { TAG_NAAM, TAG_AUTEUR, 
       TAG_BEREIDING, TAG_INGREDIENTEN, TAG_BESCHRIJVING, TAG_RATING }, new int[] { R.id.receptTitel, 
       R.id.receptAuteur, R.id.bereidingText, R.id.ingredientenText, R.id.beschrijvingText, R.id.receptRating }); 

     lv.setAdapter(adapter); 

    } 

} 


public void setText(String string){ 
    //tv.setText(string); 
} 

public void showToast(){ 
    Toast.makeText(getApplicationContext(), "Bezig met laden recept met ID "+receptid, Toast.LENGTH_LONG).show(); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_recept, menu); 
    //TextView view = (TextView) findViewById(R.id.testje); 
    //view.setText(receptid); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

}

public class serviceHandler{ 


static String response = null; 
public final static int GET = 1; 
public final static int POST = 2; 

public ServiceHandler() { 

} 

/** 
* Making service call 
* @url - url to make request 
* @method - http request method 
* */ 
public String makeServiceCall(String url, int method) { 
    return this.makeServiceCall(url, method, null); 
} 

/** 
* Making service call 
* @url - url to make request 
* @method - http request method 
* @params - http request params 
* */ 
public String makeServiceCall(String url, int method, 
           List<NameValuePair> params) { 
    try { 
     // http client 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpEntity httpEntity = null; 
     HttpResponse httpResponse = null; 

     // Checking http request method type 
     if (method == POST) { 
      HttpPost httpPost = new HttpPost(url); 
      // adding post params 
      if (params != null) { 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 
      } 

      httpResponse = httpClient.execute(httpPost); 

     } else if (method == GET) { 
      // appending params to url 
      if (params != null) { 
       String paramString = URLEncodedUtils 
         .format(params, "utf-8"); 
       url += "?" + paramString; 
      } 
      HttpGet httpGet = new HttpGet(url); 

      httpResponse = httpClient.execute(httpGet); 

     } 
     httpEntity = httpResponse.getEntity(); 
     response = EntityUtils.toString(httpEntity); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return response; 

} 

}

新的錯誤

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference 
     at me.janvandijk.receptenapp.Recept$GetRecept.onPostExecute(Recept.java:147) 
     at me.janvandijk.receptenapp.Recept$GetRecept.onPostExecute(Recept.java:63) 
     at android.os.AsyncTask.finish(AsyncTask.java:636) 
     at android.os.AsyncTask.access$500(AsyncTask.java:177) 
     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653) 
     at android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:135) 
     at android.app.ActivityThread.main(ActivityThread.java:5254) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:372) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
+0

你檢查你在這些行中得到了什麼: httpEntity = httpResponse.getEntity(); response = EntityUtils.toString(httpEntity); –

+0

Log.d(「Response:」,「>」+ jsonStr);'line? –

+0

我無法在您提供的JSON中看到「rating」。 –

回答

2

在你的堆棧跟蹤這一重要的路線是:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference


二錯誤:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

這意味着你正在呼籲setAdapter對象(LV)爲空:

lv.setAdapter(adapter); 

在活動的佈局已膨脹之前,您不能使用findViewById。這就是爲什麼lv爲空。你應該改變這一行:

ListView lv=(ListView)findViewById(R.id.receptList); 

...這樣的:

ListView lv; 

...這增加的onCreate:

lv = (ListView)findViewById(R.id.receptList); 

你也應該閱讀起來在空對象引用上,它們很常見。

+0

我需要刪除toString,因爲它們已經是字符串..? –

+0

我不確定,你的堆棧跟蹤顯示它發生在'me.janvandijk.receptenapp.Recept $ retrieveata'中,我沒有看到名爲'retrieveata'的內部類。你確定你發佈的代碼是最新的嗎? –

+0

我修好了!內容加載之前,我正在定義lv。現在我得到新的錯誤tho .... –