I'm getting the following error:
com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of
This is my code:
public void onResponse(JSONObject response) {
dialog.dismiss();
Log.d("response", response.toString());
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONArray("assignments");
if(jsonArray.length()==0)
{
Toast.makeText(getApplicationContext(), "Assignments Not Found", Toast.LENGTH_LONG).show();
}
CardView cardView=(CardView)findViewById(R.id.list_item5);
cardView.setVisibility(View.VISIBLE);
assignmentModuleListList.clear();
for (int i = 0; i < jsonArray.length(); i++) {
AssignmentModule assignmentModule = new AssignmentModule();
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
assignmentModule.setAssignmentName(jsonObject1.getString("assignmentName"));
assignmentModule.setDescription(jsonObject1.getString("description"));
assignmentModule.setSubjectName(jsonObject1.getString("subjectName"));
String date=jsonObject1.getString("startDate").substring(0,10);
String date1=jsonObject1.getString("endDate").substring(0, 10);
assignmentModule.setAssignDate(date+"\n"+"\t\t\t"+"to"+"\n"+date1);
assignmentModuleListList.add(assignmentModule);
}
setdata(assignmentModuleListList);
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Log.d("error",error.toString());
String timeout=error.toString();
if(timeout.equalsIgnoreCase("com.android.volley.TimeoutError"))
{
Toast.makeText(getApplicationContext(), "Opp's Server Can't Load Please Try Again Latter", Toast.LENGTH_LONG).show();
}
NetworkResponse response = error.networkResponse;
if(response != null && response.data != null){
switch(response.statusCode){
case 400:
Toast.makeText(getApplicationContext(), "400 Error", Toast.LENGTH_LONG).show();
break;
case 404:
Toast.makeText(getApplicationContext(), "Assignments Not Found", Toast.LENGTH_LONG).show();
break;
case 500:
Toast toast1 = Toast.makeText(getApplicationContext(), "Internal Server Error", Toast.LENGTH_SHORT);
TextView v1 = (TextView) toast1.getView().findViewById(android.R.id.message);
v1.setTextColor(Color.RED);
toast1.show();
break;
}
//Additional cases
}
}
This is what I'm expecting after parsing:
{
"assignments":[
{
"assignmentName":"asignment1",
"description":"first poam",
"subjectName":"kannada",
"startDate":"2016-01-22",
"endDate":"2016-01-23"
},
{
"assignmentName":"assigment3",
"description":"thrid lesson",
"subjectName":"kannada",
"startDate":"2016-01-22",
"endDate":"2016-01-23"
}
]
}
Related
I am using Volley in my project for handling network requests. Here is a sample JSON my server returns when it has data then fatch otherwise give error
{
"message_status": true,
"data": [
{
"message_id": "88",
"message_text": "hi,",
"message_link": "0",
},
}
{
"message_status": false,
"message": "Message not available!"
}
this is my code
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_msg,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("data") && !jsonObject.isNull("data")) {
String success = jsonObject.getString("message_status");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success.equals("true")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
ChatMessage chatMessage = new ChatMessage();
chatMessage.setMessageUser(object.getString("username"));
chatMessage.setMessageTime(object.getString("time"));
chatMessage.setMessageText(object.getString("message_text"));
chatMessage.setUserId(object.getString("user_id"));
chatMessage.setFileName(object.getString("file_name"));
chatMessage.setMessageFile(object.getString("message_link"));
chatMessage.setMessageID(object.getString("message_id"));
chatMessages.add(chatMessage);
}
setupListview();
} else {
// get message using error key
String error = "Response : " + success + " = " + message;
Toast.makeText(ChatActivity.this, error, Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(ChatActivity.this, "data not available", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(ChatActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
when data have no value then show no item message but its give server error
Try this:
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("message_status");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (jsonArray != null || jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
ChatMessage chatMessage = new ChatMessage();
chatMessage.setMessageUser(object.getString("username"));
chatMessage.setMessageTime(object.getString("time"));
chatMessage.setMessageText(object.getString("message_text"));
chatMessage.setUserId(object.getString("user_id"));
chatMessage.setFileName(object.getString("file_name"));
chatMessage.setMessageFile(object.getString("message_link"));
chatMessage.setMessageID(object.getString("message_id"));
chatMessages.add(chatMessage);
//loading.setVisibility(View.GONE);
}
setupListview();
} else {
// get message using error key
Toast.makeText(ChatActivity.this, "error 1" + message + success, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
If I have a JSON like below:
{
"Division": [
{
"DivisionId": 1,
"DivisionName" : "A"
},
{
"DivisionId": 2,
"DivisionName" : "B"
}
],
"Title": [
{
"TitleId": 11,
"Title": "Title 1"
},
{
"TitleId": 12,
"Title": "Title 2"
}
]
}
How can I get the Division only with its values inside? What I'm trying to achieve is to put the values of Division inside my ArrayList. I'm using Volley to get the JSON result and what I tried is on the onResponse I used JSONArray divisionArr = response.getJSONArray("Division"); and loop it here's my code
JSONArray divisionArr = response.getJSONArray("Division");
for (int i = 0; i < divisionArr.length(); i++) {
Division division = new Division();
JSONObject divisionObj = (JSONObject) divisionArr.get(i);
division.setId(divisionObj.getInt("DivisionId"));
division.setName(divisionObj.getString("DivisionName"));
divisionArrayList.add(division);
}
But I'm having an error ParseError, I maybe doing it wrong, but I don't know what is it. Please help, thank you.
///////
Here's my Volley request
public void getData(Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
try{
String syncCall = Constants.VOLLEY;
request = new JsonObjectRequest(Method.GET,
syncCall,
null,
listener,
errorListener);
request.setRetryPolicy(
new DefaultRetryPolicy(
60000,//DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, // 2500
1,//DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 1
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); //1f
mRequestQueue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
Then in my Activity
private void callSyncVolley() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage("Fetching data....");
pd.show();
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray divisionArr = response.getJSONArray("Division");
for (int i = 0; i < divisionArr.length(); i++) {
Division division = new Division();
JSONObject divisionObj = (JSONObject) divisionArr.get(i);
division.setId(divisionObj.getInt("DivisionId"));
division.setName(divisionObj.getString("DivisionName"));
divisionArrayList.add(division);
}
pd.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "Error: " + e.getMessage());
pd.dismiss();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null) {
Log.d(TAG, "Error Response code: " + error.networkResponse.statusCode);
pd.dismiss();
}
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Log.d(TAG, "Error Response code: Timeout/NoConnection");
pd.dismiss();
} else if (error instanceof AuthFailureError) {
//TODO
Log.d(TAG, "Error Response code: AuthFailureError");
pd.dismiss();
} else if (error instanceof ServerError) {
//TODO
Log.d(TAG, "Error Response code: ServerError");
pd.dismiss();
} else if (error instanceof NetworkError) {
//TODO
Log.d(TAG, "Error Response code: NetworkError");
pd.dismiss();
} else if (error instanceof ParseError) {
//TODO
Log.d(TAG, "Error Response code: ParseError");
pd.dismiss();
}
}
};
VolleyRequestManager.getInstance().doRequest().getData(listener, errorListener);
}
The error only shows Error Response code: ParseError
Your JSON format is invalid,
{
"Division": [
{
"DivisionId": 1,
"DivisionName" : A
},
{
"DivisionId": 2,
"DivisionName" : B
}
],
"Title": [
{
"TitleId": 11,
"Title": "Title 1"
},
{
"TitleId": 12,
"Title": "Title 2"
}
],
}
I just pasted your format here
divisionArr.setName(divisionObj.getString("DivisionName")); &&
You are trying to access a String which is not wrapped in double quotes,the String A and String B is not wrapped in double quotes.
Unnecessary comma at the end of the array ],
You can try like this, If you try to get using opt it will get value or null, so you can check that produced further
get and opt type
Use getType() to retrieve a mandatory value. This fails with a JSONException if the requested name has no value or if the value
cannot be coerced to the requested type.
Use optType() to retrieve an optional value. This returns a system- or user-supplied default if the requested name has no value or if the
value cannot be coerced to the requested type.
Example:
getJSONArray - Returns the value mapped by name if it exists and is a JSONArray, or throws otherwise., so we can't handle the upcoming line of code it will go to try block,
But optJSONArray - Returns the value mapped by name if it exists and is a JSONArray, or null otherwise., so using that null value we can handle the code easily
try {
JSONArray divisionArr = response.optJSONArray("Division");
if(divisionArr != null) {
for (int i = 0; i < divisionArr.length(); i++) {
Division divisoin = new Division();
JSONObject divisionObj =divisionArr.optJSONObject(i);
if(divisionObj == null) {
continue;
}
divisionArr.setId(divisionObj.optInt("DivisionId"));
divisionArr.setName(divisionObj.optString("DivisionName"));
divisionArrayList.add(applicationType);
}
}
pd.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "Error: " + e.getMessage());
pd.dismiss();
}
Instead of Volley use Retrofit coz it'll provide you each JSON Element seperately. And to know how to use Retrofit check this tutorial.
I finally got it right, I recode the whole thing, checked my json result and here's my code
Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray divisionArr = response.getJSONArray("Division");
if(!divisionArr.equals(null)){
for(int i = 0; i < divisionArr.length(); i++){
Division division = new Division();
JSONObject divisionObj = (JSONObject) divisionArr.get(i);
division.setId(divisionObj.getInt("DivisionId"));
division.setName(divisionObj.getString("DivisionName"));
divisionList.add(division);
}
}
pd.dismiss();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getMessage(), Toast.LENGTH_SHORT).show();
pd.dismiss();
}
}
};
I have an app which contain MainActivityand that activity contains a fragment which send server request and during that i am showing a ProgressDialog. But while progress dialog is displaying, if i move from MainActivity to another activity it was giving me error "Fragment not attached to activity".
How can i resolve this issue?
code:-
/*This method send request to server for more deals*/
private void loadmoreData() {
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
try {
String json;
// 3. build jsonObject
final JSONObject jsonObject = new JSONObject();// making object of Jsons.
jsonObject.put(ServerRequestKeyStorage.s_szAGENT_CODE, m_szMobileNumber);// put mobile number
jsonObject.put(ServerRequestKeyStorage.s_szPASSWORD, m_szEncryptedPassword);// put password
jsonObject.put(ServerRequestKeyStorage.s_szRECORD_COUNT, sz_RecordCount);// put record count
jsonObject.put(ServerRequestKeyStorage.s_szLAST_COUNT, sz_LastCount);// put last count
Log.d("CAppList:", sz_RecordCount);
Log.d("Capplist:", sz_LastCount);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();// convert Json object to string
Log.i(TAG, "Server Request:-" + json);
m_Dialog = DialogUtils.showProgressDialog(getActivity(), getString(R.string.loading_more_deals));
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
final String imgPath = APIStorage.IREWARDS_URL + APIStorage.s_szImagePath;
final String m_DealListingURL = APIStorage.IREWARDS_URL + APIStorage.s_szDEALLISTING_URL;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Server Response:-" + response);
Activity activity = getActivity();
if (activity!=null&&isAdded()){
m_Dialog.dismiss();
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString(ServerResponseStorage.s_szRESULT_CODE));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
// Select the last row so it will scroll into view...
JSONArray posts = response.optJSONArray(ServerResponseStorage.s_szDEAL_ARRAY);// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
try {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString(ServerResponseStorage.s_szDEAL_NAME));//getting deal name
item.setM_szsubHeaderText(post.getString(ServerResponseStorage.s_szDEAL_CODE));// getting deal code
item.setM_szDealValue(post.getString(ServerResponseStorage.s_szDEAL_VAlUE));
item.setM_szDetails(post.getString(ServerResponseStorage.s_szDEAL_DETAILS));
String logo = post.getString(ServerResponseStorage.s_szDEAL_LOGO);
item.setM_szLogoPath(imgPath + logo);
Log.e(TAG, "Logo Path::" + item.getM_szLogoPath());
if (!s_oDataset.contains(item)) {
s_oDataset.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
}
m_oAdapter.notifyDataSetChanged();
arrayCount = posts.length();// finding length of deals coming in response from server.
// read stored value from shared preference
int n_oLastCountLength = m_oPreferenceHelper.getIntPreference(LAST_COUNT_LENGTH);
int accumulateLastCount = n_oLastCountLength + arrayCount;
/*Here we are saving deal length in shared preference*/
// save incremental length
m_oPreferenceHelper.saveIntegerValue(LAST_COUNT_LENGTH, accumulateLastCount);
// m_ListView.removeFooterView(mFooter);
m_ListView.setSelection(m_oAdapter.getCount() - posts.length());
}
if (nResultCodeFromServer == CStaticVar.m_kCONNECTION_LOST) {//server based conditions
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.connection_not_available), getActivity());
// m_ListView.removeFooterView(mFooter);
} else if (nResultCodeFromServer == CStaticVar.m_kDEAL_NOT_FOUND) {// serevr based conditions .....
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.no_more_deals), getActivity());
// //*Counting loading footer*/
// if (m_ListView.getFooterViewsCount() != 0) {
// m_ListView.removeFooterView(mFooter);
// }
} else if (nResultCodeFromServer == CStaticVar.m_kTECHNICAL_FAILURE) {
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.technical_failure), getActivity());
} else if (nResultCodeFromServer == CStaticVar.m_kALREADY_AVAIL_BENEFIT) {
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.already_avail_deals), getActivity());
} else if (nResultCodeFromServer == CStaticVar.m_kTIMED_OUT) {
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.times_out), getActivity());
// m_ListView.removeFooterView(mFooter);
} else if (nResultCodeFromServer == CStaticVar.m_kERROR_IN_DB) {
CSnackBar.showSnackBarError(m_MainLayout, "Something happened wrong in DB. Please contact support#starxsoft.com", getActivity());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error::" + error);
Activity activity = getActivity();
if (activity!=null&&isAdded()){
m_Dialog.dismiss();
}
if (error instanceof TimeoutError) {
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.connection_timed_out), getActivity());
} else if (error instanceof NetworkError) {
CSnackBar.showSnackBarError(m_MainLayout, getString(R.string.no_internet_warning), getActivity());
}
}
});
requestQueue.add(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
In this during dismiss and showing a dialog it gives me error.
I need to show a loading screen for volley, I am sending few json to the servers using volley, i written the code inside for loop for fetching a json and sending the json. But the for loop is not waiting for the responce to continue. It just completing quickly, How can i use for loop for sending jason and show the for loops value as the count of syncing.?
Code...
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
Log.d("length", String.valueOf(result.length()));
if(result.length()!=0) {
for (int e = 0; e < result.length(); e++) {
this.dialog.setMessage("Syncing "+(e+1)+" of "+result.length());
this.dialog.show();
try {
final JSONObject js = result.getJSONObject(e);
Log.d("sdfhd", js.toString());
final JSONArray ja = new JSONArray();
ja.put(js);
Log.d("sending json", ja.toString());
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST,
server_url, ja,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("asd", ja.toString());
Log.d("JsonArray", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject store = response.getJSONObject(i);
mydb.updateweb(store.getInt("_id"), store.getString("webid"), store.getString("regid"));
if (i == response.length() - 1) {
Toast.makeText(MainActivity.this, "Synced Successfully", Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
JSONObject stor = response.getJSONObject(0);
Toast.makeText(MainActivity.this, stor.getString("result"),
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
// dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Json sdfsdfsf", js.toString());
Log.d("afs", error.toString());
Toast.makeText(MainActivity.this, "error",
Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(request);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
else{
Toast.makeText(MainActivity.this, "Updated Succesfully",
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
// dialog.dismiss();
}
Look at the code I have changed your logic about the dialog, also I have added success and failure counts functionality so that you can have an idea of request statuses
Global Variables:
int successCount = 0;
int failedCount = 0;
Revised onPostExecute():
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
successCount = 0;
failedCount = 0;
this.dialog.setMessage("Syncing 0 of "+result.length());
this.dialog.show();
Log.d("length", String.valueOf(result.length()));
if(result.length()!=0) {
for (int e = 0; e < result.length(); e++) {
this.dialog.setMessage("Syncing " + (e+1) + " of "+result.length());
try {
final JSONObject js = result.getJSONObject(e);
Log.d("sdfhd", js.toString());
final JSONArray ja = new JSONArray();
ja.put(js);
Log.d("sending json", ja.toString());
JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST,
server_url, ja,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
boolean isCodeExecutedSuccessfully = false;
Log.d("asd", ja.toString());
Log.d("JsonArray", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject store = response.getJSONObject(i);
mydb.updateweb(store.getInt("_id"), store.getString("webid"), store.getString("regid"));
if (i == response.length() - 1) {
Toast.makeText(MainActivity.this, "Synced Successfully", Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
isCodeExecutedSuccessfully = true;
} catch (JSONException e) {
isCodeExecutedSuccessfully = false;
e.printStackTrace();
}
}
try {
JSONObject stor = response.getJSONObject(0);
Toast.makeText(MainActivity.this, stor.getString("result"),
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
// dialog.dismiss();
isCodeExecutedSuccessfully = true;
} catch (JSONException e) {
isCodeExecutedSuccessfully = false;
e.printStackTrace();
}
//////////////////////////////// DIALOG WORK ON SUCCESS ///////////////////////////////
if(isCodeExecutedSuccessfully)
++successCount;
else
++failedCount;
if((e+1) == result.length()) {
dialog.dismiss();
}
this.dialog.setMessage("Syncing " + (e+1) + " of "+result.length());
Log.d("::onResponse(): Status Counts", "Success=" + successCount + ", fail=" + failedCount);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//////////////////////////////// DIALOG WORK ON ERROR RESPONSE ///////////////////////////////
++failedCount;
if((e+1) == result.length()) {
dialog.dismiss();
}
Log.d("::onErrorResponse(): Status Counts", "Success=" + successCount + ", fail=" + failedCount);
this.dialog.setMessage("Syncing " + (e+1) + " of "+result.length());
Log.d("Json sdfsdfsf", js.toString());
Log.d("afs", error.toString());
Toast.makeText(MainActivity.this, "error",
Toast.LENGTH_SHORT).show();
//dialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(request);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
else{
Toast.makeText(MainActivity.this, "Updated Succesfully",
Toast.LENGTH_SHORT).show();
mydb.updatesync();
mydb.deletet2();
dialog.dismiss();
}
// dialog.dismiss();
}
i am fetching Bunch of data from server to Local Database ,after Login.
its getting some times Alert App is not Responding Wait or Close.
Please help me any other Possible way or try to fix this issue.
Async call:
Asynctask_GetServerData task=new Asynctask_GetServerData ();
task.execute();
Asynctask Class:
public class Asynctask_GetServerData extends AsyncTask<String,Void,Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
if (!pDialog.isShowing())
{
pDialog.setIndeterminate(true);
pDialog.setCanceledOnTouchOutside(false);
pDialog.setMessage("Please Wait Getting Data...");
pDialog.show();
}
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
}
#Override
protected Void doInBackground(String... params)
{
getLoginDataCall();
return null;
}
}
private void getLoginDataCall() {
sisClient.getApi().getAllData(
new Callback<CommonResponse>() {
#Override
public void success(CommonResponse commonResponse, Response response) {
Timber.d("sendOtpAPICall%s", commonResponse.getStatusCode());
switch (commonResponse.getStatusCode()) {
case 200:
try {
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(commonResponse.getRouteMaster());
if (!commonResponse.getRouteMaster().equals("[]"))
{
for (int i = 0; i < jsonarray.length(); i++)
{
JSONObject jsonobject = jsonarray.getJSONObject(i);
RouteId_StringValue = jsonobject.getString("RouteId");
Asynxfor_Route_Master_insert(RouteId_StringValue);
}
} else {
System.out.println("ROute Master Is NULL ::" + commonResponse.getStatusMessage() + "\n");
}
} catch (Exception e) {
e.printStackTrace();
;
}
break;
case 404:
pDialog.dismiss();
Toast.makeText(LoginPage.this, R.string.wrong_Username_or_password, Toast.LENGTH_LONG).show();
break;
case 500:
pDialog.dismiss();
Toast.makeText(LoginPage.this, R.string.something_wrong, Toast.LENGTH_LONG).show();
break;
}
}
#Override
public void failure(RetrofitError error) {
try {
if (error != null) {
pDialog.dismiss();
Timber.i("sendOtpAPICall error %s", error.getResponse().getStatus());
String json = new String(((TypedByteArray) error.getResponse().getBody()).getBytes());
Timber.i("failure error %s", json.toString());
JSONObject json1 = new JSONObject(json.toString());
String json1string = json1.getString("StatusMessage");
switch (error.getResponse().getStatus()) {
case 404:
Toast.makeText(getApplicationContext(), R.string.wrong_Username_or_password, Toast.LENGTH_LONG).show();
break;
case 500:
Toast.makeText(LoginPage.this, R.string.something_wrong, Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(LoginPage.this, json1string, Toast.LENGTH_LONG).show();
break;
}
} else {
Timber.i("failure error %s", "Recieving error null rom server");
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(LoginPage.this, R.string.something_wrong, Toast.LENGTH_LONG).show();
}
}
});
}