I have a Custom ListView which is populated with retrieved from a database. Now, what I can't understand is how to remove an item from the list: searching on Google I've seen different questions without a standard solution, so I have doubts about this. How can I delete a row from a CustomListView also using Async Task?
Here is Leggi_Pizzaiolo activity (where I display the listView):
public class Leggi_Pizzaiolo extends Activity
{
// Progress Dialog
private ProgressDialog pDialog;
public List list = new LinkedList();
// 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/tesina/Leggi_Pizzaiolo.php";
// JSON Node names
private static final String TAG_SUCCESS = "Esito";
private static final String TAG_PRODUCTS = "comande";
private static final String TAG_PID = "ID";
private static final String TAG_NAME = "Nome";
private static final String TAG_TABLE = "Tavolo";
public ListView lv;
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ordini_cuoco);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
// Get listview
lv = (ListView)findViewById(R.id.lista);
new LoadAllProducts().execute();
}
/**
* 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(Leggi_Pizzaiolo.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
int id = c.getInt(TAG_PID);
String name = c.getString(TAG_NAME);
int Tavolo= c.getInt(TAG_TABLE);
list.add(new Comanda(name, id, Tavolo));
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
Listino.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 listview
final ComandaCursorAdapter adapter = new ComandaCursorAdapter(Leggi_Pizzaiolo.this, R.layout.comanda_cuoco, list);
lv.setAdapter(adapter);
}
}
}
This is the CursorAdapter:
public class ComandaCursorAdapter extends ArrayAdapter<Comanda>
{
public ComandaCursorAdapter(Context context, int comandaCuoco, List list) {
super(context, comandaCuoco, list);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.comanda_cuoco, null);
TextView Nome = (TextView)convertView.findViewById(R.id.Comanda);
TextView Tavolo = (TextView)convertView.findViewById(R.id.Tavolo);
TextView Codice = (TextView)convertView.findViewById(R.id.Codice);
Comanda c = getItem(position);
Nome.setText(c.getNome());
Tavolo.setText("Tavolo: " + Integer.toString(c.getTavolo()));
Codice.setText("Codice: " + Integer.toString(c.getCodice()));
return convertView;
}
And this is the object Comanda:
public class Comanda {
private String Nome;
private int Codice;
private int Tavolo;
public Comanda(String Nome, int Codice, int Tavolo)
{
this.Nome = Nome;
this.Codice = Codice;
this.Tavolo = Tavolo;
}
public String getNome()
{
return Nome;
}
public void setNome(String Nome)
{
this.Nome = Nome;
}
public int getCodice()
{
return Codice;
}
public void setCodice(int Codice)
{
this.Codice = Codice;
}
public int getTavolo()
{
return Tavolo;
}
public void setTavolo(int Tavolo)
{
this.Tavolo = Tavolo;
}
}
Now, where I have to declare the setOnItemClickListener in Leggi_Pizzaiolo activity? Should I have to implement a remove method into the class or something? Please let me know how...
Now, what I can't understand is how to remove an item from the list
No, normally create for example OnItemClickListener() to be able to handle click events on ListView. Then in onItemClick() you have parameter int position that returns position of item in Adapter. Now you need to remove item from your List and then perform
list.remove(position)
and then you need to call
adapter.notifyDataSetChanged();
to notify Adapter that datasource has changed.
Note: For more comfort you can show after click on ListItem some AlertDialog with buttons for deleting or not.
Try this
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
where lv is your listview,adb is a dialog, mydataobject is the collection you are using to populate your listview and adapter is your adapter.
Related
I am having a problem on my android application , i am getting data from mysql using JSON Parsing.
When i select a listview item and pass it to another activity it takes a random value instead of the one i have selected.
Here is my code in the listview activity.
public class Outlets extends ListActivity{
// Progress Dialog
private ProgressDialog pDialog;
// testing on Emulator:
private static final String READ_OUTLETS_URL = "http://10.0.2.2:8081/bfc_webservice/outlet_list.php";
// JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_OUTLET_NAME = "outlet_name";
private static final String TAG_SPARKLING_CLASSIFICATION = "sparkling_classification";
private static final String TAG_ID = "id";
private static final String TAG_POSTS= "posts";
private static final String TAG_SPARKLING_CHANNEL = "sparkling_channel";
// An array of all of our comments
private JSONArray mOutlets = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mOutletsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.outlets);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
/*public void addComment(View v) {
Intent i = new Intent(ShowComments.this, PostComment.class);
startActivity(i);
}
*/
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content.
mOutletsList = new ArrayList<HashMap<String, String>>();
// Instantiating the json parser J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
// back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_OUTLETS_URL);
//Catcing Exceptions
try {
//Checking the amount of data rows.
mOutlets = json.getJSONArray(TAG_POSTS);
// looping through the database
for (int i = 0; i < mOutlets.length(); i++) {
JSONObject c = mOutlets.getJSONObject(i);
// gets the content of each tag
String outletname = c.getString(TAG_OUTLET_NAME);
String spark_channel = c.getString(TAG_SPARKLING_CHANNEL);
String spark_class = c.getString(TAG_SPARKLING_CLASSIFICATION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_OUTLET_NAME, outletname);
map.put(TAG_SPARKLING_CHANNEL, spark_channel);
map.put(TAG_SPARKLING_CLASSIFICATION, spark_class);
// adding HashList to ArrayList
mOutletsList.add(map);
// JSON data parsing completed by hash mappings
// list
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this, mOutletsList,
R.layout.single_outlet, new String[] { TAG_OUTLET_NAME, TAG_SPARKLING_CHANNEL,
TAG_SPARKLING_CLASSIFICATION }, new int[] { R.id.outlet_name, R.id.sparkling_channel,
R.id.sparkling_classification });
// I shouldn't have to comment on this one:
setListAdapter(adapter);
// Optional: when the user clicks a list item we
//could do something. However, we will choose
//to do nothing...
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPosition = position;
TextView outname = (TextView)findViewById(R.id.outlet_name);
TextView channel = (TextView)findViewById(R.id.sparkling_channel);
TextView clas = (TextView)findViewById(R.id.sparkling_classification);
String foutname = outname.getText().toString();
String fchannel = channel.getText().toString();
String fclass = clas.getText().toString();
Intent i = new Intent(Outlets.this, ScoreSheet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
startActivity(i);
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Outlets.this);
pDialog.setMessage("Loading Outlets...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
And the code for my next activity is this one.I want just to test if i am getting the correct value using TextViews.
public class ScoreSheet extends Activity{
TextView oname, sch, scls;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.score_sheet);
oname = (TextView)findViewById(R.id.txtoutname);
sch = (TextView)findViewById(R.id.txtspchannel);
scls = (TextView)findViewById(R.id.txtspclass);
Intent myIntent = getIntent();
String ot = myIntent.getStringExtra("outlt");
String ch = myIntent.getStringExtra("chnl");
String cls = myIntent.getStringExtra("cls");
oname.setText(ot);
sch.setText(ch);
scls.setText(cls);
}
}
Your help is so much appreciated forever in my heart guys.Even other methods of doing the same tasks i welcome them.Thank you so much in advance.
Change this
TextView outname = (TextView)findViewById(R.id.outlet_name);
TextView channel = (TextView)findViewById(R.id.sparkling_channel);
TextView clas = (TextView)findViewById(R.id.sparkling_classification);
to
TextView outname = (TextView)view.findViewById(R.id.outlet_name);
TextView channel = (TextView)view.findViewById(R.id.sparkling_channel);
TextView clas = (TextView)view.findViewById(R.id.sparkling_classification);
You need to use the view to find views. Instead of initalizing views you can do as below
The other way
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String,String> map= (HashMap<String, String>) parent.getItemAtPosition(position); // use postion. get the map
String foutname =map.get(TAG_OUTLET_NAME); // get the value using key
String fchannel = map.get(TAG_SPARKLING_CHANNEL);
String fclass = map.get(TAG_SPARKLING_CLASSIFICATION);
...// rest of the code
}
});
Use Following:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPosition = position;
View view1=(View) lv.getItemAtPosition(itemPosition );
TextView outname = (TextView)view1.findViewById(R.id.outlet_name);
TextView channel = (TextView)view1.findViewById(R.id.sparkling_channel);
TextView clas = (TextView)view1.findViewById(R.id.sparkling_classification);
String foutname = outname.getText().toString();
String fchannel = channel.getText().toString();
String fclass = clas.getText().toString();
Intent i = new Intent(Outlets.this, ScoreSheet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
startActivity(i);
}
});
I am getting this error:
The constructor AllProductsActivity.MyAdapter(AllProductsActivity, int, ArrayList<HashMap<String,String>>) is undefined
At this line:
MyAdapter adapter = new MyAdapter(AllProductsActivity.this, R.layout.list_item, productsList);
My best guess is that productsList is the issue, but after about 2 days of trying to understand the code, I haven't figured it out. A lot of the code is from this tutorial and to be honest I don't understand what a hashmap is. - http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
I know it sucks to help people on stack overflow who seem clueless but I could really use a push in the right direction. The HashMap Class Overview is like gibberish to me(http://developer.android.com/reference/java/util/HashMap.html)
Thanks in advance for any help.
Here is my entire AllProductsActivity:
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://mywebsite/mycameraapp/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";
private static final String TAG_DESCRIPTION = "description";
// 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 selecting 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);
}
});
}
/** CALLED WHEN THE USER CLICKS THE RECORD BUTTON */
public void sendMessage(View view) {
Intent videoIntent = new Intent(this, PhotoIntentActivity.class);
startActivity(videoIntent);
}
// 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 trends...");
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);
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
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
* */
MyAdapter adapter = new MyAdapter(AllProductsActivity.this, R.layout.list_item, productsList);
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I actually had MyAdapter in the AllProductsActivity file, but for ease of viewing I'll put it separately here:
public class MyAdapter extends ArrayAdapter<MyItem>{
Context context;
int resourceId;
ArrayList<MyItem> items = null;
LayoutInflater inflater;
public MyAdapter (Context context, int resourceId, ArrayList<MyItem> items)
{
super(context, resourceId, items);
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
final ViewHolder holder;
if (convertView == null){
convertView = inflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.video = (VideoView)convertView.findViewById(R.id.videoView);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
MyItem item = items.get(position);
if (item != null)
{
// This is where you set up the views.
holder.name.setText(TAG_NAME);
Uri myUri = Uri.parse(TAG_DESCRIPTION);
holder.video.setVideoURI(myUri);
holder.video.seekTo(1);
holder.video.setOnTouchListener(
new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event) {
holder.video.start();
holder.video.requestFocus();
return false;
}
}
);
}
return convertView;
}
public class ViewHolder
{
TextView name;
VideoView video;
}
}
You are passing productsList to the constructor which is ArrayList of HashMaps
ArrayList<HashMap<String, String>> productsList;
Also remove runOnUiThread cause onPostExecute is invoked on the ui thread itself.
Your constructor must be.
ArrayList<HashMap<String, String>> items;
public MyAdapter (Context context, int resourceId, ArrayList<HashMap<String, String>> items)
{
super(context, resourceId, items);
this.items =items;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
In getView()
HashMap<String,String> item = (HashMap<String,String> ) items.get(position);
To set text
holder.name.setText(item.get(TAG_NAME));
Also change to
public class MyAdapter extends ArrayAdapter<HashMap<String, String>> {
In my new Android app I have a view with a ListView populated from a JSON call, that is working. But what I need now is a Spinner populated with the same data as the ListView.
But after two days trying to do it, I am not able. The new Spinner id in its layout XML file is spinner2. Spinner1 is populated from a String[] as you can see in the code.
public class HiScreen extends ListActivity {
String[] spinnerValues = { "1","2","3"};
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> newsList;
// url to get all products list
private static String url_all_news = "";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_NEWS = "news";
private static final String TAG_ID = "id";
private static final String TAG_HEADER = "header";
private static final String TAG_BODY = "body";
private static final String TAG_TIME = "time";
// products JSONArray
JSONArray news = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_news);
Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
mySpinner.setAdapter(new MyAdapter(this, R.layout.custom_spinner,
spinnerValues));
Spinner s = (Spinner) findViewById( R.id.spinner2 );
String user,server_url;
Bundle extras = getIntent().getExtras();
// Obtenemos datos enviados en el intent.
if (extras != null) {
user = extras.getString("user");//usuario
server_url = extras.getString("server");
url_all_news = server_url+"android_get_all_news.php";
} else {
user="error";
}
// Hashmap for ListView
newsList = 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
;
}
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context ctx, int txtViewResourceId, String[] objects) {
super(ctx, txtViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
return getCustomView(position, cnvtView, prnt);
}
#Override
public View getView(int pos, View cnvtView, ViewGroup prnt) {
return getCustomView(pos, cnvtView, prnt);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View mySpinner = inflater.inflate(R.layout.custom_spinner, parent,
false);
TextView main_text = (TextView) mySpinner .findViewById(R.id.text_main_seen);
main_text.setText(spinnerValues[position]);
TextView subSpinner = (TextView) mySpinner
.findViewById(R.id.sub_text_seen);
subSpinner.setText(spinnerSubs[position]);
ImageView left_icon = (ImageView) mySpinner
.findViewById(R.id.left_pic);
left_icon.setImageResource(total_images[position]);
return mySpinner;
}
}
// 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(HiScreen.this);
pDialog.setMessage("Loading News. Bitte warten...");
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_news, "GET", params);
// Check your log cat for JSON reponse
Log.d("All News: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
news = json.getJSONArray(TAG_NEWS);
String[] datos = new String[news.length()];
// looping through All Products
for (int i = 0; i < news.length(); i++) {
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
datos[i] = c.getString(TAG_HEADER);
String id = c.getString(TAG_ID);
String header = c.getString(TAG_HEADER);
String body = c.getString(TAG_BODY);
String time = c.getString(TAG_TIME);
// 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_HEADER, header);
map.put(TAG_BODY, body);
map.put(TAG_TIME, time);
// adding HashList to ArrayList
newsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
HiScreen.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(
HiScreen.this, newsList,
R.layout.list_item, new String[] { TAG_ID,
TAG_HEADER,TAG_BODY,TAG_TIME},
new int[] { R.id.pid, R.id.name,R.id.body,R.id.time });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You can create String Array or ArrayList from json, after it you can add it in array adapter so you can easily add data to spinner.
I am using json parser to pass image url and description into my listview. now i managed to load the images but how do i change the text for my list view? currently it just shows item 0, item 1 and so on.. how do i pass the description into the lazyadapter?
Main activity:
public class MainActivity extends Activity {
// CREATING JSON PARSER OBJECT
JSONParser jParser = new JSONParser();
JSONArray guide = null;
ListView list;
LazyAdapter adapter;
String[] mImageIds;
ArrayList<String> guideList =new ArrayList<String>();
ArrayList<String> descriptionList =new ArrayList<String>();
// GUIDE URL
private static String url_guide = "http://58.185.41.178/magazine_android/get_guide.txt";
private static final String TAG_GUIDES = "guides"; //the parent node of my JSON
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_IMAGE = "image";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// LOADING Guide IN BACKGROUND THREAD
new LoadGuide().execute();
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this,guideList);
list.setAdapter(adapter);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
}
#Override
public void onDestroy()
{
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0) {
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadGuide extends AsyncTask<String, String, String> {
/**
* getting All videos 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_guide, "GET", params);
// CHECKING OF JSON RESPONSE
Log.d("All guide: ", json.toString());
try {
guide = json.getJSONArray(TAG_GUIDES);
for (int i = 0; i < guide.length(); i++) {
JSONObject c = guide.getJSONObject(i);
//String title = c.getString(TAG_DESCRIPTION);
String image = c.getString(TAG_IMAGE);
String description = c.getString(TAG_DESCRIPTION);
guideList.add(image);
descriptionList.add(description);
System.out.println(guideList);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// UPDATING UI FROM BACKGROUND THREAD
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter.notifyDataSetChanged();
}
});
}
}
}
Image adapter:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<String> guideList) {
activity = a;
data=guideList;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item, null);
TextView text=(TextView)vi.findViewById(R.id.text);;
ImageView image=(ImageView)vi.findViewById(R.id.image);
text.setText("item "+position);
imageLoader.DisplayImage(data.get(position), image);
return vi;
}
}
In your adapter, you are making the TextView say "item 1", "item 2" etc specifically. What you need to do is add in the Adapter constructor your descriptionList
public LazyAdapter(Activity a, ArrayList<String> guideList, ArrayList<String> descriptionList) {
and then do
text.setText(descriptionList.get(position));
When your activity calls adapter.notifyDataSetChanged(), that forces a re-draw of every item in the list. That will trigger a call into the getView() method your adapter. So your logic belongs in the getView() method:
text.setText(descriptionList.get(position));
Use a single Hashmap for guidelist and descriptionlist and then pass that to the lazyadapter constructor. use the description part of the hashmap in the getview() method to the set the text.
#user1933630
descriptionList.add(description.subString(1,description.length()-1);
I will retrieve student information (id -number- name) from a database (MySQL) as a list view,
each student have 2 buttons (delete - alert ) and radio buttons
screen shot http://im21.gulfup.com/1pWi1.png
Every thing is ok, but how can I make an onClickListener, for example for the delete button
because I try lots of examples, I heard that I can use (custom list or get view or direct onClickListener as in my code (but it is not working ) or Simple Cursor Adapter) I do not know what to use, I looked around for examples that can help me, but in my case but I did not find any so I hope this be reference for anyone have the same problem.
this is my code which I use direct onClick with Simple Adapter
public class ManageSection extends ListActivity {
//ProgresogressDialog pDialog;
private ProgressDialog pDialog;
// Creating JSON Parser object
// Creating JSON Parser object
JSONParser jParser = new JSONParser(); //class
boolean x =true;
Button delete;
ArrayList<HashMap<String, String>> studentList;
//url to get all products list
private static String url_all_student = "http://10.0.2.2/SmsPhp/view_student_info.php";
String cl;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_student = "student";
private static final String TAG_StudentID = "StudentID";
private static final String TAG_StudentNo = "StudentNo";
private static final String TAG_FullName = "FullName";
private static final String TAG_Avatar="Avatar";
HashMap<String, String> selected_student;
// course JSONArray
JSONArray student = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_section);
studentList = new ArrayList<HashMap<String, String>>();
ListView list1 = getListView();
list1.setAdapter(getListAdapter());
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
selected_student =(HashMap<String, String>) studentList.get(pos); //member of your activity.
delete =(Button)view.findViewById(R.id.DeleteStudent);
cl=selected_student.get(TAG_StudentID);
Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
delete.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Log.d("id: ",cl);
Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
}
});
}
});
new LoadAllstudent().execute();
}
/**
* Background Async Task to Load all student by making HTTP Request
* */
class LoadAllstudent extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ManageSection.this);
pDialog.setMessage("Loading student. Please wait...");
pDialog.setIndeterminate(false);
/**
* getting All student from u r l
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_student, "GET", params);
// Check your log cat for JSON response
Log.d("All student : ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
// student found
// Getting Array of course
student = json.getJSONArray(TAG_student);
// looping through All courses
for (int i = 0; i < student.length(); i++)//course JSONArray
{
JSONObject c = student.getJSONObject(i); // read first
// Storing each json item in variable
String StudentID = c.getString(TAG_StudentID);
String StudentNo = c.getString(TAG_StudentNo);
String FullName = c.getString(TAG_FullName);
// String Avatar = c.getString(TAG_Avatar);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_StudentID, StudentID);
map.put(TAG_StudentNo, StudentNo);
map.put(TAG_FullName, FullName);
// adding HashList to ArrayList
studentList.add(map);
}
} else {
x=false;
}
} 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();
if (x==false)
Toast.makeText(getBaseContext(),"no student" ,Toast.LENGTH_LONG).show();
ListAdapter adapter = new SimpleAdapter(
ManageSection.this, studentList,
R.layout.list_student, new String[] { TAG_StudentID,
TAG_StudentNo,TAG_FullName},
new int[] { R.id.StudentID, R.id.StudentNo,R.id.FullName});
setListAdapter(adapter);
// Updating parsed JSON data into ListView
}
}
}
So what do you think, why doesn't the delete button work? There is no error in my log cat. What is the alternative way?
Add your button's onclicklistener outside of your ListView's onclicklistener -
list1.setAdapter(new (youradaptername)(getApplicationContext()));
list1.setOnItemClickListener(detaillistener);
private OnItemClickListener detaillistener = new OnItemClickListener()
{
// to your Onclick action coding here
}
};
just do as same for other buttons.
for more just go to this link here
Just define your button's onclick listener in outside of your ListView's onclicklistener -
delete =(Button)view.findViewById(R.id.DeleteStudent); // initialize this here
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l)
{
selected_student =(HashMap<String, String>) studentList.get(pos); //member of your activity.
cl=selected_student.get(TAG_StudentID);
Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
}
});
delete.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Log.d("id: ",cl);
Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
}
});
From your code it will work when your ListView's item once clicked then only your button will work. So try with above code.
#sara your code is very correct but, it is not working because you havent passed the context properly..!
now use this code it will work for sure :
ListView list1 = getListView();
list1.setAdapter(getListAdapter());
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
selected_student =(HashMap<String, String>) studentList.get(pos); //member of your activity.
delete =(Button)view.findViewById(R.id.DeleteStudent);
cl=selected_student.get(TAG_StudentID);
Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
delete.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Log.d("id: ",cl);
Toast.makeText(ManageSection.this,cl,Toast.LENGTH_LONG).show();
}
});
}
});
i have just added this line to ur code:
Toast.makeText(ManageSection.this,cl,Toast.LENGTH_LONG).show();
now try and tell me if it is working..