2015-12-08 167 views
0

我試圖連接MYSQL與Android應用程序使用PHP和JSON文件,我現在面臨的問題是,JSONParser類總是返回null,我不知道爲什麼,因爲我可以查看我的JSON文件,它是有效的Android JSON解析返回null

,我也是我在我的代碼兩個例外,第一個是:

 12-08 09:17:43.486 29666-29666/alharbi.atheer.gym_managment_system E/OpenGLRenderer: Getting MAX_TEXTURE_SIZE from GradienCache 
     12-08 09:17:43.498 29666-29666/alharbi.astrong texttheer.gym_managment_system E/OpenGLRenderer: MAX_TEXTURE_SIZE: 16384 
     12-08 09:17:43.518 29666-29666/alharbi.atheer.gym_managment_system E/OpenGLRenderer: Getting MAX_TEXTURE_SIZE from Caches::initConstraints() 
     12-08 09:17:43.522 29666-29666/alharbi.atheer.gym_managment_system E/OpenGLRenderer: MAX_TEXTURE_SIZE: 16384 

第二個是:

12-08 09:17:46.526 29666-29740/alharbi.atheer.gym_managment_system E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null 
12-08 09:17:46.526 29666-29740/alharbi.atheer.gym_managment_system E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 

這是班上 包含問題

public class ViewInfo extends AppCompatActivity { 
    JSONParser jsonParser; 
    ProgressDialog progressDialog; 
    int value; 
    String[] names,emails,levels,ids, weights,hieghts,genders,bds,addresses,ages,phones; 
    ListView listView2; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_view_info); 
     jsonParser=new JSONParser(); 
     listView2=(ListView)findViewById(R.id.listView2); 

     new DisplayViewInfo().execute(); 
    } 




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

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      progressDialog=new ProgressDialog(ViewInfo.this); 
      progressDialog.setTitle("Wait..."); 
      progressDialog.show(); 
     } 




     @Override 
     protected String doInBackground(String... strings) { 

      List<NameValuePair> list= new ArrayList<NameValuePair>(); 
      // HashMap<String,String> list = new HashMap<>(); 


      // jsonObject=jsonParser.makeHttpRequest("http://192.168.56.1/myapp/ViewInfo.php","POST",list); 
      JSONObject jsonObject=jsonParser.makeHttpRequest("http://192.168.56.1/myapp/ViewInfo.php", "POST", list); 


      try{ 
       if(jsonObject!=null && !jsonObject.isNull("value")){ 


        value=jsonObject.getInt("value"); 
        JSONArray jsonArray=jsonObject.getJSONArray("Customers"); 
        names=new String[jsonArray.length()]; 
        emails=new String[jsonArray.length()]; 
        phones=new String[jsonArray.length()]; 
        ids=new String[jsonArray.length()]; 
        weights=new String[jsonArray.length()]; 
        hieghts=new String[jsonArray.length()]; 
        genders=new String[jsonArray.length()]; 
        levels=new String[jsonArray.length()]; 
        ages=new String[jsonArray.length()]; 
        addresses=new String[jsonArray.length()]; 
        bds=new String[jsonArray.length()]; 
        for(int i=0;i<jsonArray.length();i++){ 
         JSONObject objcet=jsonArray.getJSONObject(i); 
         ids[i]=objcet.getString("Customer_ID"); 
         names[i]=objcet.getString("Name"); 
         emails[i]=objcet.getString("Email"); 
         phones[i]=objcet.getString("Phone_number"); 
         weights[i]=objcet.getString("Weight"); 
         hieghts[i]=objcet.getString("Height"); 
         genders[i]=objcet.getString("Gender"); 
         levels[i]=objcet.getString("Level"); 
         ages[i]=objcet.getString("age"); 
         addresses[i]=objcet.getString("address"); 
         bds[i]=objcet.getString("Date_of_birth"); 


        } 
       }else{ 
        value=0; 
       } 

      }catch (Exception e){ 
       Log.d("ERROR", e.getMessage()); 
      } 

      return null; 
     } 
     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 
      if(value==1){ 
       Toast.makeText(getApplicationContext(), "Done...", Toast.LENGTH_LONG).show(); 
       ArrayAdapter<String> adapter=new ArrayAdapter<String>(ViewInfo.this,android.R.layout.simple_list_item_1,android.R.id.text1,names); 
       listView2.setAdapter(adapter); 
      }else if(value==0) 
       Toast.makeText(getApplicationContext(),"Error...",Toast.LENGTH_LONG).show(); 
      else Toast.makeText(getApplicationContext(),"OUT...",Toast.LENGTH_LONG).show(); 

      progressDialog.dismiss(); 
     } 


     } 





    } 

