gpt4 book ai didi

java - 如何卡住代码直到收到 volley 请求的响应?

转载 作者:行者123 更新时间:2023-12-01 17:53:00 26 4
gpt4 key购买 nike

我正在尝试从另一个类调用此方法;在服务器上检查用户 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;
}

}

最佳答案

您必须为此使用接口(interface)回调。

为什么?

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

解决方案

  1. MyHelper 类中创建接口(interface)

编辑

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

    public void setVolleyResponseListener(OnVolleyResponse responseListener)
    {
    this.volleyResponse = volleyResponse;
    }
  • 现在从您的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 方法中删除静态,并使用 MyHelper 实例调用它。

    关于java - 如何卡住代码直到收到 volley 请求的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47902554/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com