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();
}
}
};
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) {
}
I'm trying to parse this JSON:
{
"data": [{
"name": "Griya Legita",
"is_broken": false,
"is_repaired": false,
"is_ok": true,
"asset_parent": null
},
{
"name": "4th Floor",
"is_broken": true,
"is_repaired": false,
"is_ok": false,
"asset_parent": {
"name": "Buni Building",
"is_broken": true,
"is_repaired": false,
"is_ok": false
}
}]
}
This JSON has a JSON object in a JSON array. But when I call the JSON object it says that it cannot be converted.
This is the code that I've tried:
class daftarAset extends AsyncTask < String, String, String > {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("LOADING...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String...params) {
String link_url = "https://example.com/api/assets";
HttpHandler sh = new HttpHandler();
String json = sh.makeServiceCall(link_url);
Log.e(TAG, "Response from url: " + json);
if (json != null) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject ar = data.getJSONObject(i);
String aset = ar.getString("name");
JSONObject parent = ar.getJSONObject("asset_parent");
String nama = parent.getString("name");
HashMap map = new HashMap();
map.put(in_aset, aset);
map.put(in_ruang, nama);
data_map.add(map);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
list = (ListView) getView().findViewById(R.id.baik_list);
adapter = new AssetsAdapter(getActivity(), data_map);
list.setAdapter(adapter);
setListViewHeightBasedOnChildren(list);
}
});
}
return null;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
}
I don't know what's gone wrong in my code. I'm following this tutorial and I feel like it must be correct but it has an error because the JSON cannot be converted.
This is my error:
W/System.err: org.json.JSONException: Value null at asset_parent of type org.json.JSONObject$1 cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:100)
at org.json.JSONObject.getJSONObject(JSONObject.java:613)
at com.mqa.android.monas.Fragment.BaikFragment$daftarAset.doInBackground(BaikFragment.java:188)
at com.mqa.android.monas.Fragment.BaikFragment$daftarAset.doInBackground(BaikFragment.java:162)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
First make sure JSONObject contains asset_parent key and corresponding key value is not null. Then retrieve value from JSONObject.
Use this code :
JSONObject jsonObject = new JSONObject(json);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject ar = data.getJSONObject(i);
String aset = ar.getString("name");
HashMap map = new HashMap();
map.put(in_aset, aset);
if(ar.has("asset_parent") && !ar.isNull("asset_parent") ){
JSONObject parent = ar.getJSONObject("asset_parent");
String name = parent.getString("name");
map.put(in_ruang, name );
}else{
map.put(in_ruang, null );
}
Log.i("Test", "Map: " + map.toString());
data_map.add(map);
................
.............
}
Hope it will solve your problem.
Let me know if your problem is solved.
Try This
if(mJsonObject.has("Data") && !mJsonObject.isNull("Data") ) {
// code here
}
Make a check whether the object is available or not like below
if(ar.optJSONObject("asset_parent")) {
if(ar.getJSONObject("asset_parent") != null) {
//process the object
}
}
public void get_user_details(){
StringRequest stringRequest = new StringRequest( Request.Method.GET,User_Details_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.e("Response",""+response);
JSONObject obj = new JSONObject(response);
JSONArray user_holder = obj.getJSONArray("User_holder");
JSONObject user = user_holder.getJSONObject(0);
user_id=user.getString("id");
user_name=user.getString("user_name");
user_password=user.getString("user_password");
user_emailid=user.getString("user_email");
PreferenceUtils.saveEmail(user_emailid,Register_Page.this);
PreferenceUtils.saveUsername(user_name,Register_Page.this);
PreferenceUtils.savePassword(user_password,Register_Page.this);
PreferenceUtils.saveUserid(user_id, Register_Page.this);
PreferenceUtils.saveLocalValue(localValue, Register_Page.this);
sharedPreferences.writeLginStastu(true);
if(PreferenceUtils.getEmail(Register_Page.this)!=null || !PreferenceUtils.getEmail(Register_Page.this).equals("")){
startActivity(new Intent(Register_Page.this, CongoCoin.class));
sharedPreferences.writeLginStastu(true);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("User_json",""+e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I am trying to create an android application where I want to receive an array of coordinates from SQL server using web services.
Suppose there is an array containing 30 coordinates(Latitude, Longitude) in SQL server, I want these coordinates to be fetched using web-services and plotting the markers on my map created in my application.
Please Help. Thank You!!
Hi Hope This help to u
class MyTask extends AsyncTask<Void, Void, Void> {
String msg = "";
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
URL url = new URL(
"url");
InputStream isr = url.openStream();
int i = isr.read();
while (i != -1) {
msg = msg + (char) i;
i = isr.read();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
Log.i("========>Message<=====",msg);
try
{
JSONObject mainObject=new JSONObject(msg);
//use this get Toast message of each object Toast.makeText(getActivity(), "hello1 "+mainObject, Toast.LENGTH_LONG).show();
JSONObject maJsonObject = mainObject.getJSONObject("Response");
//Toast.makeText(getActivity(), "hello2 "+maJsonObject, Toast.LENGTH_LONG).show();
JSONArray jsonArray = maJsonObject.getJSONArray("Result");
//Toast.makeText(getActivity(), "hello3 "+jsonArray, Toast.LENGTH_LONG).show();
// Log.i("<======JSONARRAY==>",jsonArray.toString());
for(int i=0;i<jsonArray.length();i++)
{
JSONObject subObject=jsonArray.getJSONObject(i);
String vocherId=subObject.getString("Voucher No");
tv1.setText("Voucher ID: "+vocherId);
String vocherAmount=subObject.getString("Voucher Amount");
tv2.setText(vocherAmount);
String store_name=subObject.getString("Store Name");
tv3.setText(store_name);
String location=subObject.getString("Location");
tv4.setText(location);
String recipient_name=subObject.getString("Recipient Name");
tv5.setText(recipient_name);
String Recipent_mobile=subObject.getString("Recipient Mobile");
tv6.setText(Recipent_mobile);
Toast.makeText(getActivity(), vocherId+"\n"+vocherAmount+"\n"+location+"\n", Toast.LENGTH_LONG).show();
Log.i("==vocherId==", vocherId);
}
/*JSONObject jsonRootObject = new JSONObject(msg);
JSONArray jsonArray = jsonRootObject.optJSONArray("Response");
for(int i=0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String VoucherId = jsonObject.optString("voucherid").toString();
String Amount = jsonObject.optString("amount").toString();
String StoreName = jsonObject.optString("storename").toString();
String Location=jsonObject.optString("location").toString();
String Recipient_Name=jsonObject.optString("recipient_name").toString();
String Recepient_Mobile=jsonObject.optString("recepient_mobile").toString();
msg += "Node"+i+" : \n voucerId= "+ VoucherId +" \n Amount= "+ Amount +" \n StoreName= "+ StoreName +" \n Location="+Location+"\n Recipient_Name"+Recipient_Name+"\n"+Recepient_Mobile;
}
tv1.setText(msg);*/
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
I am using volley library for network calling you can further research how volley is implemented into android
when you hit YOUR_WEB_SERVICE_URL in response it will send JSON array after that parsing it you can place markers
The response should be like
[
{
"id": "1",
"lat": "21.3",
"lon": "23.55",
}, {
"id": "2",
"lat": "21.3",
"lon": "23.55",
}
//...
{
"id": "30",
"lat": "21.3",
"lon": "23.55"
}
]
JsonArrayRequest req = new JsonArrayRequest(YOUR_WEB_SERVICE_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject location = (JSONObject)response.get(i);
String id = location.getString("id");
String lat = location.getString("lat");
String lon = location.getString("lon"); //lat and lon are String you have to typecast it to double before using it
Latlon ll = new Latlon(lat, lon);
placeYourMarkerFuction(ll);
}
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Add Request to queue
}
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'm trying to parse a json array, where a partcular node, under some conditions comes as a array and sometimes as object.
Example:
{
"children":
{
"id":"3",
"subject":"dddd",
"details":"dddd",
"beginDate":"2012-03-08T00:00:00+01:00",
"endDate":"2012-03-18T00:00:00+01:00",
"campus":
{
"id":"2",
"name":"paris"
}
}
}
and sometimes as:
{"children":
[{
"id":"1",
"subject":"android",
"details":"test",
"beginDate":"2012-03-26T00:00:00+02:00",
"endDate":"2012-04-09T00:00:00+02:00",
"campus":{
"id":"1",
"name":"lille"
}
},
{
"id":"2",
"subject":"lozlzozlo",
"details":"xxx",
"beginDate":"2012-03-14T00:00:00+01:00",
"endDate":"2012-03-18T00:00:00+01:00",
"campus":{
"id":"1",
"name":"lille"
}
}]
}
I have tried using this,
if (jobj123 instanceof JSONArray) {
// It's an array
Log.i("It's an array", "It's an array");
} else if (jobj123 instanceof JSONObject) {
// It's an object
Log.i("It's an object", "It's an object");
}
But the 'if' condition always fails and else loop is executed, Can anyone help me solving this issue.
JSONObject children_sub_category_object = children
.getJSONObject(j).optJSONObject("children");
if (children_sub_category_object != null) {
children_sub_jsonobject = children.getJSONObject(j)
.getJSONObject("children");
Log.e("Object", "Object");
} else {
children_sub_category = children.getJSONObject(j)
.getJSONArray("children");
Log.e("Array", "Array");
}
Try that out. That worked for me well. Let me know what happens.
You have to retrieve and check the type of the the "children" object.
Try this:
if (jobj123.has("children") && jobj123.get("children") instanceof JSONObject) {
// it is a JSONObject
JSONObject children = jobj123.getJSONObject("children");
// handle your children ...
}
else if (jobj123.has("children") && jobj123.get("children") instanceof JSONArray) {
// it is an JSONArray
JSONArray childrenArray = jobj123.getJSONArray("children");
// loop children
for (int i = 0; i < childrenArray.length(); i++)
{
if (childrenArray.get(i) instanceof JSONObject) {
JSONObject children = childrenArray.getJSONObject(i);
// handle your children ...
}
}
}
Pass your String into this function which uses nested try catch. it works:
void parse(String s){
JSONObject jsonObject = null;
try{
jsonObject = new JSONObject(s);
JSONArray jArray = jsonObject.getJSONArray("children");
for(int i = 0;i <jArray.length();i++){
Log.i("array type", jArray.getJSONObject(i).getString("id"));
}
}catch(Exception e){
e.printStackTrace();
try{
JSONObject innerObj = jsonObject.getJSONObject("children");
Log.i("object type",innerObj.getString("id"));
}catch(Exception exx){
exx.printStackTrace();
}
}
}