0

我的应用似乎没有正确地从 PHP 网络服务中提取 JSON 数据。

访问 web 服务的函数以从数据库中获取所有数据记录会正确生成 JSON,但我的应用程序无法获取该数据并且似乎以NullPointerException.

LogCat 向我发出这个问题:

更新:

注意到在以下错误之前发生的黄色错误:

W/System.err(835): org.apache.http.conn.HttpHostConnectException: 连接到 http:// localhost 被拒绝

如果我无法连接到本地主机上的 Web 服务,那么我不会将 JSON 传送到我的应用程序。但是为什么它会拒绝连接到本地主机呢?

W/System.err(1159):在 com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:113) W/System.err(1159):在 com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground( MainActivity.java:1) E/AndroidRuntime(1159):在 com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:116) E/AndroidRuntime(1159):在 com.example.myfirstapp.MainActivity$LoadAllCars。 doInBackground(MainActivity.java:1) E/WindowManager(1159): 在 com.example.myfirstapp.MainActivity$LoadAllCars.onPreExecute(MainActivity.java:103)

第 113 行: JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params); 第 116 行: Log.d("All Cars: ", json.toString());

主要活动

package com.example.myfirstproject;

//imports

public class MainActivity extends ListActivity implements OnItemClickListener {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> carsList;

    // url to get all products list
    private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_CARS = "cars";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray cars = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Hashmap for ListView
        carsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllcars().execute();

        // Get listview
        ListView lv = getListView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllcars extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading cars. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All cars: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    cars = json.getJSONArray(TAG_CARS);

                    // looping through All Products
                    for (int i = 0; i < cars.length(); i++) {
                        JSONObject c = cars.getJSONObject(i);

                        // Storing each json item in variable
                        String title = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        carsList.add(map);
                    }
                } else {
                    // no products found
                    pDialog = new ProgressDialog(MainActivity.this);
                    pDialog.setMessage("No cars found");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(false);
                    pDialog.show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            MainActivity.this, carsList,
                            android.R.id.list, new String[] {TAG_NAME},
                            new int[] { R.id.title });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }
    }
}

编辑

JSON解析器:

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

    }
}
4

3 回答 3

1

好吧,如果你在这一行得到一个空指针异常

JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);

那么其中 1 个或多个东西必须为空。jParser 被实例化,url 字符串也是,参数是一个列表,但是列表中没有任何内容。查看 jParser 内部,看看该参数列表发生了什么。你需要它们吗?它需要它们吗?

编辑

因此,jParser 正在将您的列表(为空)转换为带有字符串生成器的字符串。这是返回一个空的刺痛。

所以当它发送到你的服务器时你的 url 看起来像这样

http://localhost/webservice/get_all_cars.php?

所以正常的网址,但上面有一个问号。那是对的吗?

从您的 httpresponse 记录状态码和状态原因是有意义的,这样您就可以看到服务器正在响应什么,您会这样做......

Log.d("Class Name", "Status code: " + httpResponse.getStatusLine().getStatusCode() + " Status Phrase: " + httpResponse.getStatusLine().getReasonPhrase());

编辑

url 设置为“localhost”,所以我认为它是在设备内部而不是在您的服务器上查找。改为输入服务器的ip

于 2012-11-03T01:12:59.993 回答
1

我认为你的问题可能是你从来没有把任何东西放进去params。它只是一个空的List

于 2012-11-03T02:24:45.817 回答
0

问题在这里:

private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";

无法使用localhost,因为模拟手机本身是localhost/127.0.0.1

您需要更改localhost10.0.2.2

private static String url_all_cars = "http://10.0.2.2/webservice/get_all_cars.php";

于 2012-11-03T18:22:14.523 回答