2017-04-18 5 views
0

Ich versuche, meine Daten aus der Datenbank (phpmyadmin) zu nehmen und in Json konvertieren, um es in ListView oder TextView, aber wenn ich die Anwendung ausführen schließen und wenn ich das Protokoll I überprüfen eine Ausnahme gefunden.Ich habe einen fatalen Fehler mit AsyncTask android

dies mein Code:

MainActivity.java

public class MainActivity extends AppCompatActivity { 

ProgressDialog pDialog; 
// Creating JSON Parser object 

ListView lv; 
ArrayList<HashMap<String, String>> productsList; 

// url to get all products list 
private static String url_all_products = "http://192.168.0.100/takeofftravel/test.php"; 
// products JSONArray 
JSONArray products = null; 
int error=0; 
// JSON Node names 
private static final String TAG_SUCCESS = "success"; 
private static final String TAG_NOTIF = "notif"; 
private static final String TAG_PID = "id"; 
private static final String TAG_Type = "type"; 
private static final String TAG_REQUETE = "requete"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    // Hashmap for ListView. 
    productsList = new ArrayList<HashMap<String, String>>(); 
    // Get listview 
    lv = (ListView)findViewById(R.id.listView); 
    // Loading products in Background Thread 
    new LoadAllProducts().execute(); 



    // on seleting single product 
    // launching Edit Product Screen 
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, 
           int position, long id) { 
    /*   HashMap<String,String> map=new HashMap<String, String>(); 
      map=(HashMap<String,String>)lv.getAdapter().getItem(position); 
      String ide=map.get(TAG_PID); 
      Toast.makeText(All.this,ide,Toast.LENGTH_LONG).show(); 
      Intent i=new Intent(getApplicationContext(),Detail.class); 
      i.putExtra("id",ide); 
      startActivity(i); 
      finish();*/ 
     } 
    }); 

} 



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

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage("Loading..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 

    /** 
    * getting All products from url 
    * */ 
    protected String doInBackground(String... args) { 
     // Building Parameters 
     HashMap<String, String> params = new HashMap<String, String>(); 
     JSONParser jParser = new JSONParser(); 
     // getting JSON string from URL 

     JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); 

     // Check your log cat for JSON reponse 
     Log.d("All Products: ", json.toString()); 






     // Checking for SUCCESS TAG 
     int success = 0; 
     try { 
      success = json.getInt(TAG_SUCCESS); 
      if (success == 1) { 
       // products found 
       // Getting Array of Products 
       products = json.getJSONArray(TAG_NOTIF); 

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

        // Storing each json item in variable 
        String id = c.getString(TAG_PID); 
        String type = c.getString(TAG_Type); 
        String requete=c.getString(TAG_REQUETE); 

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

        // adding each child node to HashMap key => value 
        map.put(TAG_PID, id); 
        map.put(TAG_Type, type); 
        map.put(TAG_REQUETE,requete); 

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



     return null; 
    } 

    /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 
    protected void onPostExecute(String file_url) { 
     // dismiss the dialog after getting all products 
     pDialog.dismiss(); 
     // updating UI from Background Thread 
     // runOnUiThread(new Runnable() { 
     //  public void run() { 
     /** 
     * Updating parsed JSON data into ListView 
     * */ 
     ListAdapter adapter = new SimpleAdapter(
       MainActivity.this, productsList, 
       R.layout.item, new String[] { TAG_PID, 
       TAG_Type,TAG_REQUETE}, 
       new int[] { R.id.pid, R.id.nom,R.id.nature }); 
     // updating listview 
     lv.setAdapter(adapter); 
     // } 
     // }); 

    } 

} 

}

JSONParse.java Datei:

public class JSONParser { 
String charset = "UTF-8"; 
HttpURLConnection conn; 
DataOutputStream wr; 
StringBuilder result; 
URL urlObj; 
JSONObject jObj = null; 
StringBuilder sbParams; 
String paramsString; 

public JSONObject makeHttpRequest(String url, String method, 
            HashMap<String, String> params) { 

    sbParams = new StringBuilder(); 
    int i = 0; 
    for (String key : params.keySet()) { 
     try { 
      if (i != 0){ 
       sbParams.append("&"); 
      } 
      sbParams.append(key).append("=") 
        .append(URLEncoder.encode(params.get(key), charset)); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } 
     i++; 
    } 

    if (method.equals("POST")) { 
     // request method is POST 
     try { 
      urlObj = new URL(url); 

      conn = (HttpURLConnection) urlObj.openConnection(); 

      conn.setDoOutput(true); 

      conn.setRequestMethod("POST"); 

      conn.setRequestProperty("Accept-Charset", charset); 

      conn.setReadTimeout(10000); 
      conn.setConnectTimeout(15000); 

      conn.connect(); 

      paramsString = sbParams.toString(); 

      wr = new DataOutputStream(conn.getOutputStream()); 
      wr.writeBytes(paramsString); 
      wr.flush(); 
      wr.close(); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    else if(method.equals("GET")){ 
     // request method is GET 

     if (sbParams.length() != 0) { 
      url += "?" + sbParams.toString(); 
     } 

     try { 
      urlObj = new URL(url); 

      conn = (HttpURLConnection) urlObj.openConnection(); 

      conn.setDoOutput(false); 

      conn.setRequestMethod("GET"); 

      conn.setRequestProperty("Accept-Charset", charset); 

      conn.setConnectTimeout(15000); 

      conn.connect(); 

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

    } 

    try { 
     //Receive the response from the server 
     InputStream in = new BufferedInputStream(conn.getInputStream()); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
     result = new StringBuilder(); 
     String line; 
     while ((line = reader.readLine()) != null) { 
      result.append(line); 
     } 

     Log.d("JSON Parser", "result: " + result.toString()); 

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

    conn.disconnect(); 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(result.toString()); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON Object 
    return jObj; 
} 

}

die Fehlermeldung:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1 
       Process: com.example.asus.json, PID: 11657 
       java.lang.RuntimeException: An error occured while executing doInBackground() 
        at android.os.AsyncTask$3.done(AsyncTask.java:300) 
        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:841) 
       Caused by: java.lang.NullPointerException 
        at com.example.asus.json.JSONParser.makeHttpRequest(JSONParser.java:124) 
        at com.example.asus.json.MainActivity$LoadAllProducts.doInBackground(MainActivity.java:100) 
        at com.example.asus.json.MainActivity$LoadAllProducts.doInBackground(MainActivity.java:75) 
        at android.os.AsyncTask$2.call(AsyncTask.java:288) 
        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:841)  

Antwort

0

Das Hauptproblem ist, mit Ihrer JSONParser Klasse an der Linie 124. Dies geschieht als JSONParser Klasse ist keine JSON zurückkehrt und die resultierende JSON ist null und Sie rufen die Funktion getInt() auf dem Null-JSON-Objekt , deshalb die NullPointerException.

+0

Also was soll ich tun? –

+0

Sie sollten versuchen, einen Toast für result.toString() zu erstellen und prüfen, ob etwas angezeigt wird. –

+0

es zeigt nichts. –

Verwandte Themen