缓冲区错误转换结果java.lang.NullPointerException时出错

时间:2013-12-03 06:49:41

标签: php android json

我正在尝试使用json解析器获取数据,但我收到缓冲区错误,解析  错误等。请帮助我,代码如下.......

log cat ....

12-03 11:47:20.175: E/Buffer Error(4082): Error converting result java.lang.NullPointerException
12-03 11:47:20.175: E/JSON Parser(4082): Error parsing data org.json.JSONException: End of input at character 0 of 
12-03 11:47:20.175: W/dalvikvm(4082): threadid=8: thread exiting with uncaught exception (group=0x2aacc7d0)
12-03 11:47:20.175: E/AndroidRuntime(4082): Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
12-03 11:47:20.185: I/global(4082): Default buffer size used in BufferedWriter constructor. It would be better to be explicit if an 8k-char buffer is required.
12-03 11:47:20.195: I/klogd(117): [ 9721.632072] Uncaught handler: thread AsyncTask #1 exiting due to uncaught exception
12-03 11:47:20.225: I/global(4082): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
12-03 11:47:20.275: W/System.err(4082): java.io.IOException: Permission denied
12-03 11:47:20.285: I/global(4082): Default buffer size used in BufferedWriter constructor. It would be better to be explicit if an 8k-char buffer is required.
12-03 11:47:20.285: E/AndroidRuntime(4082): FATAL EXCEPTION: AsyncTask #1
12-03 11:47:20.285: E/AndroidRuntime(4082): java.lang.RuntimeException: An error occured while executing doInBackground()
12-03 11:47:20.285: E/AndroidRuntime(4082):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
12-03 11:47:20.285: E/AndroidRuntime(4082):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-03 11:47:20.285: E/AndroidRuntime(4082):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-03 11:47:20.285: E/AndroidRuntime(4082):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-03 11:47:20.285: E/AndroidRuntime(4082):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-03 11:47:20.285: E/AndroidRuntime(4082):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
12-03 11:47:20.285: E/AndroidRuntime(4082):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
12-03 11:47:20.285: E/AndroidRuntime(4082):     at java.lang.Thread.run(Thread.java:1096)
12-03 11:47:20.285: E/AndroidRuntime(4082): Caused by: java.lang.NullPointerException
12-03 11:47:20.285: E/AndroidRuntime(4082):     at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:131)
12-03 11:47:20.285: E/AndroidRuntime(4082):     at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
12-03 11:47:20.285: E/AndroidRuntime(4082):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-03 11:47:20.285: E/AndroidRuntime(4082):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-03 11:47:20.285: E/AndroidRuntime(4082):     ... 4 

