簡體   English   中英

嘗試使用名稱字段從數據庫獲取數據時,應用程序無響應,然后崩潰

[英]App not responding and then crashing while trying to get data from the database using name field

我正在嘗試創建一個從URL獲取json對象的應用。 事實證明,這會不必要地令人沮喪,因為它會使應該加載並解析json對象的活動不斷崩潰。 它只是彈出消息“很遺憾,(AppName)已停止。” 然后退出該應用程序。 JSON中的數據永遠不會顯示在屏幕上。 這是帶有活動和JSON解析的代碼

JSONParser.class

    package com.example.android.andrtest1;
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.equals("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.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 (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).append("\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;

    }

    public JSONObject getJSONFromUrl(String url_create_product,
                                     List<NameValuePair> params) {
        // TODO Auto-generated method stub
        return null;
    }
}

Logcat錯誤

    06-11 15:18:32.448 17200-17200/com.example.android.andrtest1 E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null
06-11 15:18:32.451 17200-17200/com.example.android.andrtest1 E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 
06-11 15:18:32.456 17200-17200/com.example.android.andrtest1 D/AndroidRuntime: Shutting down VM
06-11 15:18:32.457 17200-17200/com.example.android.andrtest1 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.android.andrtest1, PID: 17200
    java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference
        at com.example.android.andrtest1.NameSearchDisplayActivity$GetProductDetails$1.run(NameSearchDisplayActivity.java:91)
        at android.os.Handler.handleCallback(Handler.java:815)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:194)
        at android.app.ActivityThread.main(ActivityThread.java:5651)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)

NameSearchDisplayActivity.class

    package com.example.android.andrtest1;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import junit.framework.Assert;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class NameSearchDisplayActivity extends Activity {
    TextView empnameview;
    TextView empcugview;
    TextView emprailphnview;
    TextView empdesigview;
    TextView empresipnview;
    String empname;
    ProgressDialog pDialog;
    JSONParser jsonParser=new JSONParser();

    private static final String url_product_details = "http://192.168.116.1/serdb1.0/get_employee_details.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCT = "product";
    //private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_CUG = "CUG";
    private static final String TAG_RAILWAY_PHN = "railway_phone";
    private static final String TAG_DESIGNATION = "designation";
    private static final String TAG_RESIDENCE_PN = "residence_pn";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.namesearch_display);

        // getting product details from intent
        Intent i = getIntent();

        // getting name from intent
        empname = i.getStringExtra(NameSearchDisplayActivity.TAG_NAME);

        // Getting complete product details in background thread
        new GetProductDetails().execute();
    }

    private class GetProductDetails extends AsyncTask<String, String, JSONObject> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(NameSearchDisplayActivity.this);
            pDialog.setMessage("Loading employee details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected JSONObject doInBackground(String... args) {
                    if(pDialog!=null)
                        pDialog.dismiss();

                    // Check for success tag
                    JSONObject product=null;
                    int success;
                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("name", empname));

                        // getting product details by making HTTP request
                        // Note that product details url will use GET request
                        JSONObject json;
                        json = jsonParser.makeHttpRequest(
                                url_product_details, "GET", params);


                        // check your log for json response

                            Log.d("Single Product Details", json.toString());

                        // json success tag

                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            // successfully received product details
                            JSONArray productObj = json
                                    .getJSONArray(TAG_PRODUCT); // JSON Array

                            // get first product object from JSON Array
                            product = productObj.getJSONObject(0);

                        }
                        else {

                        }// product with pid not found

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return product;

                }


        protected void onPostExecute(JSONObject product) {
            // Edit Text
            try{
            empnameview = (TextView) findViewById(R.id.namevalueview);
            empcugview = (TextView) findViewById(R.id.cugvalueview);
            emprailphnview = (TextView) findViewById(R.id.railphnvalueview);
            empdesigview = (TextView) findViewById(R.id.desigvalueview);
            empresipnview = (TextView) findViewById(R.id.resipnvalueview);

            // display product data in EditText

            empcugview.setText(product.getString(TAG_CUG));
            emprailphnview.setText(product.getString(TAG_RAILWAY_PHN));
            empdesigview.setText(product.getString(TAG_DESIGNATION));
            empresipnview.setText(product.getString(TAG_RESIDENCE_PN));}
            catch (JSONException e) {
                e.printStackTrace();
            }
            // dismiss the dialog once got all details
            if(pDialog != null)
                pDialog.dismiss();
        }


    }

}

使用Chrome中的Postman擴展程序檢查方法是POST還是GET。 並使用特定的方法獲取數據。

郵遞員擴展鏈接

暫無
暫無

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

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