How to access Multiple JSONArrays with Listview? - android

I have two Listview,I am getting two JSONArray from server,I am getting following response
[
[
{
"user_status": "1",
"pooja_name": "Festival Sevas",
"sess_date": "Mon Nov 30 2015",
"session_status": "Completed",
"message": "What ever message you want"
}
],
[
{
"user_status": "1",
"pooja_name": "Pushpalankara Seva",
"sess_date": "Tue Dec 15 2015",
"session_status": "Pending",
"message": "What ever message you want"
}
]
]
I am able to parse both the arrays,but in my both listview it display Pushpalankara Seva,what i am trying is in my first listview i want to display Pushpalankara Seva and in second Festival Sevas
class LoadPoojas extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AboutUsFragment.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String,String>> upcomingdata = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(POOJA_LISTING_URL, ServiceHandler.GET);
map = new HashMap<String, String>();
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonObj = new JSONArray(jsonStr);
// Getting JSON Array node
JSONArray pastarray = jsonObj.getJSONArray(0);
for (int i = 0; i < pastarray.length(); i++) {
JSONObject c = pastarray.getJSONObject(i);
// creating new HashMap
// adding each child node to HashMap key => value
map.put(POOJA_LISTING_NAME, c.getString(POOJA_LISTING_NAME));
}
JSONArray upcoming = jsonObj.getJSONArray(1);
for (int i = 0; i < upcoming.length(); i++) {
JSONObject c = upcoming.getJSONObject(i);
// creating new HashMap
// HashMap<String, String> upcomingmap = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(POOJA_LISTING_NAME, c.getString(POOJA_LISTING_NAME));
}
data.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
/*if(interestaccept == null || interestaccept.length() == 0){
// Toast.makeText(getApplicationContext(), "No response", Toast.LENGTH_SHORT).show();
noacpt.setText(" No Accepted List ");
}
else
{
noacpt.setVisibility(View.INVISIBLE);
}*/
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterPooja(getActivity(),result);
completedpooja.setAdapter(adapter);
adapterupcoming = new CustomAdapterPoojaUpcoming(getActivity(),result);
notcompletedpooja.setAdapter(adapterupcoming);
adapter.notifyDataSetChanged();
adapterupcoming.notifyDataSetChanged();
completedpooja.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
/* upcomingaList = new ArrayList<HashMap<String, String>>();
upcomingaList.addAll(result);
adapterupcoming = new CustomAdapterPoojaUpcoming(getActivity(),result);
notcompletedpooja.setAdapter(adapterupcoming);
adapterupcoming.notifyDataSetChanged();
notcompletedpooja.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});*/
}
}

I checked you code and found you did mistake in hashmap with same key in both array(inside both For loop). So it overwrite with latest value as per rules of hashmap.
Solution :
Option 1: Take arraylist of hashmap and create new hashmap each new record.
Option 2: Take arraylist of POJO class.
Edit :
public class UserPOJO {
public String user_status;
public String pooja_name;
public String sess_date;
public String session_status;
public String message;
}
Take arraylist of POJO class like below
public ArrayList<UserPOJO> userPOJOs = new ArrayList<UserPOJO>();
Now insert data in arraylist from JSONArray.

Related

How to load replace json values in spinner?

