2017-04-18 20 views
0

データベース(phpmyadmin)からデータを取得し、それをListViewまたはTextViewに入れるためにjsonに変換しようとしていますが、アプリケーションを実行すると閉じるとログを確認するとき例外が見つかりました。AsyncTaskで致命的なエラーが発生しました

この私のコード:

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ファイル:

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; 
} 

}

エラーメッセージ:

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)  

答えて

0

主な問題は、ライン124 JSONParserクラスは、任意のJSONを返すされていないので、これが起こっているであなたのJSONParserクラスであり、得られるJSONはnullで、あなたはnullをJSONオブジェクトの関数のgetInt()を呼び出しています、それはなぜNullPointerExceptionです。

+0

どうすればいいですか? –

+0

result.toString()のトーストを作成し、何かを表示するかどうかを確認する必要があります。 –

+0

それは何も表示されません。 –

関連する問題