如何在我们收到截击请求的响应之前冻结代码?

时间:2017-12-20 09:21:48

标签: java android

我试图从另一个类调用此方法;在检查服务器上的用户ID和密码后,它应该返回truefalse

即使登录过程成功,它总是返回false,因为它在我收到请求响应之前返回默认值false

在发布此问题之前我做了很多搜索,但没有明确的答案如何解决这个问题。

MyHelper myHelper = new MyHelper();
myHelper.setVolleyResponseListener(new MyHelper.OnVolleyResponse()
{
    @Override
    public void onResponse(JSONObject jsonObject)
    {
        // do watever you want here with response.
    }
});

if (myHelper.doBackgroundLogin(getApplicationContext())) {
    uploadImageToServer();
}else{
    finish();
    startActivity(new Intent(AccountProfileImageActivity.this, AccountLoginActivity.class));
}
package com.company.testApp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

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

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by Aly on 1/11/2017.
 */

public class MyHelper {

    private static AlertDialog.Builder builder;
    public static Context ctx;
    public static ValuesManager vm;

    public static boolean status = false;


    public static boolean doBackgroundLogin(final Context context) {
        vm = new ValuesManager( context, context.getString(R.string.saved_values_file_name) );
        String user_email = vm.retrieveSharedPreferences("user_email");
        String user_password = vm.retrieveSharedPreferences("user_password");

        Toast.makeText(context, user_email + " - " + user_password, Toast.LENGTH_SHORT).show();
        //------------------------------------------------------------------------------------------
//        final MyProgressDialog progressDialog;
//        progressDialog = MyProgressDialog.show(context, "title", "message");
//        //------------------------------------------------------------------------------------------
        String url =  context.getString(R.string.server_path);
        Log.d("URL : ", url);
        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("response : ", response); // log the error to trace it and print message to user
//                        progressDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray jsonArray = jsonObject.getJSONArray("server_response");
                            JSONObject JO = jsonArray.getJSONObject(0);
                            String code = JO.getString("code");
                            if( code.equals("login_true") ) {
                                status = true;
                                vm.saveSharedPreferences( "user_token", JO.getString("user_token") );
                                Log.d("trace","code = " + code);
                                Log.d("trace","statusUpdated = " + status);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("vERROR : ", error.toString()); // log the error to trace it and print message to user
//                        progressDialog.dismiss();
                    }
                }
        )
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("action","account_login");
                params.put("email_address",vm.retrieveSharedPreferences("user_email"));
                params.put("password",vm.retrieveSharedPreferences("user_password"));
                return params;
            }
        };

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                100000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        MySingleton.getInstance(context).addToRequestQueue(stringRequest);
        //------------------------------------------------------------------------------------------
        Log.d("trace","status = " + status);
        return status;
   } 

    public interface OnVolleyResponse
    {
        void onResponse(JSONObject jsonObject);
    }

    public void setVolleyResponseListener(OnVolleyResponse responseListener)
    {
        this.volleyResponse = volleyResponse;
    }

}

3 个答案:

答案 0 :(得分:3)

你必须使用接口回调。

<强>为什么吗

因为这是异步调用,并且在不同的线程上工作。所以你的主线程不会等待它的结果。

<强>解决方案

  1. MyHelper班级
  2. 中创建界面

    修改

        OnVolleyResponse  onVolleyResponse;
        public interface OnVolleyResponse
        {
            void onResponse(JSONObject jsonObject);
        }
    
    1. 创建回调的setter方法

      public void setVolleyResponseListener(OnVolleyResponse responseListener)
      {
          this.volleyResponse = volleyResponse;
      }
      
    2. 现在从Activity

      调用此方法
      MyHelper myHelper = new MyHelper();
      myHelper.setVolleyResponseListener(new OnVolleyResponse()
      {
          @Override
          public void onResponse(JSONObject jsonObject)
          {
             // do watever you want here with response. 
          }
      });
      if (myHelper.doBackgroundLogin(getApplicationContext())) {
                                  uploadImageToServer();
                              }else{
                                  finish();
                                  startActivity(new Intent(AccountProfileImageActivity.this, AccountLoginActivity.class));
                              }
      

      注意

      从doBackgroundLogin方法中删除static,并使用MyHelper的实例调用它。

答案 1 :(得分:1)

制作interface

public interface VolleyCallback{

public void onSuccess(boolean status);}

在此之后,当您收到回复时,您应该像这样更改doBackgroundLogin()方法。

 public static boolean doBackgroundLogin(final Context context,VolleyCallback callback) {
    vm = new ValuesManager( context, context.getString(R.string.saved_values_file_name) );
    String user_email = vm.retrieveSharedPreferences("user_email");
    String user_password = vm.retrieveSharedPreferences("user_password");

    Toast.makeText(context, user_email + " - " + user_password, Toast.LENGTH_SHORT).show();

    String url =  context.getString(R.string.server_path);
    Log.d("URL : ", url);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.i("response : ", response); // log the error to trace it and print message to user

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray jsonArray = jsonObject.getJSONArray("server_response");
                        JSONObject JO = jsonArray.getJSONObject(0);
                        String code = JO.getString("code");
                        if( code.equals("login_true") ) {
                            status = true;
                            vm.saveSharedPreferences( "user_token", JO.getString("user_token") );
                            Log.d("trace","code = " + code);
                            Log.d("trace","statusUpdated = " + status);

                            callback.onSuccess(status);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("vERROR : ", error.toString()); // log the error to trace it and print message to user

                }
            }
    )
    {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("action","account_login");
            params.put("email_address",vm.retrieveSharedPreferences("user_email"));
            params.put("password",vm.retrieveSharedPreferences("user_password"));
            return params;
        }
    };
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(
            100000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    MySingleton.getInstance(context).addToRequestQueue(stringRequest);

    Log.d("trace","status = " + status);
    return status; } 

只需看看callback.onSuccess(status);

即可

这将在登录成功后立即发送响应。

答案 2 :(得分:0)

onResponse方法是为你排队等待你并在从特定网址获取数据或响应后调用onResponse方法。

  final TextView mTextView = (TextView) findViewById(R.id.text);
    ...

    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);
    String url ="http://www.google.com";

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // Display the first 500 characters of the response string.
            mTextView.setText("Response is: "+ response.substring(0,500));
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mTextView.setText("That didn't work!");
        }
    });
    // Add the request to the RequestQueue.
    queue.add(stringRequest);