首先,我是android编程的新手。 我试图通过youtube观看视频,使用volley库将数据发送到PHP服务器。但每当我点击注册按钮时,都会收到错误" com.android.volley.timeouterror"。请帮我。 这是我的代码......
StringRequest stringRequest= new StringRequest(Request.Method.POST, ip, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
String code=jsonObject.getString("code");// used in php file
String message=jsonObject.getString("message");
builder.setTitle("Server Response");
builder.setMessage(message); //message from server
displayAlert(code);
} catch (JSONException e) {
e.printStackTrace();
}}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(first.this, "Call admin error in query"+error, Toast.LENGTH_SHORT).show();
}
})//passing data to string request getparams method
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params= new HashMap<>();
params.put("name",name);
params.put("email",email);
params.put("password",password);
return params;
}};
//string request to requestqueue
MySingleton.getInstance(first.this).addToRequestqueue(stringRequest);
} else {
builder.setTitle("Something went wrong!");
builder.setMessage("password doesn't match");
displayAlert("input_error");
}
}
}
});
}
public void displayAlert(final String code){
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (code.equals("input_error")){
jet3.setText("");
jet4.setText("");
}
else {
if(code.equals("Reg_Success")){
finish();
}
else if(code.equals("Process_Failed")){
jet1.setText("");
jet2.setText("");
jet3.setText("");
jet4.setText("");
}
}
}
});
AlertDialog alertDialog= builder.create();
alertDialog.show();
}
并提交mysingleton.java文件
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue requestQueue;
private static Context mCtx;
//create a constructor
private MySingleton(Context context){
mCtx=context; //initialize context
requestQueue=getRequestQueue(); //initialize request queue
}
public RequestQueue getRequestQueue(){
if(requestQueue==null){
requestQueue= Volley.newRequestQueue(mCtx.getApplicationContext());
}
return requestQueue;
}
//return instance of class
public static synchronized MySingleton getInstance(Context context){
//initialize mInstance if it is null
if (mInstance==null){
mInstance=new MySingleton(context);
}
return mInstance;
}
//adding request to requestqueue
public <T>void addToRequestqueue(Request<T> request){
requestQueue.add(request);
}
}
答案 0 :(得分:0)
使用以下代码 ` //你的超时时间延长了它
private static final int MY_SOCKET_TIMEOUT_MS = 10000;
MySingleton.getRequestQueue().setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));