I cant post com.android.volley.ServerError - java

I try to only post my php script with this code but I have a Server Errorlike so
private static final String URL1 = "https://exp.com/appLoc.php";
private void User_Enter(){
StringRequest strRequest1 = new StringRequest(Request.Method.POST, URL1,
new Response.Listener<String>(){
#Override
public void onResponse(String response){
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams(){
Map<String, String> params1 = new HashMap<String, String> ();
params1.put ("location",la+","+lo);
params1.put ("licence",shpref.getString (Current_user,null));`like so`
params1.put ("main","enter");
return params1;
}
};
queue.add(strRequest1);
}

hi you may have error from server side to decode error what type of error it is use this
public void ShowResponse_Error(VolleyError error, Context context) {
if (error instanceof NetworkError) {
Toast.makeText(context,
context.getString(R.string.internet_error),
Toast.LENGTH_LONG).show();
} else if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(context,
context.getString(R.string.timeout_error),
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
Toast.makeText(context,
context.getString(R.string.auth_error),
Toast.LENGTH_LONG).show();
} else if (error instanceof ServerError) {
DecodeError(context, error);
}
}
private static void DecodeError(Context context, VolleyError error) {
NetworkResponse response = error.networkResponse;
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
Toast.makeText(context,
obj.getString("message"),
Toast.LENGTH_LONG).show();
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
in String res you will get error.

Related

Is there problem in instagram's "graphql" api? Volley library giving error when I make request

I'm trying to get data from Instagram's graphql api.
I'm making request to "https://www.instagram.com/p/CQWYMTlqB9w/?__a=1" and volley giving me this error: Something went wrong com.android.volley.ParseError: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
It was working well until morning but when I used it before few hours then it started to give that error. for some users it is giving this error
Is graphql having any issues or problem with volley?
( if we add ?__a=1 to the end of any post link then it gives post data in the json form)
private void downloadInstaImage() {
dialog.show();
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(InstaImages.this);
if (binding.instImageaurl.getText().toString().contains("?utm_source=ig_web_copy_link")) {
String partToRemove = "?utm_source=ig_web_copy_link";
image = binding.instImageaurl.getText().toString().replace(partToRemove, "");
} else if (binding.instImageaurl.getText().toString().contains("?utm_source=ig_web_button_share_sheet")) {
String partToRemove = "?utm_source=ig_web_button_share_sheet";
image = binding.instImageaurl.getText().toString().replace(partToRemove, "");
} else {
image = binding.instImageaurl.getText().toString();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
image + "?__a=1", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject Obj1 = null;
try {
Obj1 = response.getJSONObject("graphql");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject Obj2 = null;
try {
Obj2 = Obj1.getJSONObject("shortcode_media");
} catch (JSONException e) {
e.printStackTrace();
}
String finalImageUrl = null;
try {
finalImageUrl = Obj2.getString("display_url");
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("myapp", finalImageUrl);
Util.download(finalImageUrl, Util.RootDirectoryInstaImages, InstaImages.this, "insta" + ".png");
dialog.dismiss();
Toast.makeText(activity, "Downloading Started...", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Log.e("myapp", "Something went wrong " + error);
Toast.makeText(activity, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest);
}

AuthFailureError on a volley form data response

I get the following error:
AuthFailureError: com.android.volley.AuthFailureError
My code:
public void createNoticeBoard() {
RequestQueue queue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.PENDING_MEDIA_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject stringResponse = new JSONObject(response);
boolean success = stringResponse.getBoolean("is_success");
String requestCode = stringResponse.getString("status_code");
if (success) {
if (requestCode.equals("200")) {
Toast.makeText(mContext, "Publisher deleted!", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(mContext, "Unauthorized!", Toast.LENGTH_LONG).show();
}
} catch (JSONException je) {
je.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e(TAG, "AuthFailureError: " + error);
Toast.makeText(mContext, "Error! Please try again.", Toast.LENGTH_LONG).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> parameter = new HashMap<>();
Log.d("Network", parameter.toString());
return parameter;
}
#Override
protected Map<String, String> getParams() {
Map<String,String> params = new HashMap<String, String>();
params.put("extension", "image/jpeg");
params.put("duration", String.valueOf(20));
params.put("title", "Postman Highlight");
params.put("organization_id", String.valueOf(274));
params.put("screen_type", "TAGNOTICEBOARD");
params.put("type", "IMAGE");
params.put("do", String.valueOf(7));
params.put("advertise_bit", String.valueOf(1));
params.put("start_datetime", "2021-05-06 10:37:13");
params.put("end_datetime", "2021-05-10 10:37:13");
params.put("Global_Counter", String.valueOf(0));
params.put("Venue_Counter", String.valueOf(0));
params.put("adindex", String.valueOf(0));
params.put("adtype", "Fulltime");
params.put("media_url", "");
return params;
}
#Override
public byte[] getBody() throws AuthFailureError {
final String request = getParams().toString();
Log.e("REQ", request);
try {
return request.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", request, "utf-8");
return null;
}
}
};
queue.add(stringRequest);
}

Instagram API follow user from app not working

I've been working with instagram API for a while. Since there is no official documentation for changing relationship between users, I've found something on StackOverflow. It is an old answer, and I am not sure if this is even possible now. Can anyone tell me if there is error with my code or this functionality is just disabled by Instagram? I know some apps which are able to follow directly from the app, so I would like to know a way to do that in my app.
Here is my function for following:
public void follow(String userID){
String followURL = "https://api.instagram.com/v1/users/"+ userID +"/relationship?action=unfollow&access_token=" + instagramData.getString(InstagramData.LONG_ACCESS_TOKEN);
RequestQueue requestQueue = Volley.newRequestQueue(context);
CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST, followURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null) {
Log.d(tag, response.toString());
} else Log.d(tag, "Null");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
JSONObject obj = new JSONObject(res);
} catch (UnsupportedEncodingException e1) {
Log.d(tag, e1.toString());
} catch (JSONException e2) {
Log.d(tag, e2.toString());
}
} else {
Log.d(tag, "error");
}
}
});
requestQueue.add(jsObjRequest);
}
UserID and AccessToken are okay for sure.

Android volley returns clienterror 400 [Bad request]

I try everything to solve it but I couldn't. can anybody help me to solve this.
I try to login through volley but it gives bad request 400 error, I think it is because of body content type but I also override getbodycontenttype method but it doesn't work,
here is code
String url = "http://192.168.1.129:5000/api/dealers/login";
StringRequest stringRequest = new StringRequest( Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
Log.d("response", response);
try {
JSONObject data= new JSONObject(response);
//Boolean error =jsonObject.getBoolean("error");
if (data.getString("success").equals("true")) {
String message=data.getString("msg");
startActivity( new Intent( LoginActivity.this, MainActivity.class ) );
finishAffinity();
} else {
Toast.makeText(LoginActivity.this,
data.getString("msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
Toast.makeText(LoginActivity.this, String.valueOf(networkResponse.statusCode),
Toast.LENGTH_SHORT).show();
}else{
Log.e("Status code", String.valueOf(error));
Toast.makeText(LoginActivity.this, String.valueOf(error),
Toast.LENGTH_LONG).show();
}
}
}){
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("mobile",userMobile);
params.put("password",userPassword);
return params;
}
};
int socketTimeout = 0;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(stringRequest);
HelloIf your server is correct, do this, but when I used this address, I did not receive any data ...
I also made a error in doing a project using it ... it is better to use version of 1.1.0 and before it ...

Activity keeps restarting when I leave the activity and come back to it

I have two activities, When I will move from activity A to B, B keeps restarting or "refreshing", when i go back from B to A, it also keeps restarting. The code is very big, here I am posting area where I think problem causes :
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
deviceStatus();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
this is deviceStatus();
public void deviceStatus(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(InActivate.this);
String URL = "http://gickuwait-dev.com/electionapi/api/DeviceStatus";
JSONObject jsonBody = new JSONObject();
jsonBody.put("device_PK", device_ID2);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("true")){
Intent intent = new Intent(InActivate.this, Vote.class);
startActivity(intent);
finish();
}else if(response.equals("false")) {
}
// Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<DeviceStatusResponse> list = new ArrayList<DeviceStatusResponse>();
Type listType = new TypeToken<List<DeviceStatusResponse>>() {}.getType();
list = new Gson().fromJson(responseString, listType);
device_Status = list.get(0).getIsActive().toString();
// Toast.makeText(getApplicationContext(), ""+device_Status+" null ", Toast.LENGTH_LONG).show();
return Response.success(device_Status, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
in Activity B, i have the same code to check the device status from the database, any help would be appreciated
You can use Handle to check the repeated task.
private Handler delayHandler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
deviceStatus();
driverDelayHandler.postDelayed(runnable, 1000);
}
};
Don't forgot to cancel on onStop method.
delayHandler.removeCallbacks(runnable);

Categories