As if combining checkbox and listview wasn't difficult enough. I've faced this stupid problem: " my list items are suppose to be downloaded from an HTTP request (done) but I don't know now where I should put the checkbox on the code so each list item has its own checkbox and how can I memorize each item was cheacked ". The following are the used code for the HTTP request:
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
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://10.0.2.2:8080/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PID= "name";
private static final String TAG_CATEGORY = "category";
/*private static final String TAG_UNIT = "unit";
private static final String TAG_CALORY = "calory";
private static final String TAG_CARBOHYDRATE = "carbohydrate";
private static final String TAG_CATEGORY = "category";*/
// the array was defined in PHP file
private static final String TAG_PRODUCT = "product";
// 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();
// 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(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// 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);
Log.d("NUN complete","tyt");
}
}
/**
* 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 items. 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
Log.d("All Products: ", json.toString());
products = json.getJSONArray(TAG_PRODUCT);
// 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); // also name
String category = c.getString(TAG_CATEGORY );
// NO NEED FOR THEM !!
/*
String unit = c.getString(TAG_UNIT );
String category = c.getString(TAG_CATEGORY );
String calory = c.getString(TAG_CALORY );
String carbohydrate = c.getString(TAG_CARBOHYDRATE ); */
// 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_CATEGORY, category);
//map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
Log.d("All Products: ", json.toString());
}
} 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;
}
/**
* 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_CATEGORY},
new int[] { R.id.pid, R.id.category});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You can create a custom adapter, where you put all items you got from your HTTP request. and a checkbox per each item, you can use BaseAdapter instead of SimpleAdapter.
Create an xml with the TextView that you are using to display the products and a CheckBox then it will be generated for every item in your list. Just be sure to use a ListView with theandroid:id`
<ListView
android:id=#android:id/list
.../>
or you will get an error.
Also, you shouldn't need runOnUiThread() in onPostExecute() as it already runs on the UI thread
Related
I understand that we cannot set ImageView in AsyncTask. But I need to add the ImageView into HashMap and the HashMap need to add into an ArrayList inside the for loop. I cannot do that in onPostExecute(). Does anyone know how to do?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
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://192.168.1.132/retEqp.php";
ImageView iv;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "equipments";
private static final String TAG_PID = "item_ID";
private static final String TAG_NAME = "item_Name";
private static final String TAG_DESC = "item_Desc";
private static final String TAG_LOC = "item_Location";
private static final String TAG_STATUS = "item_Status";
private static final String TAG_IMAGE = "item_Image";
// products JSONArray
JSONArray equipments = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
iv = (ImageView)findViewById(R.id.img2);
// 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() {
#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 previousScreen = new Intent(getApplicationContext(), NewProductActivity.class);
//Sending the data to NewProductActivity
previousScreen.putExtra("id",pid);
setResult(1000, previousScreen);
finish();
// starting new activity and expecting some response back
}
});
}
// 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(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 {
equipments = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < equipments.length(); i++) {
JSONObject c = equipments.getJSONObject(i);
// Storing each json item in variable
String id = "ID: "+c.getString(TAG_PID);
String name = "Name: "+c.getString(TAG_NAME);
String desc = "Description: "+c.getString(TAG_DESC);
String loc = "Location: "+c.getString(TAG_LOC);
String status = "Status: "+c.getString(TAG_STATUS);
String image = c.getString(TAG_IMAGE);
byte[] rawImage = Base64.decode(image, Base64.DEFAULT);
Bitmap bmp12 = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
iv.setImageBitmap(bmp12);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
// map.put(TAG_IMAGE, rawImage.length);
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESC, desc);
map.put(TAG_LOC, loc);
map.put(TAG_STATUS, status);
map.put(TAG_IMAGE, iv.toString());
// 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_IMAGE,TAG_PID,
TAG_NAME,TAG_DESC,TAG_LOC,TAG_STATUS},
new int[] {R.id.img,R.id.pid, R.id.name,R.id.desc,R.id.loc,R.id.status});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You can't access the UI in a background thread.
The idea behind AsyncTask is that doInBackground does the background work, then you can return something that will be passed as a parameter to onPostExecute which is executed in the main thread.
In this case you have to return the parsed model objects from doInBackground (I would create a custom class), receive in onPostExecute. Also, create a custom adapter, which will take care of creating views. You should generate bitmaps there (probably you have to put the parsing to bitmap in another async task).
i'm trying to build android app which has tab layout which also has listfragment. i want total of three tabs, first home, second listview and third when clicked on listview it switches to third tabs and show some information all using json parsing.
i'm using this tutorials as a reference http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/
and for listview i'm using following - http://www.androidhive.info/2012/10/android-multilevel-listview-tutorial/
Now the question is that how can i change listActivity to listFragment?
How can i turn this code from Listactivity to Listfragment?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.androidhive.helper.AlertDialogManager;
import com.example.androidhive.helper.ConnectionDetector;
import com.example.androidhive.helper.JSONParser;
public class AlbumsActivity extends ListActivity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> albumsList;
// albums JSONArray
JSONArray albums = null;
// albums JSON url
private static final String URL_ALBUMS = "http://api.androidhive.info/songs/albums.php";
// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SONGS_COUNT = "songs_count";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
ListView lv = getListView();
/**
* Listview item click listener
* TrackListActivity will be lauched by passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
// TrackListActivity will be launched to show tracks inside the album
Intent i = new Intent(getApplicationContext(), TrackListActivity.class);
// send album id to tracklist activity to get list of songs under that album
String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
i.putExtra("album_id", album_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AlbumsActivity.this);
pDialog.setMessage("Listing Albums ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Albums JSON: ", "> " + json);
try {
albums = new JSONArray(json);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String songs_count = c.getString(TAG_SONGS_COUNT);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_SONGS_COUNT, songs_count);
// adding HashList to ArrayList
albumsList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} 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 albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AlbumsActivity.this, albumsList,
R.layout.list_item_albums, new String[] { TAG_ID,
TAG_NAME, TAG_SONGS_COUNT }, new int[] {
R.id.album_id, R.id.album_name, R.id.songs_count });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I've got such code:
public class ListaPrzepisow extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> recipesList;
// url to get all recipes list
private static String url_all_recipes = "http://web.onlyway.pl/wolowinkadb/get_all_recipes.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_recipeS = "recipes";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_AUTOR= "autor";
private static final String TAG_FOTKA= "zdjecie";
// recipes JSONArray
JSONArray recipes = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
recipesList = new ArrayList<HashMap<String, String>>();
// Loading recipes in Background Thread
new LoadAllrecipes().execute();
// Get listview
ListView lv = getListView();
// on seleting single recipe
// launching Edit recipe 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(),
EditrecipeActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
*/
}
// Response from Edit recipe 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 recipe
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all recipe by making HTTP Request
* */
class LoadAllrecipes extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListaPrzepisow.this);
pDialog.setMessage("Loading recipes. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All recipes 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_recipes, "GET", params);
// Check your log cat for JSON reponse
Log.d("All recipes: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// recipes found
// Getting Array of recipes
recipes = json.getJSONArray(TAG_recipeS);
// looping through All recipes
for (int i = 0; i < recipes.length(); i++) {
JSONObject c = recipes.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String autor = c.getString(TAG_AUTOR);
String fotka = c.getString(TAG_FOTKA);
// 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_AUTOR, autor);
map.put(TAG_FOTKA, fotka);
// adding HashList to ArrayList
recipesList.add(map);
}
} else {
// no recipes found
// Launch Add New recipe Activity
Intent i = new Intent(getApplicationContext(),
ListaPrzepisow.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 recipes
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ListaPrzepisow.this, recipesList,
R.layout.recipeslist_layout, new String[] { TAG_PID,
TAG_NAME, TAG_AUTOR, TAG_FOTKA},
new int[] { R.id.pid, R.id.name, R.id.Author, R.id.Thumb });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
In String fotka = c.getString(TAG_FOTKA); i have url to image. how exactly I can put it into my image view. Forexample using this lib:https://github.com/koush/UrlImageViewHelper.
I've tried on many way do that but I've stuck
Ok I've helped myself. I've added my on adapter that extends SimpleAdapter like this:
package com.app.beefmania;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
public class MyAdapter extends SimpleAdapter {
public MyAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
// TODO Auto-generated constructor stub
}
#Override
public void setViewImage(ImageView v, String value) {
UrlImageViewHelper.setUrlDrawable(v, value);
}
}
And everything working grate with my previus code ;)
This tutorial shows how to display data from database in a listview. I did that, and now I would like to refresh a listview when new data is entered in the database. If I exit the app, and enter again, new data will be displayed, but how to refresh listview with new data while you are watching listview?
AllProductsActivity.java
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
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.androidhive.info/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;
#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();
// 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(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// 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(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 {
// 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);
}
} 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;
}
/**
* 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);
}
});
}
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/pid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
</LinearLayout>
all_products.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
get_all_products.php
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM products") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["price"] = $row["price"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
Only one way you need to call it again.
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
use notifyDataSetChanged() , this will notify the adapter and will change the listview data.
please could you help me to found what is the problem with the following code !
when the item from spinner selected nothing occurs
i.e : the body of spinner.setOnItemSelectedListener is not seen !
code :
package com.example.spinner;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import java.util.HashMap;
import org.apache.http.NameValuePair;
import org.json.JSONException;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
public class MainActivity extends Activity {
// 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://10.0.2.2/RPM-connect/get_all_patients.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_DOCTOR = "products";
private static final String TAG_ID = "id";
private static final String TAG_F_NAME = "F_name";
private static final String TAG_S_NAME = "S_name";
private static final String TAG_L_NAME = "L_name";
// products JSONArray
JSONArray doctor = null;
ArrayList<String> spinnerArray ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
spinnerArray = new ArrayList<String>();
// Loading products in Background Thread
new LoadAllProducts().execute();
Spinner spinner = new Spinner(this);
//ArrayAdapter <HashMap<String, String>> spinnerArrayAdapter = new ArrayAdapter<HashMap<String, String>>(
ArrayAdapter <String> spinnerArrayAdapter = new ArrayAdapter <String >(
this, android.R.layout.simple_spinner_item, spinnerArray );
spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
spinner = (Spinner) findViewById( R.id.spinner1 );
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "You have selected : " ,
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
} );
}
// 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) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
#SuppressLint("NewApi")
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* 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
doctor = json.getJSONArray(TAG_DOCTOR);
// looping through All Products
for (int i = 0; i < doctor.length(); i++) {
JSONObject c = doctor.getJSONObject(i);
// Storing each json item in variable
String ID = c.getString(TAG_ID);
String F_name = c.getString(TAG_F_NAME);
String S_name = c.getString(TAG_S_NAME);
String L_name = c.getString(TAG_L_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, ID);
map.put(TAG_F_NAME, F_name);
map.put(TAG_S_NAME, S_name);
map.put(TAG_L_NAME, L_name);
// adding HashList to ArrayList
productsList.add(map);
Log.d("Before temp", productsList.toString());
spinnerArray.add(F_name + " " + L_name);
// temp[i]= F_name+" "+L_name ;
Log.d("TT",spinnerArray.get(i) );
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
Your ArrayList may not be populated from the AsyncTask before you set the adapter. Implement onPostExecute() in your AsyncTask and call notifyDataSetChanged() on your adapter there. Also, you create a new Spinner then use one that exists in your xml
Spinner spinner = new Spinner(this);
this is not needed. Just declare your Spinner like this
public class MainActivity extends Activity {
Spinner spinner;
then initialize it from xml as you are doing later
spinner = (Spinner) findViewById( R.id.spinner1 );
notifyDataSetChanged() Docs
After your done with loading the items into the SpinnerAdapter inside your AsyncTask you need to tell the Adapter to refresh itself to load the new values.
This can be done by calling: spinnerArrayAdapter.notifyDataSetChanged().
Because the AsyncTask is running on another thread, you will need to implement
#Override
public void onPostExecute(String result) {
spinnerArrayAdapter.notifyDataSetChanged()
}
and call the spinnerArrayAdapter.notifyDataSetChanged() inside it, as seen above.
onPostExecute and onPreExecute is run on the main thread, so they can change Views on the UI thread.