Getting com.android.volly.ServerError - android

I built an android app which i build signup form. i am using volly for network call but com.android.volly.ServerError comes. i dont understand where i make mistake.
below is my code
try {
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean status = jsonObject.getBoolean("success");
if (status) {
Constants.user = new User(jsonObject.getString("id"), jsonObject.getString("name"), jsonObject.getString("name"), jsonObject.getString("image"), jsonObject.getString("image"), "", jsonObject.getString("gender"), jsonObject.getString("dob"), 0, 0, jsonObject.getString("sb_live_id"), jsonObject.getString("is_host"), jsonObject.getString("country"), "1", jsonObject.getString("firebase_id"), "", jsonObject.getString("level"), jsonObject.getString("bio"), false, "1");
startActivity(new Intent(UserInfoActivity.this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
}
progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error != null)
Log.e("error", error.getLocalizedMessage() + "");
progressDialog.dismiss();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("name", txtfullname.getText().toString());
MyData.put("number", phoneNumber);
MyData.put("image", imgpath);
MyData.put("password", password);
MyData.put("city", etCity.getText().toString());
MyData.put("country", etCountry.getText().toString());
MyData.put("dob", txtage.getText().toString());
MyData.put("bio", txtbio.getText().toString());
MyData.put("gender", gendr);
MyData.put("firebase_password", password);
MyData.put("firebase_id", uid);
MyData.put("email", email);
return MyData;
}
};
MyStringRequest.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MyRequestQueue.add(MyStringRequest);
} catch (Exception e) {
e.printStackTrace();
}

Related

How Can I use Post Method in Volley?

