json parsing in android working with kimono api - android

I am working with a parsing json and fetching my json data from kimono.I am fetching json from following url:
http://www.brankart.com/test/tra.json
My mainactivity goes as follows:
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://www.brankart.com/test/tra.json";
// JSON Node names
private static final String lnk = "href";
private static final String d1 = "text";
private static final String dt = "property2";
// 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);
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(),
SingleContactActivity.class);
in.putExtra(lnk, name);
in.putExtra(dt, cost);
in.putExtra(d1, 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);
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);
JSONObject nsb = jsonObj.getJSONObject("results");
// Getting JSON Array node
contacts = nsb.getJSONArray("collection1");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
JSONObject p1 = c.getJSONObject("property1");
String link = p1.getString(lnk);
String descp = p1.getString(d1);
String detail = p1.getString(dt);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(lnk, link);
contact.put(d1, descp);
contact.put(dt, detail);
// 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[] { d1, dt,
lnk }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
}
I am still not able to fetch my json in listview.Please help

Try change doInBackground like below
#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);
JSONObject nsb = jsonObj.getJSONObject("results");
// Getting JSON Array node
contacts = nsb.getJSONArray("collection1");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
JSONObject p1 = c.getJSONObject("property1");
String link = p1.getString(lnk);
String descp = p1.getString(d1);
//change here !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
String detail = c.getString(dt);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(lnk, link);
contact.put(d1, descp);
contact.put(dt, detail);
// 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;
}

Related

When we click on item in listview then how we get id of that item

