[
{
"id":"20",
"name":"sinha",
"city":"new",
"zone":"",
"area":"delhi",
"mobile":"9716515438",
"address":"9716515438",
"reg_date":"2015-02-28 20:29:10"
},
this is my json.
i am retrieving this in my app, but it shows json mismatch. i know i am doing object and array mismatch.
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:159)
at org.json.JSONObject.<init>(JSONObject.java:172)
this is my log cat.
and this is my code. also please let me know if i am taking the name of anything wrong.
private static final String TAG_CONTACTS = " ";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_CITY = "city";
private static final String TAG_ZONE = "zone";
private static final String TAG_AREA = "area";
private static final String TAG_MOBILE = "mobile";
private static final String TAG_REG_DATE = "reg_date";
JSONArray json_array = null;
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
json_array = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < json_array.length(); i++) {
JSONObject c = json_array.getJSONObject(i);
String name = c.getString(TAG_NAME);
String id = c.getString(TAG_ID);
String city = c.getString(TAG_CITY);
String zone = c.getString(TAG_ZONE);
String area = c.getString(TAG_AREA);
String mobile = c.getString(TAG_MOBILE);
String date = c.getString(TAG_REG_DATE);
The error includes a line indicating where the error happened. You should indicate where the line is on your question.
Also, put the complete JSONArray that is failing, since you are using a JSONArray but your example contains only one JSONObject element, without the brackets opening/closing it.
Maybe that could be your error, since you are trying to put:
{
"id":"20",
"name":"sinha",
"city":"new",
"zone":"",
"area":"delhi",
"mobile":"9716515438",
"address":"9716515438",
"reg_date":"2015-02-28 20:29:10"
},
As a json array and it is a JSONObject
Related
I am parsing json data and i have 2 array. I have successfully parse the 1st json array "item" ,now i have no idea how i can parse 2nd "img".
Here is my code :
{
"item": [
{
"description": "بافت عالی با قاب",
"price": "11000000000000",
"country": "ايران",
"address": "کوچه مهران یک پلاک7",
"region": "البرز",
"city": "کرج",
"mobile": null,
"cat": "حیوانات و مناظر طبیعی",
"img": [
"http://tajerfarsh.com/oc-content/themes/tgsh/images/slider/slider11.jpg",
"http://tajerfarsh.com/oc-content/themes/tgsh//images/categorys/109.jpg",
"http://tajerfarsh.com/oc-content/themes/tgsh//images/categorys/125.jpg"
]
}
]
}
and here is android side code :
public class ParseJSON1 {
public static String[] ids;
public static String[] descriptions;
public static String[] email;
public static String[] country;
public static String[] address;
public static String[] region;
public static String[] city;
public static String[] cat;
public static String[] image;
public static String[] mobiles;
public static final String JSON_ARRAY = "item";
public static final String KEY_ID = "id";
public static final String DESCCRIPTION = "description";
public static final String EMAIL = "emails";
public static final String COUNTRY = "country";
public static final String ADDRESS = "address";
public static final String REGION = "region";
public static final String CITY = "city";
public static final String CATEGORY = "cat";
public static final String IMAGE = "img";
public static final String MOBILE = "mobile";
private JSONArray users = null;
private String json;
public ParseJSON1(String json){
this.json = json;
}
protected void parseJSON1(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
ids = new String[users.length()];
descriptions = new String[users.length()];
country = new String[users.length()];
address = new String[users.length()];
region = new String[users.length()];
city = new String[users.length()];
cat = new String[users.length()];
email = new String[users.length()];
mobiles = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
descriptions[i] = jo.getString(DESCCRIPTION);
email[i] = jo.getString(EMAIL);
country[i] = jo.getString(COUNTRY);
address[i] = jo.getString(ADDRESS);
region[i] = jo.getString(REGION);
city[i] = jo.getString(CITY);
cat[i] = jo.getString(CATEGORY);
// image[i] = jo.getString(IMAGE);
mobiles[i] = jo.getString(MOBILE);
JSONArray img = jsonObject.getJSONArray("img");
image = new String[img.length()];
for (int j=0;j<img.length();j++){
image[i] = jo.getString(IMAGE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
How to resolve it?
Parse it like this:
JSONArray img = jo.getJSONArray("img");
image = new String[img.length()];
for (int j=0;j<img.length();j++){
image[j] = img.getString(j);
}
Moreover, it's better to use a library like GSON for parsing.
Try implement the code below, this use List instead of arrays, it's less likely to have erros (like an Index of Bounds)
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
List<String> ids = new ArrayList<>();
List<String> descriptions = new ArrayList<>();
List<String> country = new ArrayList<>();
List<String> address = new ArrayList<>();
List<String> region = new ArrayList<>();
List<String> city = new ArrayList<>();
List<String> cat = new ArrayList<>();
List<String> email = new ArrayList<>();
List<String> mobiles = new ArrayList<>();
List<String[]> img = new ArrayList<>();
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids.add(jo.getString(KEY_ID));
// Do te rest of the "add"
JSONArray imgs = jo.getJSONArray(IMAGE)
image = new String[imgs.length()];
for (int j=0;j<imgs.length();j++){
image = jo.getString(j);
img .add(image);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_list);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
int itemPosition = position;
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
// String add = ((TextView) view.findViewById(R.id.address))
// .getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
String price =((TextView) view.findViewById(R.id.price)).getText().toString();
String amount=((TextView) view.findViewById(R.id.mobile_labels)).getText().toString();
//String sweet = ((TextView) view.findViewById(R.id.home))
// .getText().toString();
// Starting single contact activity
Intent in = new Intent(SearchActivity.this,
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
//in.putExtra(TAG_PHONE_MOBILE,description);
//in.putExtra(TAG_PHONE_HOME,price);
// in.putExtra(TAG_PHONE_OFFICE,amount);
//in.putExtra(TAG_ADDRESS,add);
//in.putExtra(TAG_PHONE_MOBILE, description);
// in.putExtra(TAG_PHONE_HOME,sweet);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// String add = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// contact.put(TAG_ADDRESS,add);
contact.put(TAG_PHONE_MOBILE, mobile);
contact.put(TAG_PHONE_HOME,home);
contact.put(TAG_PHONE_OFFICE,office);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE ,TAG_PHONE_HOME,TAG_PHONE_OFFICE }, new int[] { R.id.name,
R.id.email, R.id.mobile,R.id.price ,R.id.mobile_labels});
setListAdapter(adapter);
}
}
}
Here is the list. In this I am getting name,email and mobile number. In the list when I select a name in the list open a new activity in that activity I need name, email, phone, address, gender, office. How should I pass this in next activity.
Here is the next activity code.
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
String office= in.getStringExtra(TAG_PHONE_OFFICE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
TextView lblOffice = (TextView) findViewById(R.id.mobile_office);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
lblOffice.setText(office);
}
}
It's better if I have only a name in the listview. On selecting the name in the list further details should be displayed, for instance: name, phone, email, address, gender.
Pass them through the intent you used to start the new activity. When you generate the intent you can bundle some information and pass it as an extra. Then all the information should be in the bundle when your new activity starts. That's probably the easiest way.
There's lots of information in those links, and google has tutorials on how to use intents as well.
Hope that helps!
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_list);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
int itemPosition = position;
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
// String add = ((TextView) view.findViewById(R.id.address))
// .getText().toString();
// String description = ((TextView) view.findViewById(R.id.mobile))
//.getText().toString();
//String sweet = ((TextView) view.findViewById(R.id.home))
// .getText().toString();
// Starting single contact activity
Intent in = new Intent(SearchActivity.this,
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
//in.putExtra(TAG_ADDRESS,add);
//in.putExtra(TAG_PHONE_MOBILE, description);
// in.putExtra(TAG_PHONE_HOME,sweet);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// String add = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// contact.put(TAG_ADDRESS,add);
contact.put(TAG_PHONE_MOBILE, mobile);
contact.put(TAG_PHONE_HOME,home);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SearchActivity.this, contactList,
R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE ,TAG_PHONE_HOME }, new int[] { R.id.name,
R.id.email, R.id.mobile,R.id.home });
setListAdapter(adapter);
}
}
}
I have a list activity in the list it display the name,email,phone number on select an item in the list open a new activity and display the same name, email,number but i need others details in nextactivity including addrees,gender,home, office
In the nextactivity i displaying this items
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
}
}
Inclusignthsi i want to display address,home,office .
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String email = in.getStringExtra(TAG_EMAIL);
String mobile = in.getStringExtra(TAG_PHONE_MOBILE);
String home = in.getStringExtra(TAG_PHONE_HOME);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblEmail = (TextView) findViewById(R.id.email_label);
TextView lblMobile = (TextView) findViewById(R.id.mobile_label);
TextView lblMobiles = (TextView) findViewById(R.id.mobile_labels);
lblName.setText(name);
lblEmail.setText(email);
lblMobile.setText(mobile);
lblMobiles.setText(home);
}
#subhas i have updated th other activity code
I have trouble with a JSON array, and I really hope there is someone who can help me.
Lets say I have a class with JSON data and I'm sending "intent putextra" to another activity.
How can I change the value of null before I send it to another activity? I did a few prints to discover the null values and they are different, example :
Monday : null
Tuesday : 08:30 - 18:00
Wednesday : 09:00 - 17:00
**and so on.**
The problem is that --> I have all json data and I parsing them into objects, but I would like to before "intent.putextra" and send them to another activity finds null and replace them with "Closed"
so it will look like
Monday : Closed
Tuesday : 08:30 - 18:00
Wednesday : 09:00 - 17:00
EDIT
public class LocationBased extends ListActivity{
// JSON Node names
private static final String TAG_Location = "location_id";
private static final String TAG_Company = "company_id";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_PLACE = "place";
private static final String TAG_POSTAL = "postal";
private static final String TAG_CITY = "city";
private static final String TAG_MONDAY = "monday";
private static final String TAG_TUESDAY = "tuesday";
private static final String TAG_WEDNESDAY = "wednesday";
private static final String TAG_THURSDAY = "thursday";
private static final String TAG_FRIDAY = "friday";
private static final String TAG_SATURDAY = "saturday";
private static final String TAG_SUNDAY = "sunday";
private static final String TAG_TYPE = "type";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
private static final String TAG_NOCAR = "nocar";
private static final String TAG = "Debug of Project"; //
private String a;
private String b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db = openOrCreateDatabase("mydb.db", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS gps_kordinater (ID INTEGER PRIMARY KEY AUTOINCREMENT, Latitude REAL, Longitude REAL);");
String query = "SELECT Latitude,Longitude FROM gps_kordinater WHERE Id = (SELECT MAX(Id) FROM gps_kordinater)";
Cursor cursor = db.rawQuery(query, null);
if(cursor != null)
{
cursor.moveToFirst();
a = cursor.getString(0);
b = cursor.getString(1);
}
String url = "http://webservice.XXX.XX/webservice/getLocationList.php?lat="+ a +"&lng="+ b +"";
Log.d(TAG, "Leyth URL = Lat : " + a +" Long : " + b);
// now enabled if disabled = ingen support for jb aka 4.0
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
try {
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
String location_id = c.getString(TAG_Location);
String company_id = c.getString(TAG_Company);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String place = c.getString(TAG_PLACE);
String postal = c.getString(TAG_POSTAL);
String city = c.getString(TAG_CITY);
String monday = c.getString(TAG_MONDAY);
String tuesday = c.getString(TAG_TUESDAY);
String wednesday = c.getString(TAG_WEDNESDAY);
String thursday = c.getString(TAG_THURSDAY);
String friday = c.getString(TAG_FRIDAY);
String saturday = c.getString(TAG_SATURDAY);
String sunday = c.getString(TAG_SUNDAY);
String type = c.getString(TAG_TYPE);
String lat = c.getString(TAG_LAT);
String lng = c.getString(TAG_LNG);
String nocar = c.getString(TAG_NOCAR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_Location, location_id);
map.put(TAG_Company, company_id);
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS, address);
map.put(TAG_PLACE, place);
map.put(TAG_POSTAL, postal);
map.put(TAG_CITY, city);
map.put(TAG_MONDAY, monday);
map.put(TAG_TUESDAY, tuesday);
map.put(TAG_WEDNESDAY, wednesday);
map.put(TAG_THURSDAY, thursday);
map.put(TAG_FRIDAY, friday);
map.put(TAG_SATURDAY, saturday);
map.put(TAG_SUNDAY, sunday);
map.put(TAG_TYPE, type);
map.put(TAG_LAT, lat);
map.put(TAG_LNG, lng);
map.put(TAG_NOCAR, nocar);
// Log.d(TAG, "Leyth Days = Mandag : " + monday +" Onsdag : " + wednesday);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_LAT, TAG_LNG, TAG_POSTAL }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
String mandag = ((TextView) view.findViewById(R.id.mandag)).getText().toString();
String tirsdag = ((TextView) view.findViewById(R.id.tirsdag)).getText().toString();
String onsdag = ((TextView) view.findViewById(R.id.onsdag)).getText().toString();
String torsdag = ((TextView) view.findViewById(R.id.torsdag)).getText().toString();
String fredag = ((TextView) view.findViewById(R.id.fredag)).getText().toString();
String lordag = ((TextView) view.findViewById(R.id.lordag)).getText().toString();
String sondag = ((TextView) view.findViewById(R.id.sondag)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
in.putExtra(TAG_LAT, name);
in.putExtra(TAG_LNG, cost);
in.putExtra(TAG_Company, description);
in.putExtra(TAG_MONDAY, mandag);
in.putExtra(TAG_TUESDAY, tirsdag);
in.putExtra(TAG_WEDNESDAY, onsdag);
in.putExtra(TAG_THURSDAY, torsdag);
in.putExtra(TAG_FRIDAY, fredag);
in.putExtra(TAG_SATURDAY, lordag);
in.putExtra(TAG_SUNDAY, sondag);
startActivity(in);
}
});
}
}
I am also suffering for this problem in past but i do not know this is good solution but it works for me. Hope it is usefull to you also.
String jsonObject_string ;
try {
if (jsonObject != null) {
// ur stuff when not null
}
} catch (Exception e) {
// TODO: handle exception
// when null it automatic fill value
jsonObject_string = "Closed";
}
As I understand you want to replace any null string with a specific string , say "Closed".
This doesn't have anything todo with JSON, if this were my code I would do a simple check before adding those values to my intent. the code will look something like this:
Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
in.putExtra(TAG_LAT, name == null ? "Closed" : name);
in.putExtra(TAG_LAT, cost== null ? "Closed" : cost);
in.putExtra(TAG_Company, description == null ? "Closed" : description );
in.putExtra(TAG_MONDAY, mandag == null ? "Closed" : mandag);
....
And so on.
name == null ? "Closed" : name ;
Simple asks if name is null then the value is closed, else return name.
it is the same as :
if (name == null){
in.putExtra(TAG_LAT, "Closed");
} else {
in.putExtra(TAG_LAT, name);
}
I hope that is what you're looking for
Why not try to replace all null strings in the JSON as a string before you parse the JSON file/object?
Possible other solution could be looping through every object checking if they're null. then replacing that for Closed
EDIT:
Load the JSON object as a string and then replace all null to Closed like this:
String JSON = JsonObject.toString();
JSON.replace("null", "Closed");
EDIT 2:
add this below JSONArray json = jParser.getJSONFromUrl(url);:
String s = json.toString(); // converts json object to string
json.replace("null", "Closed"); // replaces null for Closed
JSONArray json = new JSONArray(s); // converts back to json object
if(c.getString(TAG_MONDAY!=null && c.getString(TAG_MONDAY).length>0 && !(c.getString(TAG_MONDAY).equals("")))
{
String monday=c.getString(TAG_MONDAY);
}
else
{
String monday="Closed";
}
I have the following JSON
[{"name":"Games","id":1,"thumbnail":"https:\/\/lh5.ggpht.com\/_nl17ca8wUp0BbiD9J7mTBSO1o42KpdK2IolG3NjF22o1KbhIZ6ga5e_cXPp42fNUjA=w78","image_medium":"https:\/\/lh5.ggpht.com\/_nl17ca8wUp0BbiD9J7mTBSO1o42KpdK2IolG3NjF22o1KbhIZ6ga5e_cXPp42fNUjA=w78","image_large":"https:\/\/lh5.ggpht.com\/_nl17ca8wUp0BbiD9J7mTBSO1o42KpdK2IolG3NjF22o1KbhIZ6ga5e_cXPp42fNUjA=w78"},{"name":"Sports","id":2,"thumbnail":"https:\/\/lh4.ggpht.com\/yvn4iHEzWN7NmwVkw08ufwSS86mYPpK2Z8WgYkwkQqojMTPsTs28tIiz4v780KGQfrA=w78","image_medium":"https:\/\/lh4.ggpht.com\/yvn4iHEzWN7NmwVkw08ufwSS86mYPpK2Z8WgYkwkQqojMTPsTs28tIiz4v780KGQfrA=w78","image_large":"https:\/\/lh4.ggpht.com\/yvn4iHEzWN7NmwVkw08ufwSS86mYPpK2Z8WgYkwkQqojMTPsTs28tIiz4v780KGQfrA=w78"}]
The following is the code snippet to read the above json
private static final String TAG_CATEGORY_NAME = "name";
private static final String TAG_CATEGORY_ID = "id";
private static final String TAG_CATEGORY_THUMBNAIL = "thumbnail";
private static final String TAG_CATEGORY_IMAGE_MEDIUM = "image_medium";
private static final String TAG_CATEGORY_IMAGE_LARGE = "image_large";
try
{
//Getting Array of Categories
**categories = json.getJSONArray(name);** //Line 1
for(int i=0; i < categories.length(); i++)
{
JSONObject c = categories.getJSONObject(i);
String cname = c.getString(TAG_CATEGORY_NAME);
String cid = c.getString(TAG_CATEGORY_ID);
String cThumbNail = c.getString(TAG_CATEGORY_THUMBNAIL);
String cImageMedium = c.getString(TAG_CATEGORY_IMAGE_MEDIUM);
String cImageLarge = c.getString(TAG_CATEGORY_IMAGE_LARGE);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
As there is no name given to represent each array in the json, Can anyone please tell me the right way to write way to write line 1 in this scenario.