我试图从另一个类调用此方法;在检查服务器上的用户ID和密码后,它应该返回true
或false
。
即使登录过程成功,它总是返回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;
}
}
答案 0 :(得分:3)
你必须使用接口回调。
<强>为什么吗
因为这是异步调用,并且在不同的线程上工作。所以你的主线程不会等待它的结果。
<强>解决方案强>
MyHelper
班级修改强>
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方法中删除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);