没有为JsonObjectRequest调用Android Volley getParams()方法 [英] Android Volley getParams() method not getting called for JsonObjectRequest

查看:81
本文介绍了没有为JsonObjectRequest调用Android Volley getParams()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已覆盖getParams(),并且全局声明了mEmailmUsername等.

I have overrided getParams(), and mEmail, mUsername etc. are globally declared.

@Override
public Map<String, String> getParams() throws AuthFailureError {
    Map<String,String> params = new Hashtable<String, String>();

    params.put("Email", mEmail.getText().toString().trim());
    params.put("Username",mUsername.getText().toString().trim());
    params.put("Password",mPassword.getText().toString().trim());
    params.put("BirthDay",mBirthday.getText().toString().replaceAll("\\s","-"));
    params.put("Sex",SelectedRadio());
    params.put("Bitmap",getEncodedBitmap());

    return params;
}

这是我的服务器端代码:

This is my server side code:

<?php
require "init1.php";

$email = $_POST["Email"];
$password = $_POST["Password"];
$Username  = $_POST["Username"];
$Sex = $_POST["Sex"];
$ProfilePicture = $_POST["Bitmap"];

$timestamp = strtotime($_POST["BirthDay"]);
$BirthDay = date('Y-m-d',$timestamp);

$sql = "select * from Registered_Users where Username='$Username'";
$sqle = "select * from Registered_Users where Email='$email'";
try{
    $result1 = mysqli_query($con, $sqle) or die(mysqli_error($con));;
    $result = mysqli_query($con, $sql) or die(mysqli_error($con));;
} catch(Exception $e) {
    echo $e->getMessage();
}

if (mysqli_num_rows($result) > 0){
    $myclass = new stdClass();
    $myclass->status="Not Ok";

    echo json_encode($myclass);
} else if(mysqli_num_rows($result1) > 0) {
    $myclass = new stdClass();
    $myclass->status="Not Ok";

    echo json_encode($myclass);
} else{
    try{
        $sql_query = "insert into Registered_Users (Email, Password, BirthDay, Sex, Username, ProfilePicture) values('$email', '$password', '$BirthDay', '$Sex', '$Username', '$ProfilePicture')";

        if(mysqli_query($con,$sql_query)){
            $obj1 = new stdClass();
            $obj1->status="Ok";

            echo json_encode($obj1);
        } else {
            $obj1 = new stdClass();
            $obj1->status="Not Ok ";
        }
    } catch(Exception $e) {
        echo $e->getMessage();
    }
}
?>

我得到的响应始终是not ok,因为我的数据库中已经有一个空行,并且我尝试再次上传一个空行.有人可以告诉我为什么我无法获取数据吗?为什么我会得到空数据?

The response I am getting is always not ok, becasuse I already have an empty row in my database, and I am trying upload an empty row again. Can someone tell why I am not able to get the data? Why am I getting empty data?

推荐答案

使用此自定义齐射请求类

use this Custom volley request class

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Map;

public class CustomJsonRequest extends Request<JSONObject> {

    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomJsonRequest(String url, Map<String, String> params,
                             Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomJsonRequest(int method, String url, Map<String, String> params,
                             Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    @Override
    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        return params;
    }

    ;

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

您可以将它与

Map<String,String> params = new Hashtable<String, String>();

params.put("Email", mEmail.getText().toString().trim());
params.put("Username",mUsername.getText().toString().trim());
params.put("Password",mPassword.getText().toString().trim());
params.put("BirthDay",mBirthday.getText().toString().replaceAll("\\s","-"));
params.put("Sex",SelectedRadio());
params.put("Bitmap",getEncodedBitmap());



CustomJsonRequest request = new CustomJsonRequest(Request.Method.POST, url, params,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {

    }
});

request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().getRequestQueue().add(request);

实际上这是与凌空发送参数有关的问题.检查这个答案 https://stackoverflow.com/a/27091088/1320616

Actually this a issue with sending parameters with volley. Check this answer https://stackoverflow.com/a/27091088/1320616

编辑:此行为的说明

您的JsonObjectRequest类是JsonRequest的扩展,而JsonRequest是Request的扩展.

your JsonObjectRequest class extends from JsonRequest which extends from Request.

在您的Request类中有一个方法

inside your Request class there is a method

/**
     * Returns the raw POST or PUT body to be sent.
     *
     * <p>By default, the body consists of the request parameters in
     * application/x-www-form-urlencoded format. When overriding this method, consider overriding
     * {@link #getBodyContentType()} as well to match the new body format.
     *
     * @throws AuthFailureError in the event of auth failure
     */
    public byte[] getBody() throws AuthFailureError {
        Map<String, String> params = getParams();
        if (params != null && params.size() > 0) {
            return encodeParameters(params, getParamsEncoding());
        }
        return null;
    }

请注意,此方法正在调用getParams()方法.与拨打电话时要覆盖的方法相同.

notice that this method is calling getParams() method. It is the same method that you are overriding while making the call.

但是,如果您查看JsonRequest类内部,则有一个方法

But if you look inside JsonRequest class, there is a method

@Override
    public byte[] getBody() {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                    mRequestBody, PROTOCOL_CHARSET);
            return null;
        }
    }

这意味着Request的getBody()已被JsonRequest类的getBody()覆盖,这意味着您的getParams()将永远不会被调用.因此,您需要一个自定义类,该类直接扩展Request类,并且不覆盖Request类的getBody()方法.

it means the getBody() of Request has been overridden by getBody() of JsonRequest class which means your getParams() will never get called. So you need a custom class which directly extends Request class and doesn't override the getBody() method of Request class.

这篇关于没有为JsonObjectRequest调用Android Volley getParams()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