简体   繁体   English

从 volley onResponse 返回值

[英]Returning values from volley onResponse

I am trying to make a more object oriented program with Volley.我正在尝试使用 Volley 制作一个更加面向对象的程序。 Currently I have the problem of not being able to extract data from inside the onResponse method of volley.目前我遇到了无法从 volley 的 onResponse 方法中提取数据的问题。

 private void getMember(String memberid){
    Response.Listener<String> responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success"); //key["success"]
                String userid = jsonResponse.getString("userid");
                if(success){
                    byte[] decoded_img = Base64.decode(jsonResponse.getString("userpic"), Base64.DEFAULT);
                    Bitmap member_pic = BitmapFactory.decodeByteArray(decoded_img, 0, decoded_img.length);
                    FamMember member = new FamMember(jsonResponse.getString("username")); // creating new object

////// where I need to capture the image/ any data that I get in the Json response///
                    AlertDialog.Builder builder = new AlertDialog.Builder(LandingActivity.this);
                    builder.setMessage(member.username)
                            .setNegativeButton("Retry",null)
                            .create()
                            .show(); //properly displays newly created object 'username'
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(LandingActivity.this);
                    builder.setMessage("Unable to Login")
                            .setNegativeButton("Retry",null)
                            .create()
                            .show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    //HAPPENS AFTER RESPONSE HAS BEEN GIVEN FROM SERVER////////
    MemberRequest memberRequest = new MemberRequest(type,memberid,responseListener);
    RequestQueue queue  = Volley.newRequestQueue(LandingActivity.this);
    queue.add(memberRequest); //puts actual request into the queue for processing
}

I have to be able to get the response and use them as variables to pass into my activity.我必须能够获得响应并将它们用作变量以传递到我的活动中。 How do I go about doing this when I am given the error that I cannot have any returns on the methods above?当我收到上述方法无法获得任何回报的错误时,我该怎么做?

Create a new interface like this :像这样创建一个新界面:

  public interface VolleyCallback {
            void onSuccess(String result);
            void onError(String result);
        }

Where you use callback interfaces :在哪里使用回调接口:

 public void getString(final VolleyCallback callback) {
      StringRequest strReq = new StringRequest(Request.Method.GET, url,
           new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                    callback.onSuccess(response);
            }
           }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
               callback.onError(volleyError + "");
            }
        });
        Volley.newRequestQueue(MyApplication.getAppContext()).add(strReq);
      }

Use interface on your activity class like:在您的活动类上使用接口,例如:

 FunctionName(new VolleyCallback(){
         @Override
         public void onSuccess(String result){
             ... //do stuff here
         }
         @Override
         public void onError(String result) {
             ... //show error here         
         }
    });

Create Global variable outside of the Volley block在 Volley 块之外创建全局变量

    public String response_var="";

    public void getMember()
    {
    @Override
    public void onResponse(String response) {
    {
 response_var=response;
    }

    }

Volley and other asynchronous HTTP libraries are well asynchronous . Volley 和其他异步 HTTP 库都是异步的 Your activity cannot directly get hold of the http response.您的活动无法直接获取 http 响应。 You need to process the data with in the onResponse method and then communicate with the activity.您需要在onResponse方法中处理数据,然后与活动进行通信。 One way is to send a local broadcast.一种方法是发送本地广播。

You can create a method that takes the response (or part of the response you want) as argument.您可以创建一个将响应(或您想要的响应的一部分)作为参数的方法。 For example:例如:

private void processResponse(String encodedUserPic, String userName) {

    // Use the response as you need
    byte[] decodedImg = Base64.decode(encodedUserPic), Base64.DEFAULT);
    Bitmap memberPic = BitmapFactory.decodeByteArray(decodedImg, 0, decodedImg.length);
    FamMember member = new FamMember(userName); 
}

Then, you can pass the response to this method from inside the onResponse method:然后,您可以从 onResponse 方法内部将响应传递给此方法:

private void getMember(String memberid){
    Response.Listener<String> responseListener = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        try {
            JSONObject jsonResponse = new JSONObject(response);
            boolean success = jsonResponse.getBoolean("success"); //key["success"]
            String userid = jsonResponse.getString("userid");

            if(success){
                String encodedUserPic = jsonResponse.getString("userpic");
                String userName = jsonResponse.getString("username");
                // Callback:
                processResponse(encodedUserPic, userName);
                ...
            }
            ...

Margin note: in Java, lower camelcase notation is the convention, instead of underscored.边注:在 Java 中,小驼峰字母表示法是惯例,而不是下划线。

Hope you find this useful!希望你觉得这很有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM