com.android.volley.ParseError: org.json.JSONException: - android

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;
}

Related

Retrive String Data of Json

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) *

Getting response code from volley error response

How do we get response code and message of an errenous response from client? Here error.toString() returns: com.android.volley.ServerError error.getMEssage(): null error.getCause(): null parseNetworkResponse: never ever enters that function. When I add getParams() method, it may return ClientError but response code etc still doesnt work!!!!!!! I am trying this for the last 24 hours. No answer on anywhere.
private void getStudentInfo(String number){
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
final String url = organizationRoot+"/identity/detailed/" +number ;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
txtTagContent.setText(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
txtTagContent.setText("ERROR " + error.toString() + error.getMessage() + error.getCause());
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return requestHeaders;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
txtTagContent.setText("WORKED ");
return Response.success( "", HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
}
Could you try:
int statusCode = error.networkResponse.statusCode;
Log.e(TAG, String.valueOf(statusCode);
Maybe you can try this
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String message = null;
if (error instanceof NetworkError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ServerError) {
message = "The server could not be found. Please try again after some time!!";
} else if (error instanceof AuthFailureError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ParseError) {
message = "Parsing error! Please try again after some time!!";
} else if (error instanceof NoConnectionError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof TimeoutError) {
message = "Connection TimeOut! Please check your internet connection.";
}
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
}
}

google/volley App crashing when URL do not exist

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)

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

How to dismiss Progress Dialog when Swipe to refresh is Refreshing in android?

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();
}
}

Categories

Resources