I am Newbie at Json. I can't understanding how to parse this Json.
I am using volley and retrieving data in recyclerview. Help me to retrieve this Data.
This is the json lookin:
[{
"id":"ahiru-no-sora-dub-episode-1"
},{
"id":"ahiru-no-sora-dub-episode-2"
},{
"id":"ahiru-no-sora-dub-episode-3"
},{"id":"ahiru-no-sora-dub-episode-4"
},{"id":"ahiru-no-sora-dub-episode-5"
},{"id":"ahiru-no-sora-dub-episode-6"
},{"id":"ahiru-no-sora-dub-episode-7"
},{"id":"ahiru-no-sora-dub-episode-8"
},{"id":"ahiru-no-sora-dub-episode-9"
},{"id":"ahiru-no-sora-dub-episode-10"
},{"id":"ahiru-no-sora-dub-episode-11"
},{"id":"ahiru-no-sora-dub-episode-12"
},{"id":"ahiru-no-sora-dub-episode-13"
},{"id":"ahiru-no-sora-dub-episode-14"
},{"id":"ahiru-no-sora-dub-episode-15"
},{"id":"ahiru-no-sora-dub-episode-16"
},{"id":"ahiru-no-sora-dub-episode-17"
},{"id":"ahiru-no-sora-dub-episode-18"
},{"id":"ahiru-no-sora-dub-episode-19"
},{"id":"ahiru-no-sora-dub-episode-20"}]
This is the method I am calling from Activity:
public class OnGoingDetails extends AppCompatActivity
{
private RecyclerView mRecyclerView;
private EpisodeListAdapter mExampleAdapter;
private ArrayList<EpisodeListModel> mExampleList;
private RequestQueue mRequestQueue;
private ProgressDialog loadingPop;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.ongoing_detail);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
loadingPop = new ProgressDialog(this);
loadingPop.setTitle("Loading...");
loadingPop.setMessage("Please wait retrieving data from server");
loadingPop.setCanceledOnTouchOutside(false);
loadingPop.show();
Bundle extra = getIntent().getExtras();
String url = extra.getString("ID");
//Toast.makeText(OnGoingDetails.this,url, Toast.LENGTH_SHORT).show();
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response)
{
try
{
Toast.makeText(OnGoingDetails.this,s, Toast.LENGTH_SHORT).show();
JSONObject jsonob = new JSONObject();
JSONObject jo;
for(int i=0;i<jsonArray.length();i++){
jo=jsonArray.getJSONObject(i);
String ids=jo.getString("id");
loadingPop.dismiss();
Toast.makeText(OnGoingDetails.this, "Data: "+ids, Toast.LENGTH_SHORT).show();
ClipboardManager clipboard = (ClipboardManager) OnGoingDetails.this.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label","data"+ids); //ids.toString());
clipboard.setPrimaryClip(clip);
//Toast.makeText(getActivity(), "Data Refreshed", Toast.LENGTH_SHORT).show();
mExampleList.add(new EpisodeListModel(ids));
loadingPop.dismiss();
}
mExampleAdapter = new EpisodeListAdapter(OnGoingDetails.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
//Toast.makeText(getActivity(), "Added Data", Toast.LENGTH_SHORT).show();
loadingPop.dismiss();
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(OnGoingDetails.this, "Catch" + e, Toast.LENGTH_LONG).show();
loadingPop.dismiss();
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
if (error instanceof NetworkError)
{
loadingPop.dismiss();
Toast.makeText(OnGoingDetails.this,
"Oops. Network error!",
Toast.LENGTH_LONG).show();
}
else if (error instanceof ServerError)
{
loadingPop.dismiss();
Toast.makeText(OnGoingDetails.this,
"Oops. Server error!",
Toast.LENGTH_LONG).show();
}
else if (error instanceof AuthFailureError)
{
loadingPop.dismiss();
Toast.makeText(OnGoingDetails.this,
"Oops. Authintication error!",
Toast.LENGTH_LONG).show();
}
else if (error instanceof ParseError)
{
loadingPop.dismiss();
Toast.makeText(OnGoingDetails.this,
"Oops. Parse error!",
Toast.LENGTH_LONG).show();
}
else if (error instanceof NoConnectionError)
{
loadingPop.dismiss();
Toast.makeText(OnGoingDetails.this,
"No Internet Connection!",
Toast.LENGTH_LONG).show();
}
else if (error instanceof TimeoutError)
{
Toast.makeText(OnGoingDetails.this,
"Oops. Timeout error!",
Toast.LENGTH_LONG).show();
loadingPop.dismiss();
}
}
}
);
request.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(request);
}
}
*Note: I am Using Volley Online api and getting this json from another activity using Intent(Bundle) *
Related
I am trying to insert user input in firebase and am using Volley. But nothing being inserted in firebase.Below is the code -
String url = "https://zimber-69c82.firebaseio.com/";
StringRequest stringRequest = new StringRequest(StringRequest.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Firebase firebase = new Firebase("https://zimber-69c82.firebaseio.com/users");
if (response.equals("null")) {
firebase.child(user).child("password").setValue(pass);
Toast.makeText(RegisterActivity.this, "registration successful", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject object = new JSONObject(response);
if (!object.has(user)) {
firebase.child(user).child("password").setValue(pass);
Toast.makeText(RegisterActivity.this, "registration successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(RegisterActivity.this, "username already exists", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
progressDialog.dismiss();
}
}
I'm trying to get a list of tv shows from themovidedb api and I keep getting the error below I am new to android and this is my first time using an api, please let me know if I have to provide more code. Thanks for your help.
Please note I am note trying to populate a recyclerview with this information just yet.
Error
com.android.volley.ParseError: org.json.JSONException: Value {"page":1,"total_results":20000,"total_pages":1000,"results":[{"original_name":"Doom Patrol"....
My code
#Override
protected Void doInBackground(Void... voids) {
popularTvShows = "https://api.themoviedb.org/3/tv/popular?api_key=****my api key goes here****";
popularList = new ArrayList<>();
RequestQueue requestQueue = Volley.newRequestQueue(Objects.requireNonNull(getActivity()));
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
popularTvShows,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Series series = new Series();
series.setId(jsonObject.getInt("id"));
series.setVoteAverage(jsonObject.getInt("vote_average"));
series.setVoteCount(jsonObject.getInt("vote_count"));
series.setOriginalTitle(jsonObject.getString("original_title"));
series.setTitle(jsonObject.getString("title"));
series.setPopularity(jsonObject.getDouble("popularity"));
series.setOverview(jsonObject.getString("overview"));
series.setReleaseDate(jsonObject.getString("release_date"));
series.setPosterPath(jsonObject.getString("poster_path"));
popularList.add(series);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#SuppressLint("ShowToast")
#Override
public void onErrorResponse(VolleyError error) {
Log.e("gggg", error.toString());
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
//This indicates that the reuest has either time out or there is no connection
Toast.makeText(getActivity(),"Check your internet and try again!", Toast.LENGTH_LONG);
} else if (error instanceof AuthFailureError) {
//Error indicating that there was an Authentication Failure while performing the request
Toast.makeText(getActivity(), "Authentication failure!", Toast.LENGTH_LONG);
} else if (error instanceof ServerError) {
//Indicates that the server responded with a error response
Toast.makeText(getActivity(), "Server error! Try again later", Toast.LENGTH_LONG);
} else if (error instanceof NetworkError) {
//Indicates that there was network error while performing the request
Toast.makeText(getActivity(), "Network error", Toast.LENGTH_LONG);
} else if (error instanceof ParseError) {
// Indicates that the server response could not be parsed
Toast.makeText(getActivity(), "Parse Error", Toast.LENGTH_LONG);
}
}
}
);
requestQueue.add(jsonArrayRequest);
return null;
}
your response is coming in JSONObject not in JSONArray as per your Exception:
com.android.volley.ParseError: org.json.JSONException: Value {"page":1,"total_results":20000,"total_pages":1000,"results":[{"original_name":"Doom Patrol"...
Do this :
#Override
protected Void doInBackground(Void... voids) {
popularTvShows = "https://api.themoviedb.org/3/tv/popular?api_key=****my api key goes here****";
popularList = new ArrayList<>();
RequestQueue requestQueue = Volley.newRequestQueue(Objects.requireNonNull(getActivity()));
JSONObjectRequest jsonObjectRequest = new JSONObjectRequest(
Request.Method.GET,
popularTvShows,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject json = new JSONObject(response);
JSONArray results = json.optJSONArray("results");
try {
for (int i = 0; i < results.length(); i++) {
JSONObject jsonObject = results.getJSONObject(i);
Series series = new Series();
.
.
.
popularList.add(series);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#SuppressLint("ShowToast")
#Override
public void onErrorResponse(VolleyError error) {
Log.e("gggg", error.toString());
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
//This indicates that the reuest has either time out or there is no connection
Toast.makeText(getActivity(),"Check your internet and try again!", Toast.LENGTH_LONG);
} else if (error instanceof AuthFailureError) {
//Error indicating that there was an Authentication Failure while performing the request
Toast.makeText(getActivity(), "Authentication failure!", Toast.LENGTH_LONG);
} else if (error instanceof ServerError) {
//Indicates that the server responded with a error response
Toast.makeText(getActivity(), "Server error! Try again later", Toast.LENGTH_LONG);
} else if (error instanceof NetworkError) {
//Indicates that there was network error while performing the request
Toast.makeText(getActivity(), "Network error", Toast.LENGTH_LONG);
} else if (error instanceof ParseError) {
// Indicates that the server response could not be parsed
Toast.makeText(getActivity(), "Parse Error", Toast.LENGTH_LONG);
}
}
}
);
requestQueue.add(jsonObjectRequest);
return null;
}
I am getting wrong response in volley while on the other hand postman getting correct response. Please help me where is the problem . Response i am getting from volley is "response= {"code":1020,"message":"Duplicate key not allowed","returnId":null}"
And in postman it is "{
"code": 1089,"message": "Activation Key sent in email, please activate your user/device","returnId": 438
}"
public void sendRegisterationReq("http://demo.innowi.com/v1/user/register",getJsonObject()) {
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, dataObj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(context, "" + response.toString(), Toast.LENGTH_SHORT).show();
System.out.println("response= " + response.toString());
System.out.println(TAG + ":" + dataObj.toString());
try {
if (response.getString("code").equals("1020")){
Intent intent = new Intent(RegisterDeviceActivity.this,ActivateDeviceActivity.class);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
String message = null;
if (volleyError instanceof NetworkError) {
message = "Network error!";
Log.d(TAG,message);
} else if (volleyError instanceof ServerError) {
message = "Server error!!";
Log.d(TAG,message);
} else if (volleyError instanceof AuthFailureError) {
message = "Auth failure error!";
Log.d(TAG,message);
} else if (volleyError instanceof ParseError) {
message = "Parsing error!";
Log.d(TAG,message);
} else if (volleyError instanceof NoConnectionError) {
message = "No connection error!";
Log.d(TAG,message);
} else if (volleyError instanceof TimeoutError) {
message = "timeout error !";
Log.d(TAG,message);
}
/*Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
System.out.println(TAG + ":Error: " + volleyError.getMessage());
System.out.println(TAG + ":" + volleyError.toString());*/
System.out.println(TAG + ":" + dataObj.toString());
}
}) {
/**
* Passing some request headers
* */
#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;
}
};
jsonObjReq.setShouldCache(false);
jsonObjReq.setTag("myRequest");
// Adding request to request queue
queue.add(jsonObjReq);
}
public JSONObject getJsonObject(){
JSONObject object = new JSONObject();
try {
if (username!=null && password !=null) {
object.put("username", username.getText().toString());
object.put("password", password.getText().toString());
object.put("deviceMacAddress", "90:B6:86:0D:CE:4F");
}
else
{
Toast.makeText(this, "Email/password should not be empty", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
you are the data which is already exist in your database so says duplicate key try different one or try to send all fields valid and different.
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 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();
}
}