How to check and uncheck the Checkbox? - android

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

Related

Adding string before displaying json array

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

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.

Loading image in ListView from Array ID Android

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

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