這是我的JSON解析器:

公共類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.equals("POST")){ 
      // request method is POST 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8")); 

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

     }else if(method.equals("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; 

} 

}

任何人都可以幫我嗎?由於這些錯誤,我一直在拼命尋找幾天

+1

可能的代碼[什麼是空指針異常,以及如何解決它?]的副本(http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i -fix-it) –

+0

你沒有得到有效的答覆。檢查你的http響應代碼,看看你是否得到'200'並檢查你的響應字符串,然後再嘗試創建JSONObject以確保它實際上是有效的JSON。 – NoChinDeluxe

+0

@drschultz你能告訴我如何檢查?這是我的第一個android和MySQL項目,所以我不太瞭解它 – Atheer

回答

1

從這個JSON錯誤的外觀來看,你似乎沒有得到有效的響應,而你的響應字符串只是空的。發生這種情況時,我通常會在構建Web服務調用的html響應代碼以及實際的字符串時檢查它們。這有助於確定Web服務是否是問題,或者是否您的Web服務調用是問題。

我應該提及的另一件事是,您正在使用您的網絡電話不推薦使用的代碼。 Apache的http代碼已從Android框架中刪除,因此您應該使用HttpURLConnection來進行Web服務調用。

今天我在一個漂亮的心情很好,而且我感覺有幫助,所以我只是想給你你應該使用獲得此JSON響應:)

//The JSON we will get back as a response from the server 
JSONObject jsonResponse = null; 

//Http connections and data streams 
URL url; 
HttpURLConnection httpURLConnection = null; 
OutputStreamWriter outputStreamWriter = null; 

try { 

    //open connection to the server 
    url = new URL("your_url_to_web_service"); 
    httpURLConnection = (HttpURLConnection) url.openConnection(); 

    //set request properties 
    httpURLConnection.setDoOutput(true); //defaults request method to POST 
    httpURLConnection.setDoInput(true); //allow input to this HttpURLConnection 
    httpURLConnection.setRequestProperty("Content-Type", "application/json"); //header params 
    httpURLConnection.setRequestProperty("Accept", "application/json"); //header params 
    httpURLConnection.setFixedLengthStreamingMode(jsonToSend.toString().getBytes().length); //header param "content-length" 

    //open output stream and POST our JSON data to server 
    outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream()); 
    outputStreamWriter.write(jsonToSend.toString()); 
    outputStreamWriter.flush(); //flush the stream when we're finished writing to make sure all bytes get to their destination 

    //prepare input buffer and get the http response from server 
    StringBuilder stringBuilder = new StringBuilder(); 
    int responseCode = httpURLConnection.getResponseCode(); 

    //Check to make sure we got a valid status response from the server, 
    //then get the server JSON response if we did. 
    if(responseCode == HttpURLConnection.HTTP_OK) { 

     //read in each line of the response to the input buffer 
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8")); 
     String line; 
     while ((line = bufferedReader.readLine()) != null) { 
      stringBuilder.append(line).append("\n"); 
     } 

     bufferedReader.close(); //close out the input stream 

    try { 
     //Copy the JSON response to a local JSONObject 
     jsonResponse = new JSONObject(stringBuilder.toString()); 
    } catch (JSONException je) { 
     je.printStackTrace(); 
    } 

} catch (IOException ioe) { 
    ioe.printStackTrace(); 
} finally { 
    if(httpURLConnection != null) { 
     httpURLConnection.disconnect(); //close out our http connection 
    } 

    if(outputStreamWriter != null) { 
     try { 
      outputStreamWriter.close(); //close our output stream 
     } catch (IOException ioe) { 
      ioe.printStackTrace(); 
     } 
    } 
} 

//Return the JSON response from the server. 
return jsonResponse;