2016-03-23 10 views
0

このコードであるサーバに存在するデータベースからデータを表示するために使用されるmainactivitv.javaクラスE /バッファエラー:エラー変換結果java.lang.NullPointerExceptionが:ロック== NULL

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 

import org.apache.http.NameValuePair; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.ListActivity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 

public class GetAllDevices extends ListActivity { 

    // Progress Dialog 
    private ProgressDialog pDialog; 

    // Creating JSON Parser object 
    JSONParser jParser = new JSONParser(); 

    ArrayList<HashMap<String, String>> productsList; 

    // url to get all products list 
    private static String url_all_products = "http://localhost/android_connect/db_connect.php"; 

    // JSON Node names 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_PRODUCTS = "data_9297"; 
    private static final String TAG_PID = "coldstorage_id"; 
    private static final String TAG_NAME = "device_id"; 
    private static final String TAG_DATE = "date"; 
    private static final String TAG_TIME = "time"; 
    private static final String TAG_TEMP = "temp"; 
    // products JSONArray 
    JSONArray products = null; 

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

     // Hashmap for ListView 
     productsList = new ArrayList<HashMap<String, String>>(); 

     // Loading products in Background Thread 
     new LoadAllProducts().execute(); 

     // Get listview 
     ListView lv = getListView(); 

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

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
            int position, long id) { 
       // getting values from selected ListItem 
       String pid = ((TextView) view.findViewById(R.id.pid)).getText() 
         .toString(); 

       // Starting new intent 
       Intent in = new Intent(getApplicationContext(), 
         Dashboard.class); 
       // sending pid to next activity 
       in.putExtra(TAG_PID, pid); 

       // starting new activity and expecting some response back 
       startActivityForResult(in, 100); 
      } 
     }); 

    } 

    // Response from Edit Product Activity 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     // if result code 100 
     if (resultCode == 100) { 
      // if result code 100 is received 
      // means user edited/deleted product 
      // reload this screen again 
      Intent intent = getIntent(); 
      finish(); 
      startActivity(intent); 
     } 

    } 

    /** 
    * Background Async Task to Load all product by making HTTP Request 
    * */ 
    class LoadAllProducts extends AsyncTask<String, String, String> { 

     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(GetAllDevices.this); 
      pDialog.setMessage("Loading products. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 

     /** 
     * getting All products from url 
     * */ 
     protected String doInBackground(String... args) { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      // getting JSON string from URL 
      JSONObject json = jParser.makeHttpRequest(url_all_products, "POST", params); 

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

      try { 
       // Checking for SUCCESS TAG 
       int success = json.getInt(TAG_SUCCESS); 

       if (success == 1) { 
        // products found 
        // Getting Array of Products 
        products = json.getJSONArray(TAG_PRODUCTS); 

        // 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 name = c.getString(TAG_NAME); 

         // 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_NAME, name); 

         // adding HashList to ArrayList 
         productsList.add(map); 
        } 
       } else { 
        // no products found 
        // Launch Add New product Activity 
        Intent i = new Intent(getApplicationContext(), 
          Threshold.class); 
        // Closing all previous activities 
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        startActivity(i); 
       } 
      } 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(
          GetAllDevices.this, productsList, 
          R.layout.list_item, new String[] { TAG_PID, 
          TAG_NAME}, 
          new int[] { R.id.pid, R.id.name }); 
        // updating listview 
        setListAdapter(adapter); 
       } 
      }); 

     } 

    } 
} 

これはこれはlogcatは

