google/volley App crashing when URL do not exist - android

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)

Related

Android volley NoConnection Error : java.io.IOException, java.io.EOFException

StringRequest stringRequest = new StringRequest(Request.Method.POST, UrlEndPoints.interAd,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Response::", response);
try {
int success;
JSONObject jsonObject = new JSONObject(response);
Log.e("jObj_AppURL", String.valueOf(jsonObject));
success = jsonObject.getInt(SUCCESS);
if (success == 1) {
JSONArray data = jsonObject.getJSONArray(RESPONSE);
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
appImg = c.getString(APPIMG);
appName = c.getString(APPNAME);
appPackages = c.getString(PKG);
InterAdModel interAdModel = new InterAdModel();
interAdModel.setAppImg(appImg);
interAdModel.setAppName(appName);
interAdModel.setAppPackages(appPackages);
interAdModelArrayList.add(interAdModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("erorr::", error.toString());
Toast.makeText(SplashActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
//for check service is correctly functioning use package name "com.whatsweb.whatscan.whatsappweb.whatscanforwhatweb"
Map<String, String> params = new HashMap<>();
params.put("task", "get_interad_apps");
params.put("package", getPackageName());
return params;
}
};
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue = Volley.newRequestQueue(SplashActivity.this);
requestQueue.add(stringRequest);
I am facing error while parsing the JSON object. I am adding two fields,ie. the task and the package name of the application using Map, but it is always throwing the Exceptions. Very rarely I get the actual data. Sometimes It throws only EOFException while sometimes NoConnection error.
Read NoConnectionError.
Error indicating that no connection could be established when
performing a Volley request.
#SuppressWarnings("serial")
public class NoConnectionError extends NetworkError {
public NoConnectionError() {
super();
}
public NoConnectionError(Throwable reason) {
super(reason);
}
}
You should add
public void onErrorResponse(VolleyError error)
{
if (error instanceof NoConnectionError)
{
// Your Code
}
}
You can check
Handle Volley Error.

Server responce is in json form

I want to send and receive data from server. For this I've used Volley. The code is in below. Volley can receive the data in Json format. The Server can send and receive data in Json format. How do I convert this Json data into a user readable JAVA format ?? There are about 10 methods in other class. The below class contains the methods for network calls and also interacts with the MainActivity.
public class Api_Volley {
String data;
String flag;
public void my_volley_post (String url , JSONObject jsonObject , final Context context ) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url , jsonObject , new Response.Listener(){
#Override
public void onResponse(Object response) {
String flag = response.toString();
Toast.makeText( context , flag , Toast.LENGTH_LONG ).show();
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context , "Wrong" , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
ApiVolleySingeltonClass.getInstance(context).addToRequestque(jsonObjectRequest);
}
}
Methods in another class:
public void showAllOrderByUserId() {
try {
data_args.put("userId", 2);
} catch (JSONException e) {
e.printStackTrace();
}
try {
data_action.put("action", "showAllOrderByUserId");
data_action.put("args", data_args);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
route = "/order";
new Api_Volley().my_volley_post(addUserUrl + route, data_action, context);
}
Your can use json data like
{"userNodes":[{"id":"1","name":"Enamul Haque"}]}
You can use volley like bellow
private void doLoginAction() {
String url_login = "http://www.lineitopkal.com/android/login.php";
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("userNodes");
for (int i = 0; i < loginNodes.length(); i++) {
JSONObject jo = loginNodes.getJSONObject(i);
String id = jo.getString("id");
Log.e("id ::",id);
String name = jo.getString("name");
Log.e("name ::",name);
}
} 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<>();
//Post parameter like bellow
params.put("uname", "era#gmail.com");
params.put("pass", "123456");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Create your Response format like this
public class Post {
long id;
Date dateCreated;
String title;
String author;
String url;
String body;
}
After making request like below
public void my_volley_post (String url , JSONObject jsonObject , final Context context ) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url , jsonObject , new Response.Listener(){
#Override
public void onResponse(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
// This will be your Entity
Post post = gson.fromJson(response, Post.class));
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context , "Wrong" , Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
ApiVolleySingeltonClass.getInstance(context).addToRequestque(jsonObjectRequest);
}
You have to parse JSON and have to show according to need:
By this you can use GSON (Its easy)
Use this Site to convert JSON to pojo classes.
Click here
These are the References site you can use and implement :
http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html
https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
https://kylewbanks.com/blog/tutorial-parsing-json-on-android-using-gson-and-volley

JSONObject not response

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) {
}

Android Volley post request not working on click?

Im creating an application where i can make reports and,on button click nothing happens,even the response does not come,toast not showing up. This volley post i have used it before and it is correct,another thing i should write is that i have to send the token for authorization.
this is my code:
//this is button click
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
volley_send();
}
});
//-----------------------------------------------------
//this is volley post
private void volley_send(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, "my_url",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// save_on_sharedPreference("email",email);
if(!response.isEmpty()){
try {
JSONObject jsonObject = new JSONObject(response);
error = jsonObject.getBoolean("error");
String message = jsonObject.getString("message");
if(!error){
//String token = jsonObject.getString("token");
//JSONObject data = jsonObject.getJSONObject("data");
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), Raport_Cat_NoPhoto.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
}
// JSONArray feedArray = response.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
System.out.println("JSONException :"+e.toString() );
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(),getString(R.string.err_connection),Toast.LENGTH_SHORT).show();
} else if (error instanceof AuthFailureError) {
//TODO
//Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_authentication),Toast.LENGTH_SHORT).show();
} else if (error instanceof ServerError) {
//TODO
//Toast.makeText(getApplicationContext(),"3",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_system),Toast.LENGTH_SHORT).show();
} else if (error instanceof NetworkError) {
//TODO
//Toast.makeText(getApplicationContext(),"4",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_network),Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
//TODO
//Toast.makeText(getApplicationContext(),"5",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),getString(R.string.err_processing),Toast.LENGTH_SHORT).show();
}
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Authorization","Bearer "+ApiKey);
return headers;
}
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("category","cat_ankese");
params.put("description",description.getText().toString());
params.put("city",Qyteti);
params.put("fshati",fshati.getText().toString());
params.put("address",address.getText().toString());
params.put("additional_information1",personidyshuar.getText().toString());
params.put("name",emer.getText().toString());
params.put("surname",mbiemer.getText().toString());
params.put("telephone",telefon.getText().toString());
params.put("email",email.getText().toString());
params.put("info_latt",my_latitude);
params.put("info_long",my_longitude);
params.put("file[]",image123);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
I don't know what it is wrong...
Sems like the problem was with the Authorization header,for any reason it requires only one parameter. Thank you all for replies!

