Adding string before displaying json array - android

I am new to android development. I managed to populate a listview with a string and a number coming from a JSON array.
I want to add a string (Available Quantity: ) before I display the number.
Can anyone help me with this?
It's being currently displayed as..
French Fries
1
Coke
4
I want to display it as:
Product: Coke
Quantity Available: 4
AllProductsActivity.java
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://api.nal.usda.gov/ndb/search/?format=json&q=french%20fries&sort=n&max=250&offset=0&api_key=DEMO_KEY";
// JSON Node names
private static final String TAG_PID = "offset";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
}
/**
* 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(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* 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_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// products found
// Getting Array of Products
products = json.getJSONObject("list").getJSONArray("item");
// 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(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.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();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}

you can simple add up string when getting it from json like..
String id = "Quantity Available: "+c.getString(TAG_PID);
String name = "Product: "+c.getString(TAG_NAME);

Related

How to check and uncheck the Checkbox?

I am creating a checklist that involves XAMPP and JSON. As my first step before saving the Checkbox state into sharedPreferences, can somebody help me on how to check/uncheck the Checkbox in the setOnItemClickListener? I'm using SimpleAdapter in my onPostExecute therefore I do not know how to check/uncheck the Checkbox. All example that I found often use viewHolder and custom adapter. I can't override thegetViewfor SimpleAdapter.
My AllDetails class extends a ListActivity.
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://10.207.200.73/list/get_details.php";
/// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "list";
private static final String TAG_PID = "quantity";
private static final String TAG_NAME = "items";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);
}
});
// Loading products in Background Thread
new LoadAllProducts().execute();
My JSON part
/**
* 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(AllDetails.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* 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_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_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(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.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();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllDetails.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.quantity, R.id.items });
// updating listview
setListAdapter(adapter);
}
});
}}
This link will guide you to get checkbox value from custom adapter and save to shared preference. Modify this code to feed the info from json
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country("AFG","Afghanistan",false);
countryList.add(country);
...
with your product list and pass to custom adapter
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this,
R.layout.country_info, countryList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
in your onPostExecute() and change checkButtonClick() to save your shared preference from dataAdapter

How to create a listview to get text from web and image from folder

I make list that show text from database but the image near items. I need images that get from drawable folder in Android. It means in listview text from database and image from Android.
Code is:
public class Category extends Activity {
// progress dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> categoryList;
private static String url_books = "http://10.0.2.2/project/category.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CATEGORY = "category";
private static final String TAG_CATEGORY_ID = "category_id";
private static final String TAG_CATEGORY_NAME = "category_name";
private static final String TAG_MESSAGE = "massage";
// category JSONArray
JSONArray category = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category);
Typeface font1 = Typeface.createFromAsset(getAssets(),
"font/bnazanin.TTF");
// Hashmap for ListView
categoryList = new ArrayList<HashMap<String, String>>();
new LoadCategory().execute();
ListView imagelist=(ListView) findViewById(R.id.list_image);
imagelist.setAdapter(new imageview(this));
}
/**
* Background Async Task to Load category by making HTTP Request
* */
class LoadCategory extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Category.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_books, "GET", params);
// Check your log cat for JSON reponse
Log.d("category: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Getting Array of category
category = json.getJSONArray(TAG_CATEGORY);
for (int i = 0; i < category.length(); i++) {
JSONObject c = category.getJSONObject(i);
// Storing each json item in variable
String category_id = c.getString(TAG_CATEGORY_ID);
String category_name = c.getString(TAG_CATEGORY_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CATEGORY_ID,category_id);
map.put(TAG_CATEGORY_NAME, category_name);
// adding HashList to ArrayList
categoryList.add(map);
}
return json.getString(TAG_MESSAGE);
} else {
System.out.println("no category found");
}
} 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();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
ListView lv=(ListView)findViewById(R.id.list_view);
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Category.this,categoryList,
R.layout.category_item, new String[] { TAG_CATEGORY_NAME},
new int[] { R.id.category_name });
// updating listview
// setListAdapter(adapter);
lv.setAdapter(adapter);
}
});
}
}
In my code, i have text but no image. Any help?
Create a pojo for your needs in list items,You can set pojos values from web or local, then use custom listadapter override getView method according to ur needs. A good explanation here!

Android - Update ListView when data is added in sever