03-23 13:11:20.140 2282-2951/com.gopal.coldstorage E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null 
03-23 13:11:20.141 2282-2951/com.gopal.coldstorage D/jdwp: sendRequest : Len=0x45 
03-23 13:11:20.141 2282-2951/com.gopal.coldstorage D/jdwp: sendRequest : Len=0x44 
03-23 13:11:20.146 2282-2951/com.gopal.coldstorage E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 
03-23 13:11:20.149 2282-2951/com.gopal.coldstorage D/jdwp: sendRequest : Len=0x57 
03-23 13:11:20.155 2282-2951/com.gopal.coldstorage W/dalvikvm: threadid=12: thread exiting with uncaught exception (group=0x414bd9a8) 
03-23 13:11:20.156 2282-2959/com.gopal.coldstorage D/jdwp: sendRequest : Len=0x1D 
03-23 13:11:20.167 2282-2282/com.gopal.coldstorage D/OpenGLRenderer: Flushing caches (mode 0) 
03-23 13:11:20.196 2282-2951/com.gopal.coldstorage E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1 
                    java.lang.RuntimeException: An error occured while executing doInBackground() 
                     at android.os.AsyncTask$3.done(AsyncTask.java:299) 
                     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 
                     at java.util.concurrent.FutureTask.setException(FutureTask.java:219) 
                     at java.util.concurrent.FutureTask.run(FutureTask.java:239) 
                     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
                     at java.lang.Thread.run(Thread.java:838) 
                     Caused by: java.lang.NullPointerException 
                     at com.gopal.coldstorage.GetAllDevices$LoadAllProducts.doInBackground(GetAllDevices.java:132) 
                     at com.gopal.coldstorage.GetAllDevices$LoadAllProducts.doInBackground(GetAllDevices.java:107) 
                     at android.os.AsyncTask$2.call(AsyncTask.java:287) 
                     at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
                     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)  
                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)  
                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)  
                     at java.lang.Thread.run(Thread.java:838)  

これはを示したものですJSONParser.javaクラス

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

    // function get json from url 
    // by making HTTP POST or GET mehtod 
    public JSONObject makeHttpRequest(String url, String method, 
             List<NameValuePair> params) { 

     // Making HTTP request 
     try { 

      // check for request method 
      if(method == "POST"){ 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      }else if(method == "GET"){ 
       // request method is GET 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      } 


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

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

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

     // return JSON String 
     return jObj; 

    } 
} 

ですdb_connect.phpファイル

<?php 
$response = array(); 



$link = mysqli_connect("localhost", "root", "", "received_data"); 

/* check connection */ 
if (mysqli_connect_errno()) { 
    printf("Connect failed: %s\n", mysqli_connect_error()); 
    exit(); 
} 

$result = mysqli_query($link,"SELECT * FROM data_9297 ORDER by coldstorage_id "); 
if (mysqli_num_rows($result) > 0) { 

// looping through all results 

    // products node 

    $response["data_9297"] = array(); 


    while($row = mysqli_fetch_array($result, MYSQLI_NUM)) 
{ 
     // temp user array 

     $data = array(); 


/* numeric array */ 
$data["coldstorage_id"]= $row[0] ; 
$data["device_id"]= $row[1] ; 
$data["date"]= $row[2]; 
$data["time"]= $row[3] ; 
$data["temp"]= $row[4] ; 
array_push($response["data_9297"], $data); 
} 
$response["success"] = 1; 


    // echoing JSON response 

    echo json_encode($response); 

} 
else { 

    // no products found 

$response["success"] = 0; 

    $response["message"] = "No devices found"; 


    // echo no users JSON 

echo json_encode($response); 

} 



/* free result set */ 
mysqli_free_result($result); 

/* close connection */ 
mysqli_close($link); 
?> 
+0

エラーが発生している行はありますか。 –

+0

タスクに行番号132と107を指定できますか? – goonerDroid

+0

132行目のように見える** Log.d( "All Products:"、json.toString()); **、したがってjsonはnullです。 Log.e(...)であるべき多くのprintStacktraceがあります。 JSONParserクラスを見て、そこに問題がなければなりません。 –

答えて

0

おそらくあなたは

Log.d("All Products: ", json.toString()); 

でクラッシュを取得しているが、JSONオブジェクトがnullであるようです。

+0

watはLog.dの代わりにコードでなければなりません(...) –

関連する問題