Connection Timeout Android

i have an android app in which i hit a web service and gets the result.
Now i want is if result is getting to long to be fetched or in between request internet connection is gone then i show a message or a dialog to the user that Your connection timed out
I've tried this code but this is not working
Any help would be appreciated
blic void getVolleyTask(Context context,
final IVolleyReponse responseContext, String URL) {
RequestQueue request = Volley.newRequestQueue(context);
StringRequest strReq = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (response != null) {
JSONArray _array = new JSONArray(response);
responseContext.ResponseOk(_array);
} else {
responseContext.ResponseOk(null);
}
} catch (Exception e) {
e.printStackTrace();
responseContext.ResponseOk(null);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
responseContext.ErrorBlock();
}
});
strReq.setRetryPolicy(new DefaultRetryPolicy(socketTimeout, maxTries,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
request.add(strReq);
}
public void getVolleyPostTask(Context context,
final IVolleyJSONReponse jsonResponseContext, String URL,
JSONObject obj) {
RequestQueue request = Volley.newRequestQueue(context);
JsonObjectRequest myRequest = new JsonObjectRequest(
Request.Method.POST, URL, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
jsonResponseContext.ResponseOk(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
jsonResponseContext.ErrorBlock();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
myRequest.setRetryPolicy(new DefaultRetryPolicy(socketTimeout,
maxTries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
request.add(myRequest);
}
thanks in advance!
VollyJson library have a capability to differentiate different network errors while communicating with webservices.When something went wrong with JSONObjectRequest onErrorResponse will be called,there you can differentiate the error as follows.
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
//Write Your code here
} else if (error instanceof AuthFailureError) {
//TODO
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}

Categories

Resources