I'm new to android development. I am trying to make an application that retrieves data from a web server and updates it in a list view. The problem is whenever a new data is entered in the database the list view doesn't get updated.
How to automatically update the list when there is a new entry in the database?
public class NotificationTask extends ListActivity {
UserFunctions userFunctions;
Button btnLogout;
DatabaseHandler dbHandler;
private HashMap<String, String> user;
SessionManager session;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.1.9/android_login_api/get_notifications.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "notifications";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "title";
private static final String TAG_DESCRIPTION = "discription";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new SessionManager(getApplicationContext());
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
// user already logged in show databoard
setContentView(R.layout.notifications);
btnLogout = (Button) findViewById(R.id.btnlogout);
dbHandler = new DatabaseHandler(getApplicationContext());
user = dbHandler.getUserDetails();
TextView emailTextView = (TextView) findViewById(R.id.user);
emailTextView.setText(user.get("name"));
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
session.logoutUser();
}
});
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
/**
* 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(NotificationTask.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* 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.getJSONFromUrl(url_all_products, params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_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(TAG_PID);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESCRIPTION, description);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
}
} 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();
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
NotificationTask.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME, TAG_DESCRIPTION},
new int[] { R.id.pid, R.id.name, R.id.description });
setListAdapter(adapter)
}
}
}
Looks to me like this is an ideal use case for a Sync Adapter.

Is it Possible to get results of AsyncTask as an Arraylist Hashmap

I have at least three activities in my app right now that use an AsyncTask to return JSON results into an ListView. I've started work on the app, but another person will take over development as soon as he gets the basics down, so I want to try and make things as easy to use as possible. This means that I'm trying to turn as much repeatable code into callable functions as possible, so instead of needing to copy/paste/reuse 30-40 lines of code each time they need query a webservice, they can just pass in parameters to a function.
Currently, I have the following in an activity that pulls a list of gym classes from a mysql database via a php webservice:
class LoadAllClasses extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(Checkin.this);
// pDialog.setMessage("Loading products. Please wait...");
// pDialog.setIndeterminate(false);
// pDialog.setCancelable(false);
// pDialog.show();
}
/**
* getting All products from url
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", getclasses_tag));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(SmashGyms.WEBSERVICE_URL,
"POST", params);
// Check your log cat for JSON response
Log.d("CheckinDialog", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// classes found
// Getting Array of Classes
classes2 = json.getJSONArray(TAG_CLASSES);
// looping through All Classes
for (int i = 0; i < classes2.length(); i++) {
JSONObject c = classes2.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_CLASSID);
String name = c.getString(TAG_CLASSNAME);
//String day = c.getString(TAG_DAY);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CLASSID, id);
map.put(TAG_CLASSNAME, name);
//map.put(TAG_DAY, day);
// adding HashList to ArrayList
allclasseslist.add(map);
Log.d("map: ", map.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
runOnUiThread(new Runnable() {
#Override
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(CheckinDialog.this,
allclasseslist, R.layout.checkin_item,
new String[] { TAG_CLASSID, TAG_CLASSNAME },
new int[] { R.id.pid, R.id.name });
setListAdapter(adapter);
}
});
//pDialog.dismiss();
// updating UI from Background Thread
}
}
I'd like to move this to another class that I have, called "WebServiceTasks", so that I can call something like this in the activity's OnCreate():
allclasseslist = new ArrayList<HashMap<String, String>>();
allclasseslist = new WebServiceTasks.LoadAllClasses().get();
adapter = new SimpleAdapter(CheckinDialog.this,
allclasseslist, R.layout.checkin_item,
new String[] { TAG_CLASSID, TAG_CLASSNAME },
new int[] { R.id.pid, R.id.name });
setListAdapter(adapter);
While I've tried this, I get a number of errors related to either defining the asyncTask wrong, or other things not matching up.
Here is what I've tried putting in my "WebServiceTasks" class:
public static class LoadAllClasses extends
AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> allclasseslist;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CLASSES = "classes";
private static final String TAG_CLASSID = "id";
private static final String TAG_CLASSNAME = "class";
private static final String getclasses_tag = "getclasses";
JSONArray classes2 = null;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(Checkin.this);
// pDialog.setMessage("Loading products. Please wait...");
// pDialog.setIndeterminate(false);
// pDialog.setCancelable(false);
// pDialog.show();
}
/**
* getting All classes from url
* */
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", getclasses_tag));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(SmashGyms.WEBSERVICE_URL,
"POST", params);
// Check your log cat for JSON response
Log.d("CheckinDialog", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// classes found
// Getting Array of Classes
classes2 = json.getJSONArray(TAG_CLASSES);
// looping through All Classes
for (int i = 0; i < classes2.length(); i++) {
JSONObject c = classes2.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_CLASSID);
String name = c.getString(TAG_CLASSNAME);
//String day = c.getString(TAG_DAY);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CLASSID, id);
map.put(TAG_CLASSNAME, name);
//map.put(TAG_DAY, day);
// adding HashList to ArrayList
allclasseslist.add(map);
Log.d("map: ", map.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return allclasseslist;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(
ArrayList<HashMap<String, String>> allclasses) {
// dismiss the dialog after getting all products
//pDialog.dismiss();
// updating UI from Background Thread
}
}
Is this possible, and if so, what am I doing wrong?
Well, you are trying to use get() method of AsyncTask which is very expensive because it blocks the UI until your onPostExecute() is completed. I would insist you to fire a BroadCastReceiver in onPostExecute() to update your UI or create and Interface and pass the result to your Activity using that interface in your onPostExecute(). I had just created a small demo for using BroadCastReceiver and Interface for passing result from onPostExecute() to your Activity. You can find a demo source from my github here.
You Can Create A Bean class to store all the values from async task so that your can receive it to another class my friend
For anyone trying to replicate this, Here is how I solved this, using Lalit and Samir's examples:
In my Activity:
public class CheckinDialog extends ListActivity implements
AsyncTaskCompleteListener {
WebServiceTasks.LoadAllClasses objAsyncTask = new WebServiceTasks.LoadAllClasses(
this);
objAsyncTask.execute();
#Override
public void onTaskComplete(ArrayList<HashMap<String, String>> allclasseslist) {
// TODO Auto-generated method stub
adapter = new SimpleAdapter(CheckinDialog.this, allclasseslist,
R.layout.checkin_item, new String[] { TAG_CLASSID,
TAG_CLASSNAME }, new int[] { R.id.pid, R.id.name });
setListAdapter(adapter);
Log.d("OnTaskComplete", "taskcomplete");
}
In an interface called "AsyncTaskCompleteListener":
public interface AsyncTaskCompleteListener {
void onTaskComplete(ArrayList<HashMap<String, String>> allclasseslist);
}
And the seperate WebServiceTasks Class:
public static class LoadAllClasses extends
AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
JSONParser jParser = new JSONParser();
private final AsyncTaskCompleteListener callback;
private final Activity activity;
public LoadAllClasses(Activity act) {
this.activity = act;
this.callback = (AsyncTaskCompleteListener) act;
}
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CLASSES = "classes";
private static final String TAG_CLASSID = "id";
private static final String TAG_CLASSNAME = "class";
private static final String getclasses_tag = "getclasses";
JSONArray classes2 = null;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting All classes from url
* */
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
// Building Parameters
ArrayList<HashMap<String, String>> allclasseslist = null;
allclasseslist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", getclasses_tag));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(SmashGyms.WEBSERVICE_URL,
"POST", params);
// Check your log cat for JSON response
Log.d("CheckinDialog", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// classes found
// Getting Array of Classes
classes2 = json.getJSONArray(TAG_CLASSES);
Log.d("JSONArray", json.getJSONArray(TAG_CLASSES)
.toString());
// looping through All Classes
for (int i = 0; i < classes2.length(); i++) {
JSONObject c = classes2.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_CLASSID);
String name = c.getString(TAG_CLASSNAME);
//String day = c.getString(TAG_DAY);
// creating new HashMap
final HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CLASSID, id);
map.put(TAG_CLASSNAME, name);
//map.put(TAG_DAY, day);
// adding HashList to ArrayList
allclasseslist.add(map);
//Log.d("map: ", map.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return allclasseslist;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(
ArrayList<HashMap<String, String>> allclasseslist) {
super.onPostExecute(allclasseslist);
// dismiss the dialog after getting all classes
callback.onTaskComplete(allclasseslist);
}
}
Thanks to all for the quick help. This ended up saving over 120 lines of repeating code in each activity that used this code.

