drux41001 2015-07-08 01:16
浏览 458

java.lang.NullPointerException:尝试在空对象引用上调用虚方法

I was already reading the data from my database to android. I copied the code and used it again in my other app it gave me this error.

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 data is already showing up

<?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 + "
");
        }

        // 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 + "
");
        }
        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 Code

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 + "
"
                        + "Description : " + _Desc2 + "
" + "Price : " + _Price + "
" + "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();
    }       

Double check the JSONParser class. or my java code. i really cant tell where is the null pointer.

  • 写回答

1条回答 默认 最新

  • duancai9010 2015-07-08 02:13
    关注

    After reading your source code and the exception log, I think the root cause of your NPE is that you are trying to perform network operation on UI thread, which is forbidden by Google on Android 3+. You can use AsyncTask to access the network.

    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站