I want to know how can I POST Request Object in volley
class Request {
int restId;
List<Item> items;
}
class Item{
int itemId;
int count;
}
OnCreate():
RequestQueue requestQueue = Volley.newRequestQueue(this);
Example Post Method:
StringRequest postRequest = new StringRequest(Request.Method.POST, url1,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
System.out.println("response: " + response);
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
System.out.println("success: " + success);
// success-e gore usere info gosterilir
if (success.equals("true"))
{
Toast.makeText(SignUpActivity.this, R.string.register_success, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignUpActivity.this, SignInActivity.class);
startActivity(intent);
}
else
{
String errorMessage = jsonObject.getString("message");
Toast.makeText(SignUpActivity.this, R.string.register_failed, Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(SignUpActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
)
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("name", nameText);
params.put("login", userNameText);
params.put("email", emailText);
params.put("password", passwordText);
if (!dateText.equals(""))
params.put("birthday", dateText);
return params;
}
};
requestQueue.add(postRequest);

sending jsonobject to server

i am trying to send the Jsonobject request to the server and i am getting a reply of volley timeouterror
I read something on volley RetryPolicy, that i should increase the time limit of my request and till getting the same error. please guys help to look through my code, and assist me with the right request.
Thanks in advance
private void getpay() {
prgDialog.show();
final String amount = Fund_amount;
final String number = Card.getText().toString().trim();
final String year = Year.getText().toString().trim();
final String month = Month.getText().toString().trim();
final String cvv = CVV.getText().toString().trim();
final String pin = Pin.getText().toString().trim();
aaaaaa
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.POST, "https://api.myflex.ng/wallet/fund",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
prgDialog.cancel();
String data = response.getString("status");
JSONObject obj = response.getJSONObject("data");
JSONObject transfer = obj.getJSONObject("transfer");
Payment_massage = transfer.getString("flutterChargeResponseMessage");
Payment_ref = transfer.getString("flutterChargeReference");
if (data.equalsIgnoreCase("error")) {
prgDialog.cancel();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
builder.setTitle("myFlex");
builder.setMessage("Connection Error. Please check Your Network Connection");
builder.setCancelable(false);
builder.setPositiveButton("OK", null);
builder.show();
} else {
prgDialog.cancel();
FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.replace(R.id.change_transfer, new card_token());
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);
trans.commit();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.toString(),Toast.LENGTH_LONG).show();
prgDialog.cancel();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
builder.setTitle("myFlex");
builder.setCancelable(false);
builder.setMessage("Connection Error. Please check Your Internet Connection ");
builder.setPositiveButton("OK", null);
builder.show();
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", User_Token);
headers.put("Content-Type", "application/json");
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("amount", amount);
jsonObject.put("card", come());
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("Volley", "Error" + String.valueOf(jsonObject));
return jsonObject.toString().getBytes();
}
private JSONObject come() throws JSONException {
JSONObject params = new JSONObject();
try {
params.put("number", number);
params.put("expiry_month", month);
params.put("expiry_year", year);
params.put("cvv", cvv);
params.put("pin", pin);
Log.i("Volley", "Error" + String.valueOf(params));
} catch (JSONException e) {
Log.e("Volley", "Error" + params);
}
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
obreq.setRetryPolicy(new DefaultRetryPolicy(100 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(obreq);
}
Try to configure retry policy. Give a large timeout and try
String tag_json_obj = "json_obj_req";
obreq.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.addToRequestQueue(obreq, tag_json_obj);
You can try
add volley library to build.gradle
compile 'com.mcxiaoke.volley:library:1.0.19'
You can call like bellow using volley
private void doLoginAction() {
String url_login = "http://10.0.2.2/test_sstem/public/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("ParentNode");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String key1 = jo.getString("key1");
String key2 = jo.getString("key2");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
if (error instanceof TimeoutError ) {
//Time out error
}else if(error instanceof NoConnectionError){
//net work error
} else if (error instanceof AuthFailureError) {
//error
} else if (error instanceof ServerError) {
//Erroor
} else if (error instanceof NetworkError) {
//Error
} else if (error instanceof ParseError) {
//Error
}else{
//Error
}
//End
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("uname", "era#gmail.com");
params.put("pass", "123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Timeout in Volley is represented in milliseconds. Default time out is 25000 milliseconds or 25 seconds.
int timeOut = 120; // 2 min
int timeOutInMillis = timeOut * 1000;
obreq .setRetryPolicy(new DefaultRetryPolicy(timeOutInMillis,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(obreq);
For more details:Transmitting Network Data Using Volley

Error in Android Volley Syntax

sign_in_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
request=new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),
"SUCCESS"+jsonObject.getString("success"),
Toast.LENGTH_SHORT).show();
startActivity(new
Intent(getApplicationContext(),Welcome.class));
}else {
Toast.makeText(getApplicationContext(),
"Error"+jsonObject.getString("Error"),
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
, new Response.ErrorListener() {
public void onErrorResponse(VolleyError Object error)
{
}
}
})
{
#Override
protected Map<String,String> getParams() throws AuthFailureError
{
HashMap<String,String> hashMap=new HashMap<String, String>();
hashMap.put("email",email.getText().toString());
hashMap.put("password",password.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
});
} }
There is an error in the following part:
stating misplaced token ','
new Response.ErrorListener()
{
public void onErrorResponse(VolleyError Object error)
}
sign_in_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
request=new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),
"SUCCESS"+jsonObject.getString("success"),
Toast.LENGTH_SHORT).show();
startActivity(new
Intent(getApplicationContext(),Welcome.class));
}else {
Toast.makeText(getApplicationContext(),
"Error"+jsonObject.getString("Error"),
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
, new Response.ErrorListener() {
public void onErrorResponse(VolleyError Object error)
{
}
}
})
{
#Override
protected Map<String,String> getParams() throws AuthFailureError
{
HashMap<String,String> hashMap=new HashMap<String, String>();
hashMap.put("email",email.getText().toString());
hashMap.put("password",password.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
});
You've misplaced brackets everywhere. Try the below code,
request = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.names().get(0).equals("success")) {
Toast.makeText(getApplicationContext(),
"SUCCESS" + jsonObject.getString("success"),
Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Welcome.class));
} else {
Toast.makeText(getApplicationContext(),
"Error" + jsonObject.getString("Error"),
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("email", email.getText().toString());
hashMap.put("password", password.getText().toString());
return hashMap;
}
};
requestQueue.add(request);

Integrating youtube like button in android app

