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) {
}
Related
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
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)
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!
I have an app in which inside onCreate its sending request to server and I have added a SwipeRefresh when I swipe down again, the request is sent to server.
Problem is that when I swipe down, a ProgressDialog is shown to me which I don't want. What I want is, if swipe is refreshing then don't show the ProgressDialog, otherwise show ProgressDialog.
Code:-
m_SwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getWalletBalance();
}
});
/* Here in this method we send request to server for wallet balance */
private void getWalletBalance() {
CLoginSessionManagement s_oSessionManagement = new CLoginSessionManagement(getApplicationContext());// making object of Registartion session management
// retreive user data from shared preferencce........
HashMap<String, String> user = s_oSessionManagement.getLoginDetails();// getting String from Regisatrtion session
String m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();
String m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", m_szMobileNumber);// sending mobile no.(static right know becuse of ser side data on other is null
jsonObject.put("pin", m_szEncryptedPassword);// same here as said above
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
Log.i(TAG, "Server request:-" + json);
//here I am getting error
m_Dialog = DialogUtils.showProgressDialog(getApplicationContext(),"Fetching wallet details...");
final String s_szWalletURL = "http://metallica/getWalletBalanceInJSON";
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, s_szWalletURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Server Response:-" + response);
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
m_Dialog.dismiss();
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
s_szWalletBalance = response.getString("walletbalance").trim();// get wallet balance fro response
String trimwalletBalance = s_szWalletBalance.substring(0, s_szWalletBalance.indexOf("."));// trim waalet balance from response.
CWalletDataModel.getInstance().setS_szWalletBalance(trimwalletBalance);// set wallet balance
// showing wallet transaction in textView....
m_WalletText.setText(CWalletDataModel.getInstance().getS_szWalletBalance());
} else if (nResultCodeFromServer == CStaticVar.m_kCONNECTION_NOT_AVAILABLE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection not available", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTIMED_OUT) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Timed Out", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTECHNICAL_FAILURE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Technical Failure", getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error:-" + error);
m_Dialog.dismiss();
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
m_Dialog.dismiss();
}
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection time out! please try again", getApplicationContext());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No Internet connection", getApplicationContext());
}
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Define this variable in your activity
boolean isShowProgressDialog=true;
m_SwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
isShowProgressDialog=false;
getWalletBalance();
}
});
private void getWalletBalance() {
CLoginSessionManagement s_oSessionManagement = new CLoginSessionManagement(getApplicationContext());// making object of Registartion session management
// retreive user data from shared preferencce........
HashMap<String, String> user = s_oSessionManagement.getLoginDetails();// getting String from Regisatrtion session
String m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();
String m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", m_szMobileNumber);// sending mobile no.(static right know becuse of ser side data on other is null
jsonObject.put("pin", m_szEncryptedPassword);// same here as said above
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
Log.i(TAG, "Server request:-" + json);
if(isShowProgressDialog){
isShowProgressDialog=true;
m_Dialog = DialogUtils.showProgressDialog(getApplicationContext(),"Fetching wallet details...");
}
final String s_szWalletURL = "http://metallica/getWalletBalanceInJSON";
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, s_szWalletURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Server Response:-" + response);
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
if(m_Dialog!=null && m_Dialog.isShowing()){
m_Dialog.dismiss();}
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
s_szWalletBalance = response.getString("walletbalance").trim();// get wallet balance fro response
String trimwalletBalance = s_szWalletBalance.substring(0, s_szWalletBalance.indexOf("."));// trim waalet balance from response.
CWalletDataModel.getInstance().setS_szWalletBalance(trimwalletBalance);// set wallet balance
// showing wallet transaction in textView....
m_WalletText.setText(CWalletDataModel.getInstance().getS_szWalletBalance());
} else if (nResultCodeFromServer == CStaticVar.m_kCONNECTION_NOT_AVAILABLE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection not available", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTIMED_OUT) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Timed Out", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTECHNICAL_FAILURE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Technical Failure", getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error:-" + error);
m_Dialog.dismiss();
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
if(m_Dialog!=null && m_Dialog.isShowing()){
m_Dialog.dismiss();}
}
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection time out! please try again", getApplicationContext());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No Internet connection", getApplicationContext());
}
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
Set a variable to mark if the swipe refreshing is going on like this.
private boolean isRefreshing = false;
m_SwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
isRefreshing = true; // Set the swipe refresh to true
getWalletBalance();
}
});
/* Here in this method we send request to server for wallet balance */
private void getWalletBalance() {
CLoginSessionManagement s_oSessionManagement = new CLoginSessionManagement(getApplicationContext());// making object of Registartion session management
// retreive user data from shared preferencce........
HashMap<String, String> user = s_oSessionManagement.getLoginDetails();// getting String from Regisatrtion session
String m_szMobileNumber = user.get(CLoginSessionManagement.s_szKEY_MOBILE).trim();
String m_szEncryptedPassword = user.get(CLoginSessionManagement.s_szKEY_PASSWORD).trim();
try {
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", m_szMobileNumber);// sending mobile no.(static right know becuse of ser side data on other is null
jsonObject.put("pin", m_szEncryptedPassword);// same here as said above
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
Log.i(TAG, "Server request:-" + json);
// Add a check here
if(isRefreshing) m_Dialog = DialogUtils.showProgressDialog(getApplicationContext(),"Fetching wallet details...");
final String s_szWalletURL = "http://metallica/getWalletBalanceInJSON";
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, s_szWalletURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Server Response:-" + response);
// Reset the value here
isRefreshing = false;
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
m_Dialog.dismiss();
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
s_szWalletBalance = response.getString("walletbalance").trim();// get wallet balance fro response
String trimwalletBalance = s_szWalletBalance.substring(0, s_szWalletBalance.indexOf("."));// trim waalet balance from response.
CWalletDataModel.getInstance().setS_szWalletBalance(trimwalletBalance);// set wallet balance
// showing wallet transaction in textView....
m_WalletText.setText(CWalletDataModel.getInstance().getS_szWalletBalance());
} else if (nResultCodeFromServer == CStaticVar.m_kCONNECTION_NOT_AVAILABLE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection not available", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTIMED_OUT) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Timed Out", getApplicationContext());
} else if (nResultCodeFromServer == CStaticVar.m_kTECHNICAL_FAILURE) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Technical Failure", getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error:-" + error);
m_Dialog.dismiss();
if (m_SwipeRefresh.isRefreshing()){
m_SwipeRefresh.setRefreshing(false);
}else {
m_Dialog.dismiss();
}
if (error instanceof TimeoutError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "Connection time out! please try again", getApplicationContext());
} else if (error instanceof NetworkError) {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No Internet connection", getApplicationContext());
}
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
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();
}
}