I have a problem. I am trying to take the movie name with volley get method on myapifilms, but can't get it to work. Where did I make mistakes?
output:Volley error
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext);
////
String showUrl ="http://www.myapifilms.com/imdb/idIMDB?title=batman&token=mytoken&format=json&language=en-us&limit=10";
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, showUrl , new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getMessage());
Toast.makeText(Welcome.this, "Volley Error", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsObjRequest);
if(volleyError != null && volleyError.networkResponse != null) {
VolleyError error = null;
try {
error = new VolleyError(new String(volleyError.networkResponse.data));
} catch (Exception var6) {
var6.printStackTrace();
}
try {
JSONObject e = null;
if(error != null) {
e = new JSONObject(error.getMessage());
}
String Error = e != null?e.getString("message"):"error";
System.out.println(Error);
Toast.makeText(Welcome.this, "Volley Error", Toast.LENGTH_SHORT).show();
} catch (JSONException var5) {
var5.printStackTrace();
}
}
Related
So I've implemented google/volley in my apps. When i code the apps i accidentally mistyped the url address and the app just crash suddenly. So how can i avoid this kind of problem. Below are the code i've used.
String url_login = "http://10.0.2.2/test_sstem/public/login";
//Send Post data and retrieve server respond
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_login,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,"On Response "+response,Toast.LENGTH_LONG).show();
ValidateLogin(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.data != null) {
String jsonError = new String(networkResponse.data);
String message_response=null;
try {
JSONObject object = new JSONObject(jsonError);
message_response= object.getString("error");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(LoginActivity.this, "On Error " + message_response.toString(), Toast.LENGTH_LONG).show();
showProgress(false);
}
}
})
I know that it can be fixed by correcting the URL, but what if the URL are not alive and working how do we work around this problem.
I have used bellow method for volley which is work for me.. i have used wrong address but my app does not stop. Use bellow full method..
private void doLoginAction() {
pDialog.show();
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) {
pDialog.dismiss();
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);
}
There can be number of reasons why your app crashes with incorrect url, one could be that the host is un resolvable, you can check the validity of a Url by using the following code:
URLUtil.isValidUrl(url)
How do I check if this text appears or not
{"cod":"404","message":"city not found"}
url : http://api.openweathermap.org/data/2.5/weather?q=fddfgdfgdfgdfg&units=metric&appid=efb8013262db1b77b0431909b8b173e1
My try
public void btn_search(View view) {
CheckInternet checkInternet = new CheckInternet(MainActivity.this);
boolean ci = checkInternet.isconnecting();
if(ci)
{
EditText ed_Search = (EditText)findViewById(R.id.ed_Search);
if(ed_Search.getText().length() > 0)
{
String urlOpenWeatherMap = "http://api.openweathermap.org/data/2.5/weather?q=fddfgdfgdfgdfg&units=metric&appid=efb8013262db1b77b0431909b8b173e1";
progressBar = (ProgressBar)findViewById(R.id.progressBar);
btn_search = (ImageView)findViewById(R.id.btn_search);
btn_search.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonobjectrequest = new JsonObjectRequest(Request.Method.GET, urlOpenWeatherMap, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String x = response.getString("message");
if(x.contains("404") || x.contains("city not found") )
{
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "welcome", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonobjectrequest);
}
else
{
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(MainActivity.this, "no Internet", Toast.LENGTH_SHORT).show();
}
}
I am trying to solve the problem 4 hours ago but no use
I think the problem here
String x = response.getString("message");
I need help please
You are getting json text in the response body, but the server is responding with 404 code which is an error, therefore the logic needs to be inside the overridden method:
#Override
public void onErrorResponse(VolleyError error) {
String body;
String statusCode = String.valueOf(error.networkResponse.statusCode);
if(statusCode == "400") {
// do your thing
}
// do something else
}
Json Might be look like
{"loginNodes":[{"message":"Welcome To Alamofire","name":Enamul Haque,"errorCode":"0","photo":null}]}
Your code should be ..
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://api.openweathermap.org/data/2.5/weather",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray loginNodes = jsonObject.getJSONArray("loginNodes");
pDialog.dismiss();
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String message= jo.getString("message");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
try {
} catch (Exception e) {
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("q", "fddfgdfgdfgdfg");
params.put("units", "metric");
params.put("appid", "efb8013262db1b77b0431909b8b173e1");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
Check response from GET OR Post.You can debug the error onErrorResponse
try {
if (error instanceof TimeoutError ) {
}else if(error instanceof NoConnectionError){
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}
} catch (Exception e) {
}
I have an API call with below details
URL: http://pankajservers.in/api/v1/AuthenticateUser with Input params
below
EmailAddress and Password
if I type wrong credentials, I get below JSON response with Status Code : 403
{"Status":false,"Message":"Invalid Credentials. 5 attempts left.","Data":null}
Below is the Error Response Code.
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
if (null != error.networkResponse)
{
Log.d(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
}
}
});
Is there any way to get JSON response in this code block?
I tried this post: Volley handle onErrorResponse
But it seems it never execute parseNetworkError
To print the Error on that block you just need to obtain the Response bytes:
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.data != null) {
String jsonError = new String(networkResponse.data);
// Print Error!
}
You can create custom request like this:
public class BaseRequest extends Request {
private static final String TAG = BaseRequest.class.getSimpleName();
private final Gson gson = new Gson();
private final Response.Listener listener;
public BaseRequest(String url, Response.Listener responseListener, Response.ErrorListener listener) {
super(Request.Method.GET, url, listener);
Log.e(TAG, "Requesting url : " + url);
this.listener = responseListener;
}
public BaseRequest(int method, String url, Response.Listener responseListener, Response.ErrorListener listener) {
super(method, url, listener);
Log.e(TAG, "Requesting url : " + url);
this.listener = responseListener;
}
#Override
public Response parseNetworkResponse(NetworkResponse response) {
try {
String json = null;
json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
JSONObject result = new JSONObject(json);
if (!result.getBoolean("Status"))
return Response.success(
result.get("Data"),
HttpHeaderParser.parseCacheHeaders(response));
else
return Response.error(new VolleyError(result.getString("Message")));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
} catch (JSONException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return volleyError;
}
#Override
protected void deliverResponse(Object response) {
listener.onResponse(response);
}
}
and make request:
BaseRequest baseRequest = new BaseRequest(Request.Method.POST, url, new Response.Listener() {
#Override
public void onResponse(Object response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error : " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Your parameters
return params;
}
};
queue.add(baseRequest);
You can cast an error response to a Json Object
JSONObject jsonObject = new JSONObject();
JsonObjectRequest JO = new JsonObjectRequest(Request.Method.POST,"URL String Here",jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Your Logic
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
JSONObject JO = new JSONObject(error.toString());
}catch (JSONException e){
e.printStackTrace();
}
}
});
I have used the volley library to get the API response. Initially when am calling the API the error response is showing exactly from the server. but when i again call the API means i am getting error response is null.
Kindly help me to do this.
Here is my code
public void requestString(final String requestName,
final String webserviceUrl,
final Map<Object, Object> requestParams, final int webMethod,
final boolean getCache) {
LogUtils.i("Sending Request", webserviceUrl);
StringRequest stringRequest = new StringRequest(webMethod,
webserviceUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
LogUtils.i("Response", response);
mRequestCompletedListener.onRequestCompleted(
requestName, true, response, null);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String errorResponse = null;
if (getCache) {
final Cache cache = AppController.getInstance()
.getRequestQueue().getCache();
final Entry entry = cache.get(webserviceUrl);
if (entry.data != null) {
try {
errorResponse = new String(entry.data, "UTF-8");
mRequestCompletedListener
.onRequestCompleted(requestName,
true, errorResponse, null);
return;
} catch (UnsupportedEncodingException e) {
LogUtils.e(TAG, e);
}
} else {
LogUtils.e(TAG, requestName
+ " Cache does not exist");
}
}
try {
VolleyError responseError = new VolleyError(
new String(error.networkResponse.data));
LogUtils.i("ErrorResponse", responseError.getMessage());
try {
if (responseError != null) {
final JSONObject responseJson = new JSONObject(responseError.getMessage());
// Show Alert Information
errorResponse = responseJson.getString(AppConstants.MESSAGE);
}
} catch (Exception e) {
errorResponse = "Unknown";
}
} catch (Exception e) {
LogUtils.e(TAG, e);
}
mRequestCompletedListener.onRequestCompleted(
requestName, false, null,
errorResponse);
}
})
stringRequest.setTag(requestName);
// Adding String request to request queue
AppController.getInstance().addToRequestQueue(stringRequest);
}
Here am passing the Params:
AppController.getInstance().requestApi(mVolleyRequest, REQUEST_NAME, PATH
+ API, Request.Method.POST, HTTP_POST, Request.Priority.HIGH
, false, out.toString().trim(), true);
I want to build a Utils class to make Volley calls simpler, like this:
Utils.java:
public class Utils {
static JsonObjectRequest mJsonObjectRequest;
protected static boolean busy = true;
public static JSONObject makeJsonObjectRequest(Context context, int method, String url){
final JSONObject[] jsonObject = new JSONObject[1];
mJsonObjectRequest = new JsonObjectRequest
(method, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
jsonObject[0] = response;
busy = false;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
try {
jsonObject[0] = new JSONObject(error.toString());
} catch (JSONException e) {
e.printStackTrace();
}
busy = false;
}
});
// Access the RequestQueue through your singleton class.
VolleySingleton.getInstance(context).addToRequestQueue(mJsonObjectRequest);
while (true) {
if (!busy) break;
}
return jsonObject[0];
}
}
MainActivity.java:
JSONObject jsonObject = Utils.makeJsonObjectRequest(this, Request.Method.GET, url);
mTxtDisplay.setText("Response: " + jsonObject.toString());
When app runs, jsonObject always null. I want to ask if I can delay return jsonObject[0] inside makeJsonObjectRequest until onResponse called. Can I do that and how?
.
If you execute makeJsonObjectRequest on a background thread, then you can execute synchronous Volley request this way:
Can I do a synchronous request with volley?
If you execute makeJsonObjectRequest on the UI thread, then you shouldn't wait for onResponse to avoid blocking UI thread. Use callback in this case.
I created this and managed like the following way please have a look, hope it will be useful to you
public class APIManager {
public static void createRequest(Context c, String requestTag,
String endPoint, List<NameValuePair> params,
final OnRequestCompletedListener listener,
TransParentProgressDialog pd) {
ServerDetails serverDetails = new ServerDetails(c, endPoint, params);
JsonObjectRequest request = new JsonObjectRequest(Method.GET,
serverDetails.getQueryUrl(), null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
listener.onRequestCompleted(response);
}
}, getErrorListener(c, pd)) {
};
AppController.getInstance().addToRequestQueue(request, requestTag);
}
public static ErrorListener getErrorListener(final Context c,
final TransParentProgressDialog pd, final TextView tvEmpty,
final String errorText) {
Response.ErrorListener listener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
if (tvEmpty != null) {
tvEmpty.setText(errorText);
}
MyDialog dialog;
Log.d("volley-error", error.toString());
if (error instanceof TimeoutError) {
dialog = new MyDialog(c, "Server Timeout");
dialog.show();
return;
} else if (error instanceof NoConnectionError) {
dialog = new MyDialog(c, "No Connection or Invalid Url");
dialog.show();
return;
} else if (error instanceof ServerError) {
NetworkResponse response = error.networkResponse;
if (response != null) {
// int statusCode = response.statusCode;
byte[] data = response.data;
if (data != null) {
String str = new String(data);
try {
JSONObject object = new JSONObject(str);
Log.d("error response", object.toString());
if (object.has("errors")) {
JSONArray errors = object
.getJSONArray("errors");
JSONObject errorObject = errors
.getJSONObject(0);
dialog = new MyDialog(c, "Error!",
errorObject.getString("message"));
dialog.show();
} else {
dialog = new MyDialog(c, "Error!",
object.toString());
dialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
dialog = new MyDialog(c, "Error!", "Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Server Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Server Error");
dialog.show();
}
} else if (error instanceof NetworkError) {
NetworkResponse response = error.networkResponse;
if (response != null) {
// int statusCode = response.statusCode;
byte[] data = response.data;
if (data != null) {
String str = new String(data);
try {
JSONObject object = new JSONObject(str);
Log.d("error response", object.toString());
if (object.has("errors")) {
JSONArray errors = object
.getJSONArray("errors");
JSONObject errorObject = errors
.getJSONObject(0);
dialog = new MyDialog(c, "Error!",
errorObject.getString("message"));
dialog.show();
} else {
dialog = new MyDialog(c, "Error!",
object.toString());
dialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
dialog = new MyDialog(c, "Error!", "Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Network Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Network Error");
dialog.show();
}
} else if (error instanceof ParseError) {
dialog = new MyDialog(c, "Parse Error");
dialog.show();
} else if (error instanceof AuthFailureError) {
NetworkResponse response = error.networkResponse;
if (response != null) {
// int statusCode = response.statusCode;
byte[] data = response.data;
if (data != null) {
String str = new String(data);
try {
JSONObject object = new JSONObject(str);
Log.d("error response", object.toString());
if (object.has("errors")) {
JSONArray errors = object
.getJSONArray("errors");
JSONObject errorObject = errors
.getJSONObject(0);
dialog = new MyDialog(c, "Error!",
errorObject.getString("message"));
dialog.show();
} else {
dialog = new MyDialog(c, "Error!",
object.toString());
dialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
dialog = new MyDialog(c, "Error!", "Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Error!", "Error");
dialog.show();
}
} else {
dialog = new MyDialog(c, "Error connecting server");
dialog.show();
}
}
}
};
return listener;
}
}
And the interface for call back on request completed is
public interface OnRequestCompletedListener {
public void onRequestCompleted(JSONObject response);
}
Thanks to #Gennadii Saprykin's and #Gopal Singh Sirvi's answers, I have tried both Callable and Interface Listener ways. Both worked, however, I prefer Listener way.
OnRequestCompletedListener.java:
package com.example.volleyapp;
import org.json.JSONObject;
public interface OnRequestCompletedListener {
void onRequestCompleted(JSONObject response);
}
Utils.java:
package com.example.volleyapp;
import android.content.Context;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.Callable;
public class Utils {
static JsonObjectRequest mJsonObjectRequest;
static Callable<Void> func=null;
public static void makeJsonObjectRequest_Listener(final Context context, final int method, final String url, final OnRequestCompletedListener listener){
mJsonObjectRequest = new JsonObjectRequest
(method, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
listener.onRequestCompleted(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
try {
listener.onRequestCompleted(new JSONObject(error.toString()));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Access the RequestQueue through your singleton class.
VolleySingleton.getInstance(context).addToRequestQueue(mJsonObjectRequest);
}
public static void makeJsonObjectRequest_Callable(final Context context, final int method, final String url, final MainActivity.JsonCallable doRequest){
mJsonObjectRequest = new JsonObjectRequest
(method, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
func = doRequest;
doRequest.jsonObject = response;
func.call();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
try {
func = doRequest;
doRequest.jsonObject = new JSONObject(error.toString());
func.call();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Access the RequestQueue through your singleton class.
VolleySingleton.getInstance(context).addToRequestQueue(mJsonObjectRequest);
}
}
MainActivity.java:
package com.example.volleyapp;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONObject;
import java.util.concurrent.Callable;
public class MainActivity extends Activity {
JsonCallable jsonCallable=null;
TextView mTxtDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTxtDisplay = (TextView) findViewById(R.id.textView);
String url = "https://10.0.2.2/aspnet/webapi/products/1";
// Callable way
// jsonCallable = new JsonCallable();
// Utils.makeJsonObjectRequest_Callable(this, Request.Method.GET, url, jsonCallable);
// Listener way
OnRequestCompletedListener listener = new OnRequestCompletedListener() {
#Override
public void onRequestCompleted(JSONObject response) {
mTxtDisplay.setText(response.toString());
}
};
Utils.makeJsonObjectRequest_Listener(this, Request.Method.GET, url, listener);
}
class JsonCallable implements Callable {
public JSONObject jsonObject;
public JsonCallable(){
}
#Override
public Object call() throws Exception {
mTxtDisplay.setText(jsonObject.toString());
return null;
}
}
}
Once again, thank you all for your help!