I want to integrate youtube like button in my android app. By refering through this tutorial Videos: rate
I found this api link https://www.googleapis.com/youtube/v3/videos/rate can be used to do that. Can anybody tell me how can I pass a particular video Id along with this api link
Used this code for like youtube Videos....
//getPostLikeBtn (Create this Method.)
private void getPostLikeBtn(final String rating) {
String tag_json_obj = "recipeLike";
final SpotsDialog spotsDialog = new SpotsDialog(context);
spotsDialog.show();
spotsDialog.setMessage("Loading...");
StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST,
"https://www.googleapis.com/youtube/v3/videos/rate",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
spotsDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
spotsDialog.dismiss();
try {
if (error.networkResponse.data != null) {
try {
String body = new String(error.networkResponse.data, "UTF-8");
Log.e("errorLike", body);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
spotsDialog.dismiss();
Toast.makeText(context, getResources().getString(R.string.try_again), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(context, getResources().getString(R.string.try_again), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
// hide the progress dialog
}
}) {
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
int mStatusCode = response.statusCode;
Log.e("mStatusCode", "" + mStatusCode);
if (mStatusCode == 204) {
Toast.makeText(context, "Successfully updated", Toast.LENGTH_SHORT).show();
getLikeShare();
} else {
Toast.makeText(context, getResources().getString(R.string.try_again), Toast.LENGTH_SHORT).show();
}
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
SharedPreferences prefs = getSharedPreferences("GOOGLE_TOKEN", MODE_PRIVATE);
String token = prefs.getString("token", null);
params.put("Authorization", "Bearer " + token);
return params;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> jsonObject = new HashMap<>();
try {
jsonObject.put("id", "Video id");
jsonObject.put("rating", rating);
} catch (Exception e) {
e.printStackTrace();
}
Log.e("jsonObject", "" + jsonObject);
return jsonObject;
}
};
AppController.getInstance().addToRequestQueue(jsonObjectRequest, tag_json_obj);
}
I hope this is usefull for you..

android volley post json ID and get result back from PHP server

i am struggling to make this work, basically i get an id from previous activity using intent, now i want to send this id to server so it returns all the data associated with this id.
javacode
final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
PHP server
if (!empty($_POST)) {
$query = " SELECT * FROM table WHERE ID = :ID " ;
$query_params = array(
':ID' => $_POST['ID'],);
try {
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database query error";
die(json_encode($response));
}
$result = $statement->fetchAll();
if($result){
$data =array();
foreach($result as $rows){
$json = array();
$json["Name"] = $rows["Name"];
array_push ($data,$json);
}
echo stripcslashes(json_encode($data, JSON_PRETTY_PRINT));
i used this example of http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put and coverted the string response to string array, worked for me
url = "http://httpbin.org/post";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Alif");
params.put("domain", "http://itsalif.info");
return params;
}
};
queue.add(postRequest);
I would modify the request like this:
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,URL,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
return params;
}
};
ApplicationController.getInstance().addToRequestQueue(req);
and also would modify the PHP code like this:
if (isset($_POST['ID'])) {
$id = $_POST['ID'];
try {
$statement = $db->prepare(SELECT * FROM table WHERE ID = ?);
$statement->bindValue(1, $id);
$result = $statement->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database query error";
die(json_encode($response));
}
$records = array();
$records = $statement->fetchAll(PDO::FETCH_ASSOC);
$data = array();
foreach($records as $record){
$data["Name"] = $record["Name"];
}
echo stripcslashes(json_encode($data, JSON_PRETTY_PRINT));
}
Hope it helps!!!
the issue is that you send json but you expect params in you php.
there 2 solutions:
1) update php to accept json not just post params
2) update volley request to send post params but expect JSONObject
for example you can use this request:
public class JsonObjReq extends Request<JSONObject> {
private final Response.Listener<JSONObject> mListener;
private final Map<String, String> params;
public JsonObjReq(int method, String url, Map<String, String> params, Response
.Listener<JSONObject> mListener,
Response.ErrorListener listener) {
super(method, url, listener);
this.mListener = mListener;
this.params = params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
}
and apply to your code like that:
final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("ID", "1");
JsonObjReq req = new JsonObjReq(Method.POST, URL, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
print response in textview;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

Categories

Resources