【问题标题】:Android volley library, method return null objectAndroid volley 库,方法返回空对象
【发布时间】:2015-11-26 17:39:27
【问题描述】:

我想向我的服务器传递一个 id,它让我查询并向我发送一些信息,但看起来服务器没有捕获我发送的值。 这是我的代码:

private void makeJsonObjectRequest() {



    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            Config.url_info, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d("INFO RESPONSE: ", response.toString());

            try {
                int success = response.getInt(TAG_SUCCESS);
                if(success == 1) {
                    // successfully received details
                    JSONArray infoObj = response.getJSONArray(TAG_INFO); // JSON Array

                    // get first course object from JSON Array
                    info = infoObj.getJSONObject(0);
                    showResult();

                }
            }catch (JSONException e){
                e.printStackTrace();
                Toast.makeText(getApplicationContext(),"Error: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
            }


        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("VOLLEY ERROR: ", "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_SHORT).show();


        }
    }){
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String,String> params = new HashMap<>();
        //Adding parameters to request
        params.put("id", id);
        //returning parameter
        return params;
    }
};

    // Adding request to request queue
    //AppController.getInstance().addToRequestQueue(jsonObjReq);
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonObjReq);
}

错误在变量信息中,错误日志说是空值。 “java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.String org.json.JSONObject.getString(java.lang.String)'”

这是我的php代码:

<?php

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

// include db connect class
require_once __DIR__ . '/db_connect.php';
//include query class
require_once __DIR__ . '/query.php';

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

// check for post data

if (isset($_GET["id"])) {
    $id = $_GET['id'];

    // get a product from products table
    $result = $db ->sth -> query("SELECT * FROM info WHERE id = $id");

    if (!empty($result)) {
      // check for empty result
      if (mysqli_num_rows($result) > 0) {

        $result = mysqli_fetch_array($result);
        $dett = array();
        $dett["where"] = $result["where"];
        $dett["when"] = $result["when"];
        $dett["cost"] = $result["cost"];
        $dett["link"] = $result["link"];

        // success
        $response["success"] = 1;

        // user node
        $response["info"] = array();

        array_push($response["info"], $dett);

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

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // no product found
    $response["success"] = 0;
    $response["message"] = "No course found";

    // echo no users JSON
    echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

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

感谢阅读。

编辑。我尝试更改我的 php 文件,如果我使用特定数字设置变量 $id 它可以工作,所以问题可能出在 $_get for php 中(但我不认为因为以前我使用的是旧库并且它有效),我尝试在 map 方法中插入一条 toast 消息,但没有显示出来。 屏幕保持白色,成功值为0

【问题讨论】:

    标签: php android database database-connection android-volley


    【解决方案1】:

    试着做这样的代码..

    public void sendContactMessage(final String sfullname, final String semail, final String smessage){
        class DownloadJSONsendContactMessage extends AsyncTask<String, Void, String> {
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                mProgressDialog = ProgressDialog.show(getActivity(), null, null, true, false);
                mProgressDialog.setContentView(R.layout.progressdialog);
            }
    
            @Override
            protected String doInBackground(String... params) {
                ArrayList<NameValuePair> dataToSend = new ArrayList<>();
                dataToSend.add(new BasicNameValuePair("fullname", sfullname));
                dataToSend.add(new BasicNameValuePair("email", semail));
                dataToSend.add(new BasicNameValuePair("message", smessage));
    
                HttpParams httpRequestParams = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
                HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
    
                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost(SERVER_ADDRESS + "sendcontactmessage.php");
    
                // Depends on your web service
                //httppost.setHeader("Content-type", "application/json");
    
                InputStream inputStream = null;
                String sendcontactresult = null;
                try {
                    httppost.setEntity(new UrlEncodedFormEntity(dataToSend));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
    
                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();
    
                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    sendcontactresult = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return sendcontactresult;
            }
    
            @Override
            protected void onPostExecute(String sendcontactresult){
                // Close the progressdialog
                mProgressDialog.dismiss();
                sendcontactsuccessful();
            }
        }
        DownloadJSONsendContactMessage g = new DownloadJSONsendContactMessage();
        g.execute();
    }
    

    【讨论】:

    • 我试过但它不起作用,我改变了 showResult() 方法的位置,不是它没有崩溃而是成功 il 0,php 没有达到我传递的 id getParam() 方法。
    • 我在 $varibale1 的 php 文件顶部添加了您的代码,我添加了“1”,在变量 2 中添加了“success”,输出是这样的:{“response”:[{“success ":"1","message":"success"}]}{"0":{"success":"1","message":"success"},"success":0,"message":"缺少必填字段"}
    • 这个$response0 = array(); $response0["success"] = 0; $response0["message"] = "No course found"; $response1["sm"] = array(); array_push$response1["sm"], $response); echo json_encode($response1);怎么样
    • 输出应该是这样的: {"success":1,"info":[{"where":"gym","when":" November", "cost":"" , "链接":"http:\/\/www.hi.it"}]}
    • 对不起我错了..我没有阅读所有内容..请参阅编辑我在将值传递给 php 时使用的示例代码..
    猜你喜欢
    • 2020-02-20
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    相关资源
    最近更新 更多