I am new in android,I have one application,in my application i am getting user's profile data,here in my profile data i am getting user's state and city which user had previously set,like right now user set following state and city,and i am able to display that state and city in my spinner
{
"user_city": "Kolkata",
"user_state": "West Bengal",
}
Now issue is if user want to change state like from WestBengal to Karnataka,then i need to display all state and make user to change,so for that i have other separate webservice for load all state and i want to display that all state in same that spinner,but right now issue is i need to click two times then only it is showing all states
this is the response
[{"user_status":"1","state_id":"1","state":"Karnataka"},{"user_status":"1","state_id":"2","state":"Tamilnadu"},{"user_status":"1","state_id":"3","state":"Maharastra"},{"user_status":"1","state_id":"4","state":"Andhra Pradesh"},{"user_status":"1","state_id":"5","state":"West Bengal"},{"user_status":"1","state_id":"6","state":"Delhi"},{"user_status":"1","state_id":"8","state":"Andaman & Nicobar Islands"},{"user_status":"1","state_id":"9","state":"Arunachal Pradesh"},{"user_status":"1","state_id":"10","state":"Bihar"},{"user_status":"1","state_id":"11","state":"Chattisgarh"},{"user_status":"1","state_id":"12","state":"Dadra & Nagar Haveli"},{"user_status":"1","state_id":"13","state":"Daman & Diu"},{"user_status":"1","state_id":"14","state":"Goa"},{"user_status":"1","state_id":"15","state":"Gujarat"},{"user_status":"1","state_id":"16","state":"Haryana"},{"user_status":"1","state_id":"17","state":"Himachal Pradesh"},{"user_status":"1","state_id":"18","state":"Jharkhand"},{"user_status":"1","state_id":"19","state":"Kerala"},{"user_status":"1","state_id":"20","state":"Lakshadweep"},{"user_status":"1","state_id":"21","state":"Madhya pradesh"},{"user_status":"1","state_id":"22","state":"Pondichery"},{"user_status":"1","state_id":"23","state":"Punjab"},{"user_status":"1","state_id":"24","state":"Rajasthan"},{"user_status":"1","state_id":"25","state":"Sikkim"},{"user_status":"1","state_id":"26","state":"Telangana"},{"user_status":"1","state_id":"27","state":"Tripura"},{"user_status":"1","state_id":"28","state":"Uttaranchal"},{"user_status":"1","state_id":"29","state":"Uttar Pradesh"},{"user_status":"1","state_id":"31","state":"Nagaland"},{"user_status":"1","state_id":"32","state":"Mizoram"},{"user_status":"1","state_id":"33","state":"Meghalaya"},{"user_status":"1","state_id":"34","state":"Manipur"},{"user_status":"1","state_id":"35","state":"Assam"},{"user_status":"1","state_id":"36","state":"Chandigarh"},{"user_status":"1","state_id":"37","state":"Orissa"},{"user_status":"1","state_id":"38","state":"Others"}]
Loading profile
class LoadAllProdetails extends
AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
private String test;
private JSONObject jsonObjsss;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Profiles.this.getActivity());
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(GET_PRO_DETAILS, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObjsss = new JSONObject(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
profilessstates=new ArrayList<HashMap<String,String>>();
profilecitis=new ArrayList<HashMap<String,String>>();
if(jsonObjsss.getString(GET_PRO_USERSTATUS).equals("0"))
{
final String msgs=jsonObjsss.getString("message");
System.out.println("Messagessss"+msgs);
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getActivity(), msgs, Toast.LENGTH_LONG).show();
}
});
}
else if(jsonObjsss.getString(GET_PRO_USERSTATUS).equals("1")) {
HashMap<String, String> mapzz = new HashMap<String, String>();
usersstatus = jsonObjsss.getString(GET_PRO_USERSTATUS);
usersfname = jsonObjsss.getString(GET_PRO_FIRSTNAME);
usersmails = jsonObjsss.getString(GET_PRO_EMAILS);
usersmob = jsonObjsss.getString(GET_PRO_MOBILE);
usersdobs = jsonObjsss.getString(GET_PRO_DATES);
usersaddresss = jsonObjsss.getString(GET_PRO_ADDRESS);
userszipss = jsonObjsss.getString(GET_PRO_ZIP);
userstates=jsonObjsss.getString(GET_PRO_STATE);
usercitys=jsonObjsss.getString(GET_PRO_CITY);
mapzz.put(GET_PRO_STATE, jsonObjsss.getString(GET_PRO_STATE));
mapzz.put(GET_PRO_CITY, jsonObjsss.getString(GET_PRO_CITY));
profilessstates.add(mapzz);
profilecitis.add(mapzz);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return profilessstates;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
pDialog.dismiss();
updtfname.setText(usersfname);
updtmail.setText(usersmails);
updtmob.setText(usersmob);
updtaddress.setText(usersaddresss);
updtpin.setText(userszipss);
datestext.setText(usersdobs);
arrprostates = new String[profilessstates.size()];
for (int index = 0; index < profilessstates.size(); index++) {
HashMap<String, String> map = profilessstates.get(index);
arrprostates[index] = map.get(GET_PRO_STATE);
}
adapterprostates = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrprostates);
statespinner.setAdapter(adapterprostates);
arrprocities = new String[profilecitis.size()];
for (int index = 0; index < profilecitis.size(); index++) {
HashMap<String, String> map = profilecitis.get(index);
arrprocities[index] = map.get(GET_PRO_CITY);
}
adapterprocities = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrprocities);
cityspinner.setAdapter(adapterprocities);
To load all states
class LoadStatess extends
AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
private String test;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Profiles.this.getActivity());
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
statedata = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONArray(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(USER_STATUSS, c.getString(USER_STATUSS));
map.put(PRESET_TITLES, c.getString(PRESET_TITLES));
statedata.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return statedata;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
// pDialog.dismiss();
arrallstates = new String[statedata.size()];
for (int index = 0; index < statedata.size(); index++) {
HashMap<String, String> map = statedata.get(index);
arrallstates[index] = map.get(PRESET_TITLES);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adapterallstates = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrallstates);
statespinner.setAdapter(adapterallstates);
statespinner.setPrompt("Select State");
statespinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spitems = statespinner.getSelectedItem().toString();
System.out.println("PresetEVent selected" + spitems);
new Logincity().execute();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
first screen by default get
then i click to load state it shows
then again i click the only it shows
Put these lines in OnCreate method of your activity.
adapterallstates = new ArrayAdapter<String>(Profiles.this.getActivity(),android.R.layout.simple_spinner_dropdown_item, new ArrayList<String>());
statespinner.setAdapter(adapterallstates);
And delete these lines from onPostExecute:
adapterallstates = new ArrayAdapter<String>(Profiles.this.getActivity(),android.R.layout.simple_spinner_dropdown_item, arrallstates);
statespinner.setAdapter(adapterallstates);
And add these lines in for loop of onPostExecute.
adapterallstates.add(map.get(PRESET_TITLES));
adapterprostates.notifyDataSetChanged();
Do this it will work for you.
other one is to,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoadListView();
}
private void LoadListView() {
try {
statespinner.setAdapter(adapterprostates);
} catch (Exception e) {
e.printStacktrace();
}
}

