2015-07-08 3 views
0

Я уже читал данные из своей базы данных на Android. Я скопировал код и снова использовал его в своем другом приложении, он дал мне эту ошибку.java.lang.NullPointerException: попытка вызвать виртуальный метод при ссылке на нулевой объект

LogCat:

07-08 08:52:24.422: E/Buffer Error(2636): Error converting result java.lang.NullPointerException: lock == null 
07-08 08:52:24.422: E/JSON Parser(2636): Error parsing data org.json.JSONException: End of input at character 0 of 
07-08 08:52:24.423: D/AndroidRuntime(2636): Shutting down VM 
07-08 08:52:24.424: E/AndroidRuntime(2636): FATAL EXCEPTION: main 
07-08 08:52:24.424: E/AndroidRuntime(2636): Process: com.example.purplerose, PID: 2636 
07-08 08:52:24.424: E/AndroidRuntime(2636): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.purplerose/com.example.purplerose._Appetizer}: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference 

PHP КОД уже появляется

<?PHP 
include_once("connection.php"); 
$sql = "SELECT MenuID, Name, Description2, Price FROM menu"; 
$result = mysqli_query($con,$sql); 
$json = array(); 

if(mysqli_num_rows($result)){ 
while($row=mysqli_fetch_assoc($result)){ 
$json['menu'][]=$row; 
} 
} 
mysqli_close($con); 
echo json_encode($json); ?> 

JSONParser

public class JSONParser { 

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

// constructor 
public JSONParser() { 

} 


public JSONObject getJSONFromUrl(final String url) { 

    // Making HTTP request 
    try { 
     // Construct the client and the HTTP request. 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     // Execute the POST request and store the response locally. 
     HttpResponse httpResponse = httpClient.execute(httpPost); 
     // Extract data from the response. 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     // Open an inputStream with the data content. 
     is = httpEntity.getContent(); 

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

    try { 
     // Create a BufferedReader to parse through the inputStream. 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     // Declare a string builder to help with the parsing. 
     StringBuilder sb = new StringBuilder(); 
     // Declare a string to store the JSON object data in string form. 
     String line = null; 

     // Build the string until null. 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 

     // Close the input stream. 
     is.close(); 
     // Convert the string builder data to an actual string. 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // Try to 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 the JSON Object. 
    return jObj; 

} 


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

}} 

JAVA код

ListView mListView = (ListView) findViewById(R.id.listView1); 

    String url = "http://10.0.2.2/purple/readMenu.php"; 
    try { 
     JSONParser jParser = new JSONParser(); 
     JSONObject table = jParser.getJSONFromUrl(url); 
     JSONArray data = table.getJSONArray("menu"); 
     //JSONArray data = new JSONArray(getJSONUrl(url)); 
     final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>(); 
     HashMap<String, String> map; 

     for(int i = 0; i < data.length(); i++){ 
      JSONObject c = data.getJSONObject(i); 

      map = new HashMap<String, String>(); 
      map.put("MenuID", c.getString("MenuID")); 
      map.put("Name", c.getString("Name")); 
      map.put("Description2", c.getString("Description2")); 
      map.put("Price", c.getString("Price")); 

      MyArrList.add(map); 

     } 

     SimpleAdapter sAdap; 
     sAdap = new SimpleAdapter(_Appetizer.this, MyArrList, R.layout.menulist_arrangement, 
       new String[] {"Name", "Description2", "Price", "MenuID"}, new int[] {R.id.lblName, R.id.lblDesc2, R.id.lblPrice, R.id.lblMenuID});  
     mListView.setAdapter(sAdap); 

     final AlertDialog.Builder viewDetail = new AlertDialog.Builder(this); 
     // OnClick Item 
     mListView.setOnItemClickListener(new OnItemClickListener() { 
      public void onItemClick(AdapterView<?> myAdapter, View myView, 
        int position, long mylng) { 

       String _Name = MyArrList.get(position).get("Name") 
         .toString(); 
       String _Desc2 = MyArrList.get(position).get("Description2") 
         .toString(); 
       String _Price = MyArrList.get(position).get("Price") 
         .toString(); 
       String _MenuID = MyArrList.get(position).get("MenuID") 
         .toString(); 
       //String sMemberID = ((TextView) myView.findViewById(R.id.ColMemberID)).getText().toString(); 
       // String sName = ((TextView) myView.findViewById(R.id.ColName)).getText().toString(); 
       // String sTel = ((TextView) myView.findViewById(R.id.ColTel)).getText().toString(); 

       viewDetail.setIcon(android.R.drawable.btn_star_big_on); 
       viewDetail.setTitle(_Name); 
       viewDetail.setMessage("Name : " + _Name + "\n" 
         + "Description : " + _Desc2 + "\n" + "Price : " + _Price + "\n" + "ID: " + _MenuID); 
       viewDetail.setPositiveButton("OK", 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, 
            int which) { 
           // TODO Auto-generated method stub 
           dialog.dismiss(); 
          } 
         }); 
       viewDetail.show();     
      } 

     }); 

    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     Log.e("Log", "Failed" +e); 
     e.printStackTrace(); 
    }  

Двойная проверка класса JSONParser. или мой java-код. я действительно не могу сказать, где нулевой указатель.

+0

Возможный дубликат [Что такое Исключение нулевого указателя и как его исправить?] (Http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how -do-i-fix-it) – Gosu

+0

решил мой вопрос. его любопытные объятия. я забыл предоставить разрешение на интернет. – LevLevinstine

ответ

0

После прочтения исходного кода и журнала исключений, я считаю, что основной причиной вашего NPE является то, что вы пытаетесь выполнить сетевую операцию в потоке пользовательского интерфейса, что запрещено Google на Android 3+. Вы можете использовать AsyncTask для доступа к сети.

Смежные вопросы