I am new to using json . fetching data from mysql in json format display on listview android . Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url= "http://127.0.0.1/bloodRequest/data.php";
// JSON Node names
private static final String TAG_CONTACTS = "requests ";
private static final String TAG_NAME = "User_name";
private static final String TAG_BLOCKNO = "user_block_no";
private static final String TAG_ADDRESS = "user_stree_address";
private static final String TAG_CITY = "user_city_village";
private static final String TAG_TALUKA = "user_taluka";
private static final String TAG_DISTRICT = "user_district";
private static final String TAG_BLOOD_TYPE = "blood_type";
private static final String TAG_CREATE_DATE = "createdate";
private static final String TAG_PHONE = "user_mobile";
// contacts JSONArray
JSONArray requests= null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView list = getListView();
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(MainActivity.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.POST);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
requests = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < requests.length(); i++) {
JSONObject c = requests.getJSONObject(i);
String name = c.getString(TAG_NAME);
String blockno = c.getString(TAG_BLOCKNO);
String address = c.getString(TAG_ADDRESS);
String city = c.getString(TAG_CITY);
String district=c.getString(TAG_DISTRICT);
String taluk=c.getString(TAG_TALUKA);
String blodtype=c.getString(TAG_BLOOD_TYPE);
String phone=c.getString(TAG_PHONE);
String createdate=c.getString(TAG_CREATE_DATE);
// tmp hashmap for single contact
HashMap<String, String> requests1 = new HashMap<String, String>();
// adding each child node to HashMap key => value
requests1 .put(TAG_NAME, name);
requests1 .put(TAG_BLOCKNO, blockno);
requests1 .put(TAG_ADDRESS, address);
requests1 .put(TAG_CITY, city);
requests1 .put(TAG_TALUKA, taluk);
requests1 .put(TAG_DISTRICT, district);
requests1 .put(TAG_BLOOD_TYPE, blodtype);
requests1 .put(TAG_PHONE, phone);
requests1 .put(TAG_CREATE_DATE, createdate);
// adding contact to contact list
contactList.add( requests1 );
}
} 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(
MainActivity.this, contactList,
R.layout.item_list,
new String[] { TAG_NAME, TAG_BLOCKNO,TAG_ADDRESS,TAG_CITY,TAG_TALUKA,TAG_DISTRICT,TAG_BLOOD_TYPE,TAG_PHONE,TAG_CREATE_DATE},
new int[] { R.id.name, R.id.blono, R.id.street,R.id.city,R.id.taluk,R.id.distr,R.id.btype,R.id.phno,R.id.crdate });
setListAdapter(adapter);
}
}
}
Add to your activity_main ListView with android:id="#android:id/list"
If you use ListActivity in your activity layout you should add:
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
When you extends ListActivity you should use
ListView list = getListView(); // OR you can do
ListView list = (ListView)findViewById(android.R.id.list); //consider the android prefix
And Set Listview Id android:id="#android:id/list"
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
ListView whose id attribute is 'android.R.id.list' Error when I have the ListView id set correctly
Your content must have a ListView whose id attribute is 'android.R.id.list'
i used a list view in my app.i used scroll bar for update the details. i got complete updated list again.which added all the data in ny list. i wants to avoid it so plz suggest me how i retrict the duplicate values in list after updation.... my code snippet is here.....
public class MainActivity extends ListActivity implements SwipeRefreshLayout.OnRefreshListener {
private ProgressDialog pDialog;
ListView mListView;
SwipeRefreshLayout swipeLayout;
Adapter mAdapter;
// URL to get contacts JSON
private static String url = "http://api.androidhive.info/contacts/";
// 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.activity_main);
// SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
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
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();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
ak.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
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(MainActivity.this);
// pDialog.setMessage("Please wait...");
// pDialog.setCancelable(false);
//Dialog.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 address = 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_PHONE_MOBILE, mobile);
// 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(
MainActivity.this, contactList,
R.layout.list_item, new String[]{TAG_NAME, TAG_EMAIL,
TAG_PHONE_MOBILE}, new int[]{R.id.name,
R.id.email, R.id.mobile});
setListAdapter(adapter);
}
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new GetContacts().execute();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
The only thing you have to do is set adapter like this way and it won't replicate data. It just add new data below older one.
adapter = null;
if (adapter == null) {
adapter = new CustomAdapter(this, arrayList);
listvie.setAdapter(adapter);
}
adapter.notifyDataSetChanged();
Hope it will work.
Thanks. :)
Solution is very simple.
Create ListAdapter before executing AsyncTask with empty Collection
Set adapter for ListView with created adapter
In AsyncTask create local field ArrayList<HashMap<String, String>> localList
Parsed contacts put to localList, not to contactList
After download items, clear Collection by calling contactList.clear();
Add download contacts contactList.addAll(localList);
Call adapter.notifyDataSetChanged();
I am new to Android. I am using Fedor's Lazy Loading List. Is it possible to get all the values from a HashMap (values were retrieved from mysql) and store it to private String[] drinkImages?
String[] drinkImages' values will be passed to adapter Lazy_Adapter.
Or is there any other way to pass the value to Lazy_Adapter?
Code:
Lazy_ListItem.java
public class Lazy_ListItem extends Activity {
ListView list;
Lazy_Adapter adapter;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all products list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_RID = "rid";
private static final String TAG_DRK_ID = "drk_id";
private static final String TAG_DRK_NAME = "drk_name";
private static final String TAG_DRK_DESC = "drk_desc";
private static final String TAG_DRK_PRICE = "drk_price";
private static final String TAG_DRK_AVAIL = "drk_avail";
private static final String TAG_DRK_IMAGE = "drk_image";
// products JSONArray
JSONArray drinks = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
list = (ListView) findViewById(R.id.list);
adapter = new Lazy_Adapter(this, drinkImages);
list.setAdapter(adapter);
// Button b = (Button) findViewById(R.id.button1);
// b.setOnClickListener(listener);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
/*
* public OnClickListener listener = new OnClickListener() {
*
* #Override public void onClick(View arg0) {
* adapter.imageLoader.clearCache(); adapter.notifyDataSetChanged(); } };
*/
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
/*
* #Override protected void onPreExecute() { super.onPreExecute();
*
* pDialog = new ProgressDialog(Lazy_Adapter.this, Lazy_ListItem.class);
* pDialog.setMessage("Loading drinks. Please wait...");
* pDialog.setIndeterminate(false); pDialog.setCancelable(false);
* pDialog.show();
*
* //final ProgressDialog dialog; // dialog =
* ProgressDialog.show(getActivity, "Title", "Message", true); }
*/
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Products
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
String drk_image = c.getString(TAG_DRK_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_IMAGE, drk_image);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
}
private String[] drinkImages = {
"http://webitprojects.com/restaurant/images/drinks/drk_coffee.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_calamansijuice.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_blackgulaman.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_avocadoshake.jpg",
"http://webitprojects.com/restaurant/images/drinks/drk_durianshake.jpg" }; }
Lazy_Adapter.java
public class Lazy_Adapter extends BaseAdapter {
String drk_name, drk_desc, drk_price, drk_avail;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> drinksList;
// url to get all products list
private static String url_all_drinks = "http://10.0.2.2/restosnapp/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DRINKS = "drinks";
private static final String TAG_RID = "rid";
private static final String TAG_DRK_ID = "drk_id";
private static final String TAG_DRK_NAME = "drk_name";
private static final String TAG_DRK_DESC = "drk_desc";
private static final String TAG_DRK_PRICE = "drk_price";
private static final String TAG_DRK_AVAIL = "drk_avail";
private static final String TAG_DRK_IMAGE = "drk_image";
// products JSONArray
JSONArray drinks = null;
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public Lazy_ImageLoader imageLoader;
public Lazy_Adapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new Lazy_ImageLoader(activity.getApplicationContext());
// Hashmap for ListView
drinksList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ///
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_drinks, "GET",
params);
// Check your log cat for JSON response
Log.d("All Drinks: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
drinks = json.getJSONArray(TAG_DRINKS);
// looping through All Products
for (int i = 0; i < drinks.length(); i++) {
JSONObject c = drinks.getJSONObject(i);
// Storing each json item in variable
drk_name = c.getString(TAG_DRK_NAME);
drk_desc = c.getString(TAG_DRK_DESC);
drk_price = c.getString(TAG_DRK_PRICE);
drk_avail = c.getString(TAG_DRK_AVAIL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DRK_NAME, drk_name);
map.put(TAG_DRK_DESC, drk_desc);
map.put(TAG_DRK_PRICE, drk_price);
map.put(TAG_DRK_AVAIL, drk_avail);
// adding HashList to ArrayList
drinksList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
#SuppressWarnings("unused")
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item, null);
for (Map<String, String> menuItem : drinksList) {
ImageView image = (ImageView) vi.findViewById(R.id.image);
imageLoader.DisplayImage(data[position], image);
TextView tvMenuName = (TextView) vi.findViewById(R.id.tvMenuName);
tvMenuName.setText(drinksList.get(position).get(TAG_DRK_NAME));
TextView tvMenuDesc = (TextView) vi.findViewById(R.id.tvMenuDesc);
tvMenuDesc.setText(drinksList.get(position).get(TAG_DRK_DESC));
TextView tvMenuPrice = (TextView) vi.findViewById(R.id.tvMenuPrice);
tvMenuPrice.setText("P"
+ drinksList.get(position).get(TAG_DRK_PRICE));
TextView tvMenuAvail = (TextView) vi.findViewById(R.id.tvMenuAvail);
tvMenuAvail.setText(drinksList.get(position).get(TAG_DRK_AVAIL));
}
return vi;
}}
I hope you can help me. Thank you.
You can access perticular string on loacation with this code. Here i is an index number which may be 0,1,2 etc.
String yourstring = drinksList.get(i).get(TAG_DRK_IMAGE)
String[] drinkImages = (String[]) drinkList.get(0).values().toArray();
Yes, something like this will work .
public static void main(String[] args) {
Map<String, String> hm = new HashMap<String, String>(); // and yes. I am still using java 6 :(
hm.put("a", "a.jpg");
hm.put("b", "b.jpg");
String[] arr = new String[hm.size()];
hm.values().toArray(arr);
for (String s : arr) {
System.out.println(s);
}
}
O/P:
b.jpg
a.jpg
Try to iterate HashMap and build Array from HashMap value :
public String[] getStringArrayFromMap(HashMap<String,String> map){
String[] array = new String[map.size()];
int i=0;
for (String key : map.keySet()) {
array[i++] = map.get(key);
}
return array;
}
I'm developing an app which reads JSON data. Json Data is parsed but it is not viewing in the listview. Logcat says about a type mismatch. I'm not that much familiar in Json.
http://api.openweathermap.org/data/2.5/forecast/daily?lat=6.421465&lon=81.332396&cnt=10&mode=json
This is my logcat and code. Please hemp me with this.
org.json.JSONException: Index 1 out of range [0..1)
org.json.JSONArray.get(JSONArray.java:263)
org.json.JSONArray.getString(JSONArray.java:421)
com.is.parsej.ParseJ$GetContacts.doInBackground(ParseJ.java:141)
com.is.parsej.ParseJ$GetContacts.doInBackground(ParseJ.java:1)
android.os.AsyncTask$2.call(AsyncTask.java:287)
java.util.concurrent.FutureTask.run(FutureTask.java:234)
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
public class ParseJ extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=6.421465&lon=81.332396&cnt=10&mode=json";
// JSON Node names
private static final String TAG_COd = "list"; //edited
private static final String TAG_ID = "dt"; //edited
private static final String TAG_WEATHER = "weather";
private static final String TAG_MAIN = "main";
private static final String TAG_DESC = "description";
private static final String TAG_TEMP = "temp";
private static final String TAG_DAY = "day";
private static final String TAG_MIN = "min";
private static final String TAG_MAX = "max";
private static final String TAG_NIGHT = "night";
private static final String TAG_MORN= "morn";
private static final String TAG_HUMIDITY = "humidity";
// 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.activity_parse_j);
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
String weather = ((TextView) view.findViewById(R.id.main))
.getText().toString();
String Temp = ((TextView) view.findViewById(R.id.Descrption))
.getText().toString();
String Humidity = ((TextView) view.findViewById(R.id.temp))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_WEATHER, weather);
in.putExtra(TAG_TEMP, Temp);
in.putExtra(TAG_HUMIDITY, Humidity);
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(ParseJ.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_COd);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String humidity = c.getString(TAG_HUMIDITY);
// Phone node is JSON Object
JSONObject temp = c.getJSONObject(TAG_TEMP);
String day = temp.getString(TAG_DAY);
String maxTemp = temp.getString(TAG_MAX);
String minTemp = temp.getString(TAG_MIN);
String morningTemp = temp.getString(TAG_MORN);
//edited
JSONArray weather = c.getJSONArray(TAG_WEATHER);
String main = weather.getString(1);
String desc = weather.getString(2);
// 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_DAY, day);
contact.put(TAG_DESC, desc);
contact.put(TAG_HUMIDITY, humidity);
// 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(
ParseJ.this, contactList,
R.layout.list_item, new String[] { TAG_DAY, TAG_DESC,
TAG_HUMIDITY }, new int[] { R.id.temp,
R.id.main, R.id.Descrption });
setListAdapter(adapter);
}
}
}
based on your JSON it is just a list of element. Arrays have [ at the beginning and ] at the end. look closely at your JSON you may find some array elements there that has [].
weather only has 1 element
"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}]
index out of bounds because you are using
JSONArray weather = c.getJSONArray(TAG_WEATHER);
String main = weather.getString(1);
String desc = weather.getString(2);
where there is no 1 and 2 in your json array weather, since the weather seems to have only 1 element put it in another json object
JSONObject weather = c.getJSONArray(TAG_WEATHER).getJSONObject(0);
String main = weather.getString("main");
String desc = weather.getString("description");
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("list");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
}
change this in your code and let me know, if any issue.
the json is here
{"cod":"200","message":0.2809,"city":{"id":1244926,"name":"Hambantota","coord":{"lon":81.1185,"lat":6.1241},"country":"LK","population":0},"cnt":10,"list":[{"dt":1409896800,"temp":{"day":301.95,"min":300.47,"max":302.12,"night":301.31,"eve":301.87,"morn":300.47},"pressure":1020.63,"humidity":88,"weather":[{"id":803,"main":"Clouds","description":"broken
clouds","icon":"04d"}],"speed":6.47,"deg":243,"clouds":56},{"dt":1409983200,"temp":{"day":301.11,"min":299.62,"max":301.29,"night":299.62,"eve":300.76,"morn":300.13},"pressure":1021.53,"humidity":92,"weather":[{"id":802,"main":"Clouds","description":"scattered
clouds","icon":"03d"}],"speed":6.66,"deg":249,"clouds":48},{"dt":1410069600,"temp":{"day":300.9,"min":299.36,"max":300.9,"night":299.58,"eve":300.2,"morn":299.36},"pressure":1022.25,"humidity":90,"weather":[{"id":803,"main":"Clouds","description":"broken
clouds","icon":"04d"}],"speed":7.21,"deg":242,"clouds":80},{"dt":1410156000,"temp":{"day":299.47,"min":298.71,"max":300.44,"night":299.5,"eve":299.96,"morn":298.71},"pressure":1023.27,"humidity":98,"weather":[{"id":802,"main":"Clouds","description":"scattered
clouds","icon":"03d"}],"speed":5.83,"deg":252,"clouds":44},{"dt":1410242400,"temp":{"day":301.38,"min":297.39,"max":301.38,"night":298.36,"eve":300.82,"morn":297.39},"pressure":1012.02,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":3.87,"deg":250,"clouds":76,"rain":0.38},{"dt":1410328800,"temp":{"day":301.77,"min":297.49,"max":301.77,"night":299.44,"eve":301.13,"morn":297.49},"pressure":1011.84,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":4.88,"deg":259,"clouds":27,"rain":0.82},{"dt":1410415200,"temp":{"day":302.15,"min":299.15,"max":302.15,"night":299.43,"eve":300.52,"morn":299.15},"pressure":1011.1,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":6.3,"deg":257,"clouds":64,"rain":1.82},{"dt":1410501600,"temp":{"day":301.52,"min":299.16,"max":301.52,"night":299.36,"eve":300.59,"morn":299.16},"pressure":1011.05,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":8.05,"deg":257,"clouds":50,"rain":2.38},{"dt":1410588000,"temp":{"day":301.26,"min":298.74,"max":301.26,"night":299.53,"eve":300.43,"morn":298.74},"pressure":1010.43,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10d"}],"speed":7.69,"deg":258,"clouds":33,"rain":1.34},{"dt":1410674400,"temp":{"day":300.01,"min":298.37,"max":300.01,"night":298.48,"eve":298.37,"morn":298.87},"pressure":1010.17,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate
rain","icon":"10d"}],"speed":8.36,"deg":253,"clouds":55,"rain":8.91}
and then you get object with tag "cod"
contacts = jsonObj.getJSONArray(TAG_COd)
"cod":"200"
you will get "200"
how can "200" be converted to JSONArray?
the array structure is just like this
[{"dt":1409896800},{"dt":1409896800},{"dt":1409896800},{"dt":1409896800}]
starts with "[" and end with "]"
Exception is self Explaining
org.json.JSONException: Value 200 at cod of type java.lang.String cannot be converted to JSONArray
You are converting String to JSONArray here,
contacts = jsonObj.getJSONArray(TAG_COd);
cod is a String while you're converting it to JSONArray
String cod = jsonObj.getJSONString(TAG_COd);
I'm working on an app that I need to be able to load a list of locations into a ListView, and then let the user select a single location which will then determine the rest of the user's experience down the line.
Currently I have the list of locations being pulled from a JSON request and I can easily display the information into a ListView - the problem I am having though is getting that same list into some form of list that the user can select just one location. I personally have no preference on if it's a radio button list or a spinner. I have been trying various methods for the past week now from tutorials on the net, but I can never get any of them to work with my current method of retrieving and storing the list, so I'm finally at wits end and looking for some guidance. I am extremely new to java/android programming so I know that my lack of experience is probably the most to blame here. So I guess if someone can at least just point me in the right direction so I'm not spinning my wheels on a solution that would require a ton of re-work then I would greatly appreciate it!
Below is my current activity that retrieves the JSON and slaps it into a standard ListView - I have it storing the info into a DB for use further down the app's line.
public class SQLiteJSONParsing extends ListActivity {
private ProgressDialog pDialog;
//////////////////////// JSON URL //////////////////////////
private static String url = "http://my/link/to/json";
//////////////////////// 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_CON_POSITION = "con_position";
private static final String TAG_ADDRESS = "address";
private static final String TAG_SUBURB = "suburb";
private static final String TAG_STATE = "state";
private static final String TAG_POSTCODE = "postcode";
private static final String TAG_TELEPHONE = "telephone";
private static final String TAG_EMAIL_TO = "email_to";
//////////////////////// JSON Array //////////////////////////
JSONArray contacts = null;
private DatabaseHelper databaseHelper;
//////////////////////// HashMap ListView //////////////////////////
ArrayList<HashMap<String, String>> locationsList;
///////////////////////// Start onCreate method ////////////////////////////
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_launch_options);
databaseHelper = new DatabaseHelper(SQLiteJSONParsing.this);
locationsList = new ArrayList<HashMap<String, String>>();
//////////////////////// Skip Button //////////////////////////
Button cancel = (Button)findViewById(R.id.cancel);
cancel.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
Intent locationList = new Intent(SQLiteJSONParsing.this, MainActivity.class);
startActivity(locationList);
finish();
}
});
//////////////////////// Start ASYNC //////////////////////////
new GetLocations().execute();
}
//////////////////////// ASYNC HTTP Call //////////////////////////
private class GetLocations extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SQLiteJSONParsing.this);
pDialog.setMessage("Loading Locations...");
pDialog.setCancelable(true);
pDialog.show();
}
//////////////////////// Start Background Service Handler & Load the DB //////////////////////////
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
LocationsFeedServiceHandler sh = new LocationsFeedServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, LocationsFeedServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
//////////////////////// Get the JSON Node Array //////////////////////////
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
//////////////////////// Loop Through the Results //////////////////////////
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 con_position = c.getString(TAG_CON_POSITION);
String address = c.getString(TAG_ADDRESS);
String suburb = c.getString(TAG_SUBURB);
String state = c.getString(TAG_STATE);
String postcode = c.getString(TAG_POSTCODE);
String telephone = c.getString(TAG_TELEPHONE);
String email_to = c.getString(TAG_EMAIL_TO);
//////////////////////// Save Records to DB //////////////////////////
databaseHelper.saveTableRecord(id, name, con_position, address, suburb, state, postcode, telephone, email_to);
//////////////////////// Single Items HashMap //////////////////////////
HashMap<String, String> items = new HashMap<String, String>();
//////////////////////// Add Items to the HashMap //////////////////////////
items.put(TAG_ID, id);
items.put(TAG_NAME, name);
items.put(TAG_CON_POSITION, con_position);
items.put(TAG_ADDRESS, address);
items.put(TAG_SUBURB, suburb);
items.put(TAG_STATE, state);
items.put(TAG_POSTCODE, postcode);
items.put(TAG_TELEPHONE, telephone);
items.put(TAG_EMAIL_TO, email_to);
//////////////////////// Add Items to the LocationsList //////////////////////////
locationsList.add(items);
}
//////////////////////// Capture Exceptions //////////////////////////
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("LocationsFeedServiceHandler", "Couldn't get any data from the url");
}
return null;
}
//////////////////////// Close Progress Dialog //////////////////////////
protected void onPostExecute(Void location_result) {
super.onPostExecute(location_result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
//////////////////////// Update the Parsed JSON into the ListAdapter //////////////////////////
ListAdapter locations_adapter = new SimpleAdapter(
SQLiteJSONParsing.this, locationsList,
R.layout.first_launch_locations_detail,
new String[] { TAG_NAME },
new int[] { R.id.name });
setListAdapter(locations_adapter);
}
}
I used this following example code, which i need to select single item from the listview.
http://amitandroid.blogspot.in/2013/03/android-custon-single-choice-lsitview.html