簡體   English   中英

java.lang.NullPointerException:嘗試在空對象引用上調用虛擬方法

[英]java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

我已經從數據庫讀取數據到android。 我復制了代碼,並在其他應用程序中再次使用它,這給了我這個錯誤。

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 CODE數據已經顯示

<?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代碼。 我真的不能告訴空指針在哪里。

閱讀完源代碼和異常日志后,我認為您的NPE的根本原因是您試圖在UI線程上執行網絡操作,這是Google在Android 3+上禁止的。 您可以使用AsyncTask訪問網絡。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM