在Android Studio中调用其他Java类中的实例和函数后,在主Java类中等待响应
由于api调用和响应的延迟,数据没有及时获取,我使用延迟来获取响应。如果响应延迟超过我的计时器限制,我会得到null错误。有没有更好的方法来实现这一点 这是我在UrlCalls.java中的代码在Android Studio中调用其他Java类中的实例和函数后,在主Java类中等待响应,java,android,multithreading,callback,Java,Android,Multithreading,Callback,由于api调用和响应的延迟,数据没有及时获取,我使用延迟来获取响应。如果响应延迟超过我的计时器限制,我会得到null错误。有没有更好的方法来实现这一点 这是我在UrlCalls.java中的代码 public void getProfile() { progressDialog=new ProgressDialog(con); progressDialog.setMessage("Please wait..."); progressDialog.show(); A
public void getProfile()
{
progressDialog=new ProgressDialog(con);
progressDialog.setMessage("Please wait...");
progressDialog.show();
AuthTokenGenerator authtoken = new AuthTokenGenerator(con);
Authenticator profilerequest = new Authenticator(Request.Method.POST, UrlBag.PROFILE, authtoken.getToken(data),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject profileresponse) {
response = String.valueOf(profileresponse);
progressDialog.dismiss();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error)
{
progressDialog.dismiss();
Toast.makeText(con,"Couldn't connect to server right now.",Toast.LENGTH_SHORT).show();
}
})
{
@Override
public Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("customer_id", data.GetData(SharedDataHandler.CUSTOMER_ID));
return params;
}
};
int socketTimeout = 1000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
profilerequest.setRetryPolicy(policy);
RequestQueue requestQueue = Volley.newRequestQueue(con);
requestQueue.add(profilerequest);
}
类似的问题也被问到了。。。请学习如何使用异步方法。显然,您应该再次将代码移到回调(onResponse)中,并在onResponse方法中更新您的UI
final UrlCalls callProfile=new UrlCalls(this,data);
callProfile.getProfile();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run()
{
try
{
jObject = new JSONObject(String.valueOf(callProfile.getResponse()));
if (!jObject.equals(""))
{
JSONObject customer = jObject.getJSONObject("customer");
customername.setText(customer.getString("customer_name"));
data.SaveData(SharedDataHandler.FULL_NAME, customer.getString("customer_name"));
customeremail.setText(customer.getString("email"));
data.SaveData(SharedDataHandler.EMAIL, customer.getString("email"));
customerphone.setText(customer.getString("mobile"));
data.SaveData(SharedDataHandler.MOBILE, customer.getString("mobile"));
}
else
{
Toast.makeText(getApplicationContext(),"Server Request time out.",Toast.LENGTH_SHORT).show();
}
}
catch(JSONException e)
{
Toast.makeText(getApplicationContext(),"Error occurred while processing the data.",Toast.LENGTH_SHORT).show();
}
catch (NullPointerException e)
{
Toast.makeText(getApplicationContext(),"Couldn't connect to server right now.",Toast.LENGTH_SHORT).show();
}
}
}, 1000);