Parsed JSON Data not displaying on android

I have a JSON string which is generated by a php file. The problem is that the JSON string is not appearing on the textview of android. can anyone explain why?
public class AllUsersActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> usersList;
// url to get all users list
private static String url_all_users = "http://10.0.2.2/android_connect/get_all_users.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UID = "UserID";
private static final String TAG_FIRSTNAME = "FirstName";
// users JSONArray
JSONArray users = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_users);
// Hashmap for ListView
usersList = new ArrayList<HashMap<String, String>>();
// Loading users in Background Thread
new LoadAllusers().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String uid = ((TextView) view.findViewById(R.id.uid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
UserDetailsActivity.class);
// sending uid to next activity
in.putExtra(TAG_UID, uid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllusers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllUsersActivity.this);
pDialog.setMessage("Loading users. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All users 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_users, "GET", params);
// Check your log cat for JSON reponse
Log.d("All users: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// users found
// Getting Array of users
users = json.getJSONArray(TAG_USERS);
// looping through All users
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_UID);
String name = c.getString(TAG_FIRSTNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_UID, id);
map.put(TAG_FIRSTNAME, name);
// adding HashList to ArrayList
usersList.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 users
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllUsersActivity.this, usersList,
R.layout.list_item, new String[] { TAG_UID,
TAG_FIRSTNAME},
new int[] { R.id.uid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
this is the JSON string from the PHP file
{"Users":[{"0":[],"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"0":[],"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null,"1":[]},{"0":[],"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null,"1":[],"2":[]},{"0":[],"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null,"1":[],"2":[],"3":[]}],"success":1}
I've found the error.
It is caused by case sensitiveness.
users --> Users
Mistake on my part. Sorry.
Thanks for trying to help me!

Categories

Resources