I currently have a ListAdapter set up that is passed information pulled from a MYSQL database via JSON. I'm trying to display an image I have stored in the drawable folder based on the ID of the product. e.g For Product 1 R.drawable.img1 is shown in and so on..
public class GetProducts extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSON jParser = new JSON();
Functions uf = new Functions();
ArrayList<HashMap<String, Object>> productsList;
// url to get all products list
private static String url_all_products = "http://jumpto.be/api/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_IMGURL = "image";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, Object>>();
new GetProductsFromDB().execute();
// Loading products in Background Thread
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
/*lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
OrderBuild.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});*/
}
class GetProductsFromDB extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(GetProducts.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.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 ImgUrl = c.getString(TAG_PID);
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
String imageLink = "R.drawable.img"+id;
map.put(TAG_IMGURL, imageLink);
// adding HashList to ArrayList
productsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
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() {
ListAdapter adapter = new SimpleAdapter(
GetProducts.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME, TAG_IMGURL},
new int[] { R.id.pid, R.id.name, R.id.img });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The current code I have just tells me it cannot find the directory. I have looked at URI but I can't figure out how I run them in the array / for loop.
Many Thanks
R.drawable.img1 is actually just an int value defined in your automatically generated R.java file, so you cannot use it directly.
However, you can retrieve your drawable using the following:
Resources resources = getResources();
int resId = resources.getIdentifier("img" + id, "drawable", getPackageName());
Drawable myDrawable = resources.getDrawable(resId);
Alternatively, you can place your image files in your assets directory and load them from there using the filename.
InputStream inputStream = getAssets().open("img" + id + ".jpg");
Drawable drawable = Drawable.createFromStream(inputStream, null);
mImageView.setImageDrawable(drawable);
You can set int value for drawable in hashmap. It is easy to bind in list adapter.
int imageLink = R.drawable.img1;
map.put(TAG_IMGURL, imageLink);
Related
I have this code for show product.
how to make each textview a clickable link to open a siteweb ?
public class AllProductsActivity extends ListActivity {
Progress Dialog
private ProgressDialog pDialog;
static String TAG = "MainActivity";
private EditText et_number;
private Button btnSet;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
url to get all products list
private static String url_all_products = "http:xxxx/android_connect/get_all_products.php";
JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
products JSONArray
JSONArray products = null;
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();
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 pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
}
});
}
Response from Edit Product Activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if result code 100
if (resultCode == 100) {
if result code 100 is received
means user edited/deleted product
reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllProducts extends AsyncTask<String, String, String> {
Before starting background thread Show Progress Dialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
setBadge(AllProductsActivity.this,
Integer.parseInt("6"));
Toast.makeText(AllProductsActivity.this, "please see badge on your application in launcher", Toast.LENGTH_SHORT).show();
}
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);
adding HashList to ArrayList
productsList.add(map);
}
} else {
no products found
Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
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() {
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);
}
});
}
}
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
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.
I have a problem getting a json value in PHP(mySQL). How can i get the value of totaly in the php page. I just want the value of totaly. Please help me. I am newbie in android programming.
This is my php page.
{"sales":[{"pid":"1","name":"book of eden","number_to_sale":"2","price":"2.00","total":"4.00","created_at":"2014-02-02 11:31:53"},{"pid":"2","name":"shirt","number_to_sale":"2","price":"500.00","total":"1000.00","created_at":"2014-02-03 14:23:49"},{"pid":"3","name":"mars","number_to_sale":"2","price":"2.00","total":"4.00","created_at":"2014-02-03 21:07:48"},{"pid":"4","name":"shirt","number_to_sale":"1","price":"500.00","total":"500.00","created_at":"2014-02-07 12:05:18"},{"pid":"5","name":"item2","number_to_sale":"4","price":"400.00","total":"1600.00","created_at":"2014-02-12 13:57:49"},{"pid":"6","name":"shirt","number_to_sale":"2","price":"500.00","total":"1000.00","created_at":"2014-02-12 15:42:04"}],"success":1}
[{"totaly":"4108.00"}]
and this is my activity in android
package com.sales;
public class AllSalesActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
AdminJSONParser jParser = new AdminJSONParser();
ArrayList<HashMap<String, String>> salesList;
// url to get all products list
private static String url_all_products = "http://10.0.2.2/android_supplyinfo/sales/get_all_sales.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_SALES = "sales";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_DATE= "created_at";
private static final String TAG_TOTAL_ALL= "totaly";
// products JSONArray
JSONArray sales = null;
JSONArray wtf = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sales_all);
// Hashmap for ListView
salesList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().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 pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditSalesActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
Button btnBacktoMain = (Button)findViewById(R.id.btnBackMain);
btnBacktoMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), DashboardActivity.class);
startActivity(i);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
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(AllSalesActivity.this);
pDialog.setMessage("Loading sales. 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
sales = json.getJSONArray(TAG_SALES);
// looping through All Products
for (int i = 0; i < sales.length(); i++) {
JSONObject c = sales.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String date = c.getString(TAG_DATE);
// 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_DATE, date);
// adding HashList to ArrayList
salesList.add(map);
}
JSONArray wtf = new JSONArray("");
for (int i = 0; i < wtf.length(); i++) {
JSONObject total = wtf.getJSONObject(i);
TextView txtTotal = (TextView) findViewById(R.id.total_all);
txtTotal.setText(total.getString(TAG_TOTAL_ALL));
}
} else {
// no products found
// Launch Add New product Activity
//Intent i = new Intent(getApplicationContext(),
// AddSalesActivity.class);
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//startActivity(i);
}
} 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(
AllSalesActivity.this, salesList,
R.layout.sales_list_item, new String[] { TAG_PID,TAG_NAME,TAG_DATE},new int[] { R.id.pid, R.id.name, R.id.date });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I am not an expert on JSON-objects, but it seems to me that the php page is not returning the "totaly" part inside your JSON-object. If it instead returned it like this:
{"sales":[{"pid":"1","name":"book of eden","number_to_sale":"2","price":"2.00","total":"4.00","created_at":"2014-02-02 11:31:53"},{"pid":"2","name":"shirt","number_to_sale":"2","price":"500.00","total":"1000.00","created_at":"2014-02-03 14:23:49"},{"pid":"3","name":"mars","number_to_sale":"2","price":"2.00","total":"4.00","created_at":"2014-02-03 21:07:48"},{"pid":"4","name":"shirt","number_to_sale":"1","price":"500.00","total":"500.00","created_at":"2014-02-07 12:05:18"},{"pid":"5","name":"item2","number_to_sale":"4","price":"400.00","total":"1600.00","created_at":"2014-02-12 13:57:49"},{"pid":"6","name":"shirt","number_to_sale":"2","price":"500.00","total":"1000.00","created_at":"2014-02-12 15:42:04"}],"success":1, "totaly":"4108.00"}
Then you could get the "totaly" part like your "success":
int success = json.getInt(TAG_SUCCESS);
String totaly = json.getString(TAG_TOTAL_ALL);
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!