在Android Studio中调用其他Java类中的实例和函数后,在主Java类中等待响应
由于api调用和响应延迟,数据无法及时获取,我正在使用延迟来获取响应。如果那里的响应延迟超过我的定时器限制,我会得到空错误。有没有更好的方法来实现这一点
这是我在UrlCalls中的代码。爪哇
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);
}
我在我的主线程中调用这个
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);
共 (0) 个答案