json parsing in android working with kimono api

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;
}

JSON Data stored to SQLite

I am following this to store JSON parsed data into SQLite Database, but whenever i use my app offline not getting stored data into ListView.
Is there anything left to implement in my existing code ?
MainActivity.java:-
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper=new CategoryHelper(MainActivity.this);
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) {
}
});
// 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);
// 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);
databaseHelper.saveCategoryRecord(id,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
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 }, new int[] { R.id.name });
setListAdapter(adapter);
}
}
I don't know what that ServiceHandler thing is, but I'm guessing the call to makeServiceCall() returns null when you're offline. This means you aren't populating the contactList, which means it's empty when you're creating the ListAdapter.
I'm guessing what you want to do, is add an else clause to if (jsonStr != null) that populates contactList with records from your DB. How to do this depends on the implementation details of CategoryHelper.
Using shared preference would be a better approach for that. Follow these steps:
search and download GSON library. This will simplify our task for saving and retrieving JSON to/from shared preferences and let your app use the GSON library
example:
SharedPreferences prefs = getSharedPreferences("mySharedPreferenceKey");
Editor editor = prefs.edit();
Gson gson = new Gson();
//convert your object to string and save it to shared preference
ArrayList<Integer> myIntArrs = new ArrayList<Integer>();
editor.putString("myJSONKey", new Gson().toJson(myIntArrs)).commit();
//get your json string from shared preferences
public final Type ARRAYLIST_INTEGER = new TypeToken<ArrayList<Integer>>(){}.getType();
ArrayList<Integer> intArrs = gson.fromJson(prefs.getString("myJSONKey", "{}"), ARRAYLIST_INTEGER);
//do something with your intArrs
Hope this helps!

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.

implementing the Endless Adapter

I get the entire data from the Server by using doInBackground() method as shown below.
class DataLoader extends Activity{
public void onCreate()
{
...............................
new AsyncTask1().execute();
}
class AsyncTask1 extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(DataLoader.this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
protected String doInBackground(String... args) {
JSONObject json;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1",datafield1));
params.add(new BasicNameValuePair("param2",datafield2));
json = jsonParser.makeHttpRequest(url, "POST", params);
try {
int success = json.getInt(SUCCESS);
if (success == 1) {
products = json.getJSONArray(PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(ID);
String price = c.getString(PRICE);
String name = c.getString(NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(PID, id);
map.put(PRICE, price);
map.put(NAME, name);
..................
// adding HashList to ArrayList
productsList.add(map);
}
return "success";
}
else {
// no materials found for this section
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String msg) {
if( msg != null && msg.equals("success"))
{
progressDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
customadapter=new CustomAdapterList(DataLoader.this, productsList);
listView.setAdapter(adapter);
}
});
}
}
}
As per the above code, I am setting the data to the listview in the onPostExecute() method only after the entire data is loaded. But now I want to implement the CW Endless Adapter with the present code, but as I am new to this, I am unable to get how to move on from here. I included the CWAdapter jar file in the libs folder. Have referred this and searched a lot , but no use. Can some one please help me implementing the endless feature for the data I get?
Basic Idea is to run an AsyncTask when more data is required, that is when uses scrolls to bottom of the list. Here's a quick demo project.

Categories

Resources