在Json对象上获取null对象引用错误

时间:2018-03-17 05:17:36

标签: java android mysql

Java文件:

我想通过Android应用程序更新MySQl数据库中的现有行。我得到空指针异常。下面是我的代码以及logcat。我试图解决它但没有成功。善意的帮助。使用HTML运行时,Web服务运行良好。但与android连接时无法正常工作。

 private ProgressDialog pDialog;

        JSONParser jsonParser = new JSONParser();
        int success=0;
        double pickup_lat, pickup_lng, drop_lat, drop_lng;
        // url to create new product
        private static String url_create_product = "http://192.168.10.6:8080/courier/add_location.php";

        // JSON Node names
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_USERNO = "user_no";
        private static final String TAG_PICKUP_LAT = "pickup_lat";
        private static final String TAG_PICKUP_LNG = "pickup_lng";
        private static final String TAG_DROP_LAT = "drop_lat";
        private static final String TAG_DROP_LNG = "drop_lng";

     class AddLocation extends AsyncTask<String, String, String> {

            /**
             * Before starting background thread Show Progress Dialog
             */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MapActivity.this);
                pDialog.setMessage("Adding Details..");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
            }

            /**
             * Creating product
             */
            protected String doInBackground(String... args) {

                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
               params.add(new BasicNameValuePair(TAG_USERNO, "120"));
                params.add(new BasicNameValuePair(TAG_PICKUP_LAT, "12"));
                params.add(new BasicNameValuePair(TAG_PICKUP_LNG,  "12"));
                params.add(new BasicNameValuePair(TAG_DROP_LAT,  "12"));
                params.add(new BasicNameValuePair(TAG_DROP_LNG, "12"));


                // getting JSON Object
                // Note that create product url accepts POST method
                JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                        "POST", params);

                // check for success tag
                try {
                    success = json.getInt(TAG_SUCCESS);

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

                }

                return null;
            }

            /**
             * After completing background task Dismiss the progress dialog
             **/
            protected void onPostExecute(String file_url) {
                //dismiss the dialog once done
                pDialog.dismiss();
                if (success == 1) {
                    // successfully created product
                    Intent i = getIntent();
                    // send result code 100 to notify about product update
                    setResult(100, i);
                    finish();
                    // closing this screen

                    finish();
                } else {

                    //failed to create product
                }
            }
        }
        @Override
        public void onDestroy(){
            super.onDestroy();

            pDialog.dismiss();
            pDialog.cancel();
        }
    }

网络服务代码:

<?php header('Access-Control-Allow-Origin: *'); ?>
<?php header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept'); ?>
<?php header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT'); ?>
<?php
// array for JSON response
$response = array();
if (isset($_POST['user_no']) && isset($_POST['pickup_lat']) && isset($_POST['pickup_lng']) && isset($_POST['drop_lat']) && isset($_POST['drop_lng'])) {
   $user_no = $_POST['user_no'];
    $pickup_lat = $_POST['pickup_lat'];
    $pickup_lng = $_POST['pickup_lng'];
    $drop_lat= $_POST['drop_lat'];
    $drop_lng = $_POST['drop_lng'];
     }

$db_host = "localhost"; 
// Place the username for the MySQL database here 
$db_username = "root"; 
// Place the password for the MySQL database here 
$db_pass = "";  
// Place the name for the MySQL database here 
$db_name = "smartcourier";

// Run the actual connection here  
$link=mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysqli_select_db($link,"$db_name") or die ("no database");

$sql = "UPDATE courier_detail SET pickup_lat='$pickup_lat' , pickup_lng='$pickup_lng',  drop_lat= '$drop_lat', drop_lng=$drop_lng WHERE user_no=$user_no";
$result =mysqli_query($link,$sql);

if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Location added successfully.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }

@mysql_close($link);

?>

log cat

1 个答案:

答案 0 :(得分:0)

这可能是因为 jsonParser.makeHttpRequest()方法返回null对象并将其分配给json对象。这就是为什么在尝试从json对象获取getInt()时会出现空指针异常的原因。请再次检查你的jsonParser.makeHttpRequest()或检查jsonParser.makeHttpRequest()是否返回null对象。

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

            // check if json is null or not
            Log.i("Json Check : ", json == null + "");

            // check for success tag
            try {
                success = json.getInt(TAG_SUCCESS);

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

            }