活动类 ..........

    package com.example.androidhive;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;

    import org.apache.http.NameValuePair;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.TextView;

    public class AllProductsActivity extends ListActivity {

        // Progress Dialog
        private ProgressDialog pDialog;

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

        ArrayList<HashMap<String, String>> productsList;

        // url to get all products list
        private static String url_all_products =//"http://api.androidhive.info/android_connect/get_all_products.php"; 
          "http://10.0.2.2:80/android_connect/get_all_products.php";

        // JSON Node names
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_PRODUCTS = "products";
        private static final String TAG_PID = "pid";
        private static final String TAG_NAME = "name";

        // products JSONArray
        JSONArray products = null;

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

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

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

            // Get listview
            ListView lv = getListView();

            // on seleting single product
            // launching Edit Product Screen
            lv.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // getting values from selected ListItem
                    String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                            .toString();

                    // Starting new intent
                    Intent in = new Intent(getApplicationContext(),
                            EditProductActivity.class);
                    // sending pid to next activity
                    in.putExtra(TAG_PID, pid);

                    // starting new activity and expecting some response back
                    startActivityForResult(in, 100);
                }
            });

        }

        // Response from Edit Product Activity
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            // if result code 100
            if (resultCode == 100) {
                // if result code 100 is received 
                // means user edited/deleted product
                // reload this screen again
                Intent intent = getIntent();
                finish();
                startActivity(intent);
            }

        }

        /**
         * Background Async Task to Load all product by making HTTP Request
         * */
        class LoadAllProducts extends AsyncTask<String, String, String> {
            int success;
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            /*  pDialog = new ProgressDialog(AllProductsActivity.this);
                pDialog.setMessage("Loading products. 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_products, "GET", params);

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

                try {
                    // Checking for SUCCESS TAG

                    success = json.getInt(TAG_SUCCESS);

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

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

                            // Storing each json item in variable
                            String id = c.getString(TAG_PID);
                            String name = 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_PID, id);
                            map.put(TAG_NAME, name);

                            // adding HashList to ArrayList
                            productsList.add(map);
                        }
                    } else {
                        // no products found
                        // Launch Add New product Activity
                        Intent i = new Intent(getApplicationContext(),
                                NewProductActivity.class);
                        // Closing all previous activities
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);
                    }
                } 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(
                                AllProductsActivity.this, productsList,
                                R.layout.list_item, new String[] { TAG_PID,
                                        TAG_NAME},
                                new int[] { R.id.pid, R.id.name });
                        // updating listview
                        setListAdapter(adapter);
                    }
                });

            }

        }

    }

Php file.......  

 <?php
    //header('content-type: application/json; charset=utf-8');
    /*
     * Following code will list all the products
     */

    // array for JSON response
    $response = array();


    // include db connect class
    require_once('db_connect.php');

    // connecting to db
    $db = new DB_CONNECT();

    // get all products from products table
    $result = mysql_query("SELECT * FROM products") or die(mysql_error());

    // check for empty result
    if (mysql_num_rows($result) > 0) {
        // looping through all results
        // products node
        $response["products"] = array();

        while ($row = mysql_fetch_array($result)) {
            // temp user array
            $product = array();
            $product["pid"] = $row["pid"];
            $product["name"] = $row["name"];
            $product["price"] = $row["price"];
            $product["description"] = $row["description"];
            $product["created_at"] = $row["created_at"];
            $product["updated_at"] = $row["updated_at"];



            // push single product into final response array
            array_push($response["products"], $product);
        }
        // success
        $response["success"] = 1;

        // echoing JSON response
        print json_encode($response);
    } else {
        // no products found
        $response["success"] = 0;
        $response["message"] = "No products found";

        // echo no users JSON
        echo json_encode($response);
    }
    ?>






Php file.......  

 <?php
    //header('content-type: application/json; charset=utf-8');
    /*
     * Following code will list all the products
     */

    // array for JSON response
    $response = array();


    // include db connect class
    require_once('db_connect.php');

    // connecting to db
    $db = new DB_CONNECT();

    // get all products from products table
    $result = mysql_query("SELECT * FROM products") or die(mysql_error());

    // check for empty result
    if (mysql_num_rows($result) > 0) {
        // looping through all results
        // products node
        $response["products"] = array();

        while ($row = mysql_fetch_array($result)) {
            // temp user array
            $product = array();
            $product["pid"] = $row["pid"];
            $product["name"] = $row["name"];
            $product["price"] = $row["price"];
            $product["description"] = $row["description"];
            $product["created_at"] = $row["created_at"];
            $product["updated_at"] = $row["updated_at"];



            // push single product into final response array
            array_push($response["products"], $product);
        }
        // success
        $response["success"] = 1;

        // echoing JSON response
        print json_encode($response);
    } else {
        // no products found
        $response["success"] = 0;
        $response["message"] = "No products found";

        // echo no users JSON
        echo json_encode($response);
    }
    ?>

2 个答案:

答案 0 :(得分:1)

试试这个..你无法通过 doInBackground

中的intent
class LoadAllProducts extends AsyncTask<String, String, int> {
            int success;
            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            /*  pDialog = new ProgressDialog(AllProductsActivity.this);
                pDialog.setMessage("Loading products. 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_products, "GET", params);

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

                try {
                    // Checking for SUCCESS TAG

                    success = json.getInt(TAG_SUCCESS);

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

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

                            // Storing each json item in variable
                            String id = c.getString(TAG_PID);
                            String name = 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_PID, id);
                            map.put(TAG_NAME, name);

                            // adding HashList to ArrayList
                            productsList.add(map);
                        }
                    } else {
                        success = 0;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return success;
            }

            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(int success) {

                if (success == 1) {
                        ListAdapter adapter = new SimpleAdapter(
                                AllProductsActivity.this, productsList,
                                R.layout.list_item, new String[] { TAG_PID,
                                        TAG_NAME},
                                new int[] { R.id.pid, R.id.name });
                        // updating listview
                        setListAdapter(adapter);
                  }else {
                        Intent i = new Intent(AllProductsActivity.this,
                            NewProductActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                    }

            }

        }

答案 1 :(得分:0)

1)找到IP地址: 在命令提示符下键入ipconfig:

Find IP Address

2)通过在浏览器中输入您的IP地址/ android_connect / get_all_products.php确保其有效。例如,对我而言,它是“http://192.168.1.79/android_connect/get_all_products.php” 如果它有效,你应该看到:

PHP Right Message

如果你像我一样,你会看到: PHP Error Message

因此,错误消息将与JSON文件一起发回,并在Android代码中导致NullPointerException。

3)如果您收到PHP错误消息,请关闭错误消息报告。

要更改PHP设置以使错误消息无法返回,请转到此处。来自任务栏 - &gt;右键单击WAMP-&gt; PHP的&GT;的php.ini

Php.ini

将文本“display_errors = On”更改为“display_errors = Off”

PHP Settings