I have a json in which i have product_id and product_name through the Json products are showing in listview now i want that when clicked on item then id of that product should be show in toast. I am new to android i am unable to do this
can anyone tell me how can i do this please
public class CityNameActivity extends ListActivity{
ListView list;
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
// list.setOnClickListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(),
Specialities_Activity.class);
startActivity(in);}
});
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.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
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} 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();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
Code of Service Handlerclass:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
code of Hospital Activity in which hospital is showing in listview i want that not all hospitals show only show hospital of specific city
public class HospitalList_Activity extends ListActivity {
private ProgressDialog pDialog;
// URL to get Hospitals JSON
private static String url = "http://14.140.200.186/hospital/get_hospital.php";
// JSON Node names
private static final String TAG_HOSPITAL = "Hospitals";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "hospital_name";
// Hospitals JSONArray
JSONArray Hospitals = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> hospitallist;
//ArrayList<String> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital_list_);
ListView listView=getListView();
hospitallist = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(), Specialities_Activity.class);
startActivity(in);
}
});
new GetHospitals().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetHospitals extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(HospitalList_Activity.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
Hospitals = jsonObj.getJSONArray(TAG_HOSPITAL);
// looping through All Cities
for (int i = 0; i < Hospitals.length(); i++) {
JSONObject c = Hospitals.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Hospitals = new HashMap<String, String>();
Hospitals.put(TAG_NAME, name);
// adding contact to Cities list
hospitallist.add(Hospitals);
}
} 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();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(HospitalList_Activity.this, hospitallist, R.layout.hospital_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
public class CityNameActivity extends ListActivity {
ListView list;
Map <String, String> cityListWithId = new HashMap<String, String>();
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
private static final String TAG_ID = "city_id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cityname_activity_main);
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//String tagname = ((TextView) findViewById(R.id.name)).getText().toString();
Map<String, String> tempHashmap = (Map<String, String>) parent.getItemAtPosition(position);
String tagName = tempHashmap.get(TAG_NAME);
System.out.println("tagname" + tagName);
String tagId = (String)cityListWithId.get(tagName);
System.out.println("tagId" + tagId);
Toast.makeText(CityNameActivity.this, tagId,Toast.LENGTH_SHORT).show();
}
});
new GetCities().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.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
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
cityListWithId.put(c.getString(TAG_NAME), c.getString(TAG_ID));
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} 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();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
}
On ItemClick() method you can add this to get the id of the product.
HashMap<String,String> data = cityList.get(position);
//position is the paramater from ItemClick
String id = data.get("your key for Id");
why you every time hit the service . as per my opinion don't call service in onItemClick . when you start activity or app start Async task and pass data to list view .
please find below code . i am just refactor few thing so please let me if there some thing wrong
public class CityNameActivity extends ListActivity
{
private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
//private static final String TAG_ID = "id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new GetCities().execute();
ListView listView=getListView();
citylist = new ArrayList<HashMap<String, String>>();
// list.setOnClickListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(citylist!=null && !citylist.isEmpty())
{
Toast.makeText(CityNameActivity.this,""+citylist.get(position).get(TAG_NAME).toString(),Toast.LENGTH_SHORT).show();
}
}
});
new GetCities().execute();
}
private class GetCities extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CityNameActivity.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
Cities = jsonObj.getJSONArray(TAG_CITIES);
// looping through All Cities
for (int i = 0; i < Cities.length(); i++) {
JSONObject c = Cities.getJSONObject(i);
//String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> Cities = new HashMap<String, String>();
Cities.put(TAG_NAME, name);
// adding contact to Cities list
citylist.add(Cities);
}
} 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();
/**`enter code here`
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
}

Android JSON ListView import

I'm slowly turning crazy here.
I've got NewsActivity that gets information from a website and puts it in the listview but it isn't working.
public class NewsActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String NEWS_URL = "http://www.bandofbrothersgaming.nl/android/news.php";
// JSON Node names
private static final String TAG_POSTID = "sid";
private static final String TAG_POSTSUBJECT = "title";
private static final String TAG_POSTTEXT = "hometext";
// contacts JSONArray
JSONArray post_id = null;
// Hashmap for ListView
ArrayList < HashMap < String, String >> NewsList;
#
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
NewsList = 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.post_id))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.post_subject))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.post_text))
.getText().toString();
// Starting single contact activity
/* Intent in = new Intent(getApplicationContext(),
SingleContactActivity.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(NewsActivity.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(NEWS_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
post_id = jsonObj.getJSONArray(TAG_POSTID);
// looping through All Posts
for (int i = 0; i < post_id.length(); i++) {
JSONObject c = post_id.getJSONObject(i);
String postid = c.getString(TAG_POSTID);
String postsubject = c.getString(TAG_POSTSUBJECT);
String posttext = c.getString(TAG_POSTTEXT);
// tmp hashmap for single contact
HashMap < String, String > contact = new HashMap < String, String > ();
// adding each child node to HashMap key => value
contact.put(TAG_POSTID, postid);
contact.put(TAG_POSTSUBJECT, postsubject);
contact.put(TAG_POSTTEXT, posttext);
// adding contact to contact list
NewsList.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(
NewsActivity.this, NewsList,
R.layout.list_item, new String[] {
TAG_POSTID, TAG_POSTSUBJECT,
TAG_POSTTEXT
}, new int[] {
R.id.post_id,
R.id.post_subject, R.id.post_text
});
setListAdapter(adapter);
}
}
}
When I run it LogCat says the following :
12-29 13:56:39.698: W/System.err(1685): org.json.JSONException: Value [{"hometext":"Welcome to Nuke-Evolution.<br \/><br \/>\r\n\r\nYou must now setup an admin account. You can do this by <a href=\"admin.php\">clicking here<\/a>.<br \/><br \/><br \/><br \/>\r\n\r\n<b>NOTE:<\/b> You can remove this by going into the News Administration or by clicking the delete button below.\r\n","sid":"1","time":"2005-07-02 10:38:28","title":"Welcome To Nuke-Evolution"},{"hometext":"<p>\n\ttest android<\/p>\n<p>\n\tandroid test<\/p>","sid":"2","time":"2014-12-28 23:21:25","title":"android test"}] of type org.json.JSONArray cannot be converted to JSONObject
Does anybodey knows what im doing wrong?
You are trying to convert jsonStr to a JSONObject, but in fact is a JSONArray, looking at the LogCat. So convert it to a JSONArray first, then iterate over it and get the data you are looking for.
You can use
JSONArray post_id = new JSONArray(jsonStr);
instead of
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
post_id = jsonObj.getJSONArray(TAG_POSTID);
because jsonStr you get is a JSONArray
That is response of you php file, review your code PHP.
try this
JSONArray jsonArr = new JSONArray(jsonStr);
for(int i = 0; i < jsonArr.length(); i++){
JSONObject item = jsonArr.getJSONObject(i);
String postid = item.getString(TAG_POSTID);
String postsubject = item.getString(TAG_POSTSUBJECT);
String posttext = item.getString(TAG_POSTTEXT);
// tmp hashmap for single contact
HashMap < String, String > contact = new HashMap < String, String > ();
// adding each child node to HashMap key => value
contact.put(TAG_POSTID, postid);
contact.put(TAG_POSTSUBJECT, postsubject);
contact.put(TAG_POSTTEXT, posttext);
// adding contact to contact list
NewsList.add(contact);
}

can't create multiple choice listview

This is my code i can't create the multiple choice mode listview.
Data is fetched by jason and set in the listview.
I want to multiple selection choice mode on the list view
public class ExamView extends ListActivity{
private ProgressDialog pDialog;
Intent activity;
// URL to get contacts JSON
// JSON Node names
private static final String TAG_USERMST = "products";
private static final String TAG_QID = "que_id";
private static final String TAG_QUE = "question";
private static final String TAG_QANS = "ans";
JSONArray products = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.user_activity_lv);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(ExamView.this);
pDialog.setMessage("Exam Paper is downloading...");
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
products = jsonObj.getJSONArray(TAG_USERMST);
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String queid = c.getString(TAG_QID);
String que = c.getString(TAG_QUE);
String queans = c.getString(TAG_QANS);
// tmp hashmap for single contact
HashMap<String, String> product = new HashMap<String, String>();
// adding each child node to HashMap key => value
product.put(TAG_QID,queid);
product.put(TAG_QUE, que);
product.put(TAG_QANS, queans);
// adding contact to contact list
contactList.add(product);
}
} 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(
ExamView.this, contactList,
R.layout.user_list_item_lbl, new String[] { TAG_QID, TAG_QUE,
TAG_QANS }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice, array_sort));
Use this code its working for me.
Here array_sort is an arraylist i.e. list of all the items to be displayed.
Multiple items can be selected with this.

JSON to listView in android

I'm trying to put JSON to ListView. I am getting data from http://api.androidhive.info/contacts/ (only using the name field) I am able to get them to array, but im unable to put them into the list,
[NOTE]
however the ListView makes exactly 13 lines for 13 entries (number of names) but the lines are blank.
private class GetJidla extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(TableMenuActivity.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
jidla = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < jidla.length(); i++) {
JSONObject c = jidla.getJSONObject(i);
// String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// 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);
// adding contact to contact list
jidlaList.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(
TableMenuActivity.this, jidlaList,
android.R.layout.simple_list_item_1, new String[] {TAG_NAME}, new int[] {android.R.id.list,
});
menu = (ListView)findViewById(android.R.id.list);
menu.setAdapter(adapter);
}
and the list is here
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip" >
</ListView>
i need it to be on one screen, in one activity here is the image, the brown lsit is where i need it
I have an exemple to do that:
public class MainActivity extends Activity {
//json string
private String jsonString = "{\"employee\":[{\"emp_name\":\"employee1\",\"emp_no\":\"101700\"},{\"emp_name\":\"employee2\",\"emp_no\":\"101701\"},{\"emp_name\":\"employee3\",\"emp_no\":\"101702\"},"+
"{\"emp_name\":\"employee4\",\"emp_no\":\"101703\"},{\"emp_name\":\"employee5\",\"emp_no\":\"101704\"},{\"emp_name\":\"employee6\",\"emp_no\":\"101705\"},"+
"{\"emp_name\":\"employee7\",\"emp_no\":\"101706\"},{\"emp_name\":\"employee8\",\"emp_no\":\"101707\"},{\"emp_name\":\"employee9\",\"emp_no\":\"101708\"},"+
"{\"emp_name\":\"employee10\",\"emp_no\":\"101709\"},{\"emp_name\":\"employee11\",\"emp_no\":\"101710\"},{\"emp_name\":\"employee12\",\"emp_no\":\"101711\"},"+
"{\"emp_name\":\"employee13\",\"emp_no\":\"101712\"},{\"emp_name\":\"employee14\",\"emp_no\":\"101713\"},{\"emp_name\":\"employee15\",\"emp_no\":\"101712\"}]}";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initList();
ListView listView = (ListView) findViewById(R.id.listView1);
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList, android.R.layout.simple_list_item_1, new String[] {"employees"}, new int[] {android.R.id.text1});
listView.setAdapter(simpleAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
List<Map<String,String>> employeeList = new ArrayList<Map<String,String>>();
private void initList(){
try{
JSONObject jsonResponse = new JSONObject(jsonString);
JSONArray jsonMainNode = jsonResponse.optJSONArray("employee");
for(int i = 0; i<jsonMainNode.length();i++){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("emp_name");
String number = jsonChildNode.optString("emp_no");
String outPut = name + "-" +number;
employeeList.add(createEmployee("employees", outPut));
}
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), "Error"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
private HashMap<String, String>createEmployee(String name,String number){
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
I use this code and it works fine!
Code from JSON Exemple
Here is the very simple example for json to list view
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
download the project and use your own service in MainActivity.java
replace the service URl with your url and format your array accordingly thatz it
happy coding.

How to parse a json rss feed into an android widget

please i need help, am a rookie, how can i create a widget that get its feed from from a Json in android. Is there a helpful tutorial that can help with this or a source code i can look at. I have checked online for a suitable tutorail but i found none that can help directly. this is the json url feed i want to pass into my android widget:url
public class MinistryNews extends SherlockListActivity {
private ActionBarMenu abm;
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://";
// JSON Node names
private static final String TAG_QUERY = "query";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_CONTENT = "content";
// private static final String TAG_CAT_CODE = "cat_code";
// private static final String TAG_STATUS = "status";
// private static final String TAG_CREATED_TIME = "created_time";
private static final String TAG_UPDATE_TIME = "update_time";
// private static final String TAG_AUTHOR_ID = "author_id";
// contacts JSONArray
JSONArray query = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> queryList;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ministry_news);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
abm = new ActionBarMenu(MinistryNews.this);
if (com.cepfmobileapp.org.service.InternetStatus.getInstance(this)
.isOnline(this)) {
// Toast t = Toast.makeText(this,"You are online!!!!",8000).show();
// Toast.makeText(getBaseContext(),"You are online",Toast.LENGTH_SHORT).show();
// Calling async task to get json
new GetQuery().execute();
} else {
// Toast.makeText(getBaseContext(),"No Internet Connection",Toast.LENGTH_LONG).show();
// Toast t =
// Toast.makeText(this,"You are not online!!!!",8000).show();
// Log.v("Home",
// "############################You are not online!!!!");
AlertDialog NetAlert = new AlertDialog.Builder(MinistryNews.this)
.create();
NetAlert.setMessage("No Internet Connection Found! Please check your connection and try again!");
NetAlert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
// finish();
}
});
NetAlert.show();
}
queryList = 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.title))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.time))
.getText().toString();
String description = ((TextView) view
.findViewById(R.id.content)).getText().toString();
// String plain = Html.fromHtml(description).toString();
// description.replace(/<\/?[^>]+>/gi, '');
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleActivity.class);
in.putExtra(TAG_TITLE, name);
in.putExtra(TAG_UPDATE_TIME, cost);
in.putExtra(TAG_CONTENT, description);
startActivity(in);
}
});
// Calling async task to get json
// new GetQuery().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetQuery extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MinistryNews.this);
pDialog.setMessage("Please wait..Loading news");
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
query = jsonObj.getJSONArray(TAG_QUERY);
// looping through All Contacts
for (int i = 0; i < query.length(); i++) {
JSONObject c = query.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_CONTENT);
String update_time = c.getString(TAG_UPDATE_TIME);
// 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_TITLE, title);
contact.put(TAG_CONTENT, content);
contact.put(TAG_UPDATE_TIME, update_time);
// contact.put(TAG_PHONE_MOBILE, mobile);
// adding contact to contact list
queryList.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(MinistryNews.this,
queryList, R.layout.list_item, new String[] { TAG_TITLE,
TAG_UPDATE_TIME, TAG_CONTENT }, new int[] {
R.id.title, R.id.time, R.id.content });
setListAdapter(adapter);
}
}
here is a nice tutorial for you to import json data http://mrbool.com/how-to-use-json-to-parse-data-into-android-application/28944
if its hard for you still.i can suggest you one thing ,you can import your rss to any website and customize it there as you want it to be and post them as json data it will be easier to do i guess.
its a raugh test for geting json data only the method i think its a bit easier and detail u can return the values instead of showing them in a text from the textvw
public void getdata()
{
String result=null;
InputStream inputstream=null;
try{
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://www.hadid.aero/news_and_json");
HttpResponse response=httpclient.execute(httppost);
HttpEntity httpentity=response.getEntity();
inputstream= httpentity.getContent();
}
catch(Exception ex)
{
resultview.setText(ex.getMessage()+"at 1st exception");
}
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(inputstream,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!= null)
{
sb.append(line +"\n");
}
inputstream.close();
result=sb.toString();
}
catch(Exception ex)
{
resultview.setText(ex.getMessage()+"at 2nd exception");
}
try{
String s="test :";
JSONArray jarray=new JSONArray(result);
for(int i=0; i<jarray.length();i++)
{
JSONObject json=jarray.getJSONObject(i);
s= s +"+json.getString("lastname")+"\n"+
"newsid&title : "+json.getString("id_news")+" "+json.getString("title")+"\n"+
"date :"+json.getString("date")+"\n"+
"description : "+json.getString("description");
}
resultview.setText(s);
}
catch(Exception ex)
{
this.resultview.setText(ex.getMessage()+"at 3rd exception");
}
Check out GSON library which will create Java object with JSON content and use this in Your widget

Categories

Resources