delete multiple items in custom listview - android

I want to create a custom listview in which every single row has a textview and an imageview(which i'll use to check/uncheck the list items) as shown in the following figure:
I want to delete multiple items from the list. How to achieve this ?? Can you please provide any tutorial or reference or link to learn this ??

This is how i created my custom listview with ease:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DeleteData extends Activity {
Cursor cursor;
ListView lv_delete_data;
static ArrayList<Integer> listOfItemsToDelete;
SQLiteDatabase database;
private Category[] categories;
ArrayList<Category> categoryList;
private ArrayAdapter<Category> listAdapter;
ImageView iv_delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_data);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
manage_reload_list();
listOfItemsToDelete = new ArrayList<Integer>();
iv_delete = (ImageView) findViewById(R.id.imageViewDeleteDataDelete);
iv_delete.setClickable(true);
iv_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
}
else {
showDialog(
"Warning",
"Are you sure you want to delete these categories ? This will erase all records attached with it.");
}
}
});
lv_delete_data = (ListView) findViewById(R.id.listViewDeleteData);
lv_delete_data.setAdapter(listAdapter);
lv_delete_data.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) arg1
.findViewById(R.id.imageViewSingleRowDeleteData);
Category category = (Category) imageView.getTag();
if (category.getChecked() == false) {
imageView.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageView.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
}
private void showDialog(final String title, String message) {
AlertDialog.Builder adb = new Builder(DeleteData.this);
adb.setTitle(title);
adb.setMessage(message);
adb.setIcon(R.drawable.ic_launcher);
String btn = "Ok";
if (title.equals("Warning")) {
btn = "Yes";
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
adb.setPositiveButton(btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
if (title.equals("Warning")) {
for (int i : listOfItemsToDelete) {
// -------first delete from category table-----
database.delete("category_fields", "cat_id=?",
new String[] { i + "" });
// --------now fetch rec_id where cat_id =
// i-----------------
cursor = database.query("records_data",
new String[] { "rec_id" }, "cat_id=?",
new String[] { i + "" }, null, null, null);
if (cursor.getCount() == 0)
cursor.close();
else {
ArrayList<Integer> al_tmp_rec_id = new ArrayList<Integer>();
while (cursor.moveToNext())
al_tmp_rec_id.add(cursor.getInt(0));
cursor.close();
for (int i1 : al_tmp_rec_id) {
database.delete("records_fields_data",
"rec_id=?", new String[] { i1 + "" });
database.delete("record_tag_relation",
"rec_id=?", new String[] { i1 + "" });
}
// ---------delete from records_data-------
database.delete("records_data", "cat_id=?",
new String[] { i + "" });
cursor.close();
}
}
showDialog("Success",
"Categories, with their records, deleted successfully.");
} else {
database.close();
listOfItemsToDelete.clear();
manage_reload_list();
lv_delete_data.setAdapter(listAdapter);
}
}
});
AlertDialog ad = adb.create();
ad.show();
}
protected void manage_reload_list() {
loadDatabase();
categoryList = new ArrayList<Category>();
// ------first fetch all categories name list-------
cursor = database.query("category", new String[] { "cat_id",
"cat_description" }, null, null, null, null, null);
if (cursor.getCount() == 0) {
Toast.makeText(getBaseContext(), "No categories found.",
Toast.LENGTH_SHORT).show();
cursor.close();
} else {
while (cursor.moveToNext()) {
categories = new Category[] { new Category(cursor.getInt(0),
cursor.getString(1)) };
categoryList.addAll(Arrays.asList(categories));
}
cursor.close();
}
listAdapter = new CategoryArrayAdapter(this, categoryList);
}
static class Category {
String cat_name = "";
int cat_id = 0;
Boolean checked = false;
Category(int cat_id, String name) {
this.cat_name = name;
this.cat_id = cat_id;
}
public int getId() {
return cat_id;
}
public String getCatName() {
return cat_name;
}
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
public void toggleChecked() {
checked = !checked;
}
}
static class CategoryViewHolder {
ImageView imageViewCheck;
TextView textViewCategoryName;
public CategoryViewHolder(ImageView iv_check, TextView tv_category_name) {
imageViewCheck = iv_check;
textViewCategoryName = tv_category_name;
}
public ImageView getImageViewCheck() {
return imageViewCheck;
}
public TextView getTextViewCategoryName() {
return textViewCategoryName;
}
}
static class CategoryArrayAdapter extends ArrayAdapter<Category> {
LayoutInflater inflater;
public CategoryArrayAdapter(Context context, List<Category> categoryList) {
super(context, R.layout.single_row_delete_data,
R.id.textViewSingleRowDeleteData, categoryList);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Category category = (Category) this.getItem(position);
final ImageView imageViewCheck;
final TextView textViewCN;
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_row_delete_data,
null);
imageViewCheck = (ImageView) convertView
.findViewById(R.id.imageViewSingleRowDeleteData);
textViewCN = (TextView) convertView
.findViewById(R.id.textViewSingleRowDeleteData);
convertView.setTag(new CategoryViewHolder(imageViewCheck,
textViewCN));
}
else {
CategoryViewHolder viewHolder = (CategoryViewHolder) convertView
.getTag();
imageViewCheck = viewHolder.getImageViewCheck();
textViewCN = viewHolder.getTextViewCategoryName();
}
imageViewCheck.setFocusable(false);
imageViewCheck.setFocusableInTouchMode(false);
imageViewCheck.setClickable(true);
imageViewCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView iv = (ImageView) v;
Category category = (Category) iv.getTag();
if (category.getChecked() == false) {
imageViewCheck.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageViewCheck
.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
imageViewCheck.setTag(category);
if (category.getChecked() == true)
imageViewCheck.setImageResource(R.drawable.set_check);
else
imageViewCheck.setImageResource(R.drawable.set_basecircle);
textViewCN.setText(category.getCatName());
return convertView;
}
}
private void loadDatabase() {
database = openOrCreateDatabase("WalletAppDatabase.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Anyone who have doubts in this can ask me...

Fisrt of all make a custom adapter and row layout for your listview. Follow this link (click) for that.Then add check-box to each row.You can customize check-box to achieve like the image you have posted.To do that, check this link (click)
After creating your custom listview, you have to get the checked listview row id on checkbox click in custom adapter(inside getview method).When the user click a checkbox you have to get the clicked row id and store into an array list.Lets say, your selected id-array list is "ArrayId" and your listview items array list is "Yourarray". here is the code,
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked)
{
ArrayId.add(Yourlist.get(position));//add item position to arraylist if checked
}
else
{
ArrayId.remove(Yourlist.get(position));//remove item position from arraylist if unchecked
}
}
}
Then you loop through each id stored in arraylist and delete the entry.Check the code below,
for(int i=0;i<ArrayId.size();i++)
{
Yourlist.remove(ArrayId[i]);
}
Now the items from your listview items array-"Yourlist" will be removed.Then invalidate the listview with updated "Yourlist" array.

Related

How to get gridview multiple positions and store into array variable

Now I am displaying images in grid-view, it working fine. In that grid-view i am going to select few images, i want store selected multiple images position in array variable (example: if i select position 1, 4 ,10. i want that particular position id and i want to store it array like 1,4,10,15,). I will put my activity and adapter code below. Thank you in advance.
Activity
public class EM_event_total_userSeats extends AppCompatActivity implements RestCallback,AdapterView.OnItemClickListener {
String user_id,first_name,last_name,name,emailid,contact_no,gender1,date_of_birth,country_id,postal_code,rolename,profession_response,Street_Address,City,photo;
GridView GridUserSeats;
;
TextView textView1,textView2,Tvposition;
ImageView Ivseats;
public static EM_event_total_userseatsAdapter adapter;
ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist;
View savedView;
View previous = null;
String event_id = "EVEPRI62";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.em_event_total_user_seats);
initviews();
callSeatsApi();
GridUserSeats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
String a = String.valueOf(position);
Toast.makeText(EM_event_total_userSeats.this, a + "#Selected", Toast.LENGTH_SHORT).show();
v.setBackgroundColor(Color.GREEN);
adapter.notifyDataSetChanged();
}
});
}
private void initviews() {
GridUserSeats=(GridView)findViewById(R.id.GridUserSeats);
GridUserSeats.setOnItemClickListener(this);
textView1=(TextView) findViewById(R.id.textView1);
// textView2=(TextView) findViewById(R.id.textView2);
Intent intent = getIntent();
first_name = intent.getStringExtra("first_name");
last_name = intent.getStringExtra("last_name");
}
private void callSeatsApi() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("events", event_id);
RestService.getInstance(EM_event_total_userSeats.this).getUserSeats(map, new MyCallback<ArrayList<EM_event_total_UserSeatsModel>>(EM_event_total_userSeats.this,
EM_event_total_userSeats.this, true, "Finding seats....", GlobalVariables.SERVICE_MODE.EM_SEATS));
}
#Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {
}
#Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode)
{
switch (mode)
{
case EM_SEATS:
EMeventuserseatslist = (ArrayList<EM_event_total_UserSeatsModel>)response.body();
adapter = new EM_event_total_userseatsAdapter(EMeventuserseatslist, getApplicationContext());
GridUserSeats.setAdapter(adapter);
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import cfirst.live.com.R;
import cfirst.live.com.model.BasketModel;
import cfirst.live.com.model.EM_event_total_UserSeatsModel;
public class EM_event_total_userseatsAdapter extends ArrayAdapter<EM_event_total_UserSeatsModel> implements View.OnClickListener {
ArrayList<EM_event_total_UserSeatsModel> dataSet;
public ArrayList<EM_event_total_UserSeatsModel> EMeventuserseatslist = new ArrayList<EM_event_total_UserSeatsModel>();
Context mContext;
ViewHolder holder;
String user_seats;
private int[] tagCollection;
private String[] mobileValues;
private String[] mobileValuesD;
private static class ViewHolder {
TextView TvEmUserSeats;
ImageView IvUsreSeats,available,selctedimag;
}
private String[] strings;
List<Integer> selectedPositions = new ArrayList<>();
public EM_event_total_userseatsAdapter(ArrayList<EM_event_total_UserSeatsModel> data, Context context) {
super(context, R.layout.list_em_get_seats, data);
this.dataSet = data;
this.mContext=context;
}
public int getTagFromPosition(int position) {
return tagCollection[position];
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(tagCollection[position]);
EM_event_total_UserSeatsModel dataModel=(EM_event_total_UserSeatsModel) object;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
EM_event_total_UserSeatsModel dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_em_get_seats, parent, false);
viewHolder.TvEmUserSeats = (TextView) convertView.findViewById(R.id.TvEmUserSeats);
viewHolder.IvUsreSeats = (ImageView) convertView.findViewById(R.id.IvUsreSeats);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
String blue_available = "seat3.png";
String red_booked = "seat1.png";
String get_seat = dataModel.getBookedStatus();
viewHolder.TvEmUserSeats.setText(dataModel.getSeatName());
if(Integer.parseInt(get_seat) == 1){
Picasso.with(mContext).load("imageurl + red_booked).into(viewHolder.IvUsreSeats);
}else
{
Picasso.with(mContext).load("imageurl + blue_available).into(viewHolder.IvUsreSeats);
}
return convertView;
}
}
It's simple. You can use SparseBooleanArray for this purpose. Just add the following methods as is in your adapter:
public void toggleSelection(int item) {
if (selectedItems.get(item, false)) {
selectedItems.delete(item);
} else {
selectedItems.put(item, true);
}
notifyDataSetChanged();
}
public void setSelectedItems(List<Object> objects) {
if (objects != null) {
for (Object object : objects) {
toggleSelection(object.getId());
}
notifyDataSetChanged();
}
}
public void clearSelections() {
selectedItems.clear();
notifyDataSetChanged();
}
public int getSelectedItemCount() {
return selectedItems.size();
}
public List<Integer> getSelectedItems() {
List<Integer> items =
new ArrayList<Integer>(selectedItems.size());
for (int i = 0; i < selectedItems.size(); i++) {
items.add(selectedItems.keyAt(i));
}
return items;
}
Use the set selection method to store the selected status of your item.
Don't forget to initialize SparseBooleanArray in your constructor.
SparseBooleanArray SparseBooleanArray = new SparseBooleanArray();
After that, use toggleSelection(position); to change the selected status of an item, then after performing selections, call getSelectedItem() to get the selected items in an array.
// create an Arraylist and add the selected position in a list
List <int> selectedArray = new ArrayList<>();
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int click = (int) parent.getItemAtPosition(position);
selectedArray.add(click);
}

How to send checked multiple contacts from list view to another layout in android studio

I retrieved the contacts from phone and I have selected the multiple contacts. I need to send that selected contacts into next class in android studio.i have tried to send that data but it displayed a blank page. How to display selected contacts into next page. My MainActivity is :
package com.example.vijayasrivudanti.contact;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ContactDetails extends AppCompatActivity implements View.OnClickListener {
ListView mainListView;
Contact[] contact_read;
Cursor mCursor;
ArrayAdapter<Contact> listAdapter;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_details);
b=(Button)findViewById(R.id.done);
b.setOnClickListener(this);
mainListView = (ListView) findViewById(R.id.listview);
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
Contact con = listAdapter.getItem(position);
con.toggleChecked();
ContactViewHolder viewHolder = (ContactViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(con.isChecked());
}
});
String[] projection = new String[] { ContactsContract.Contacts.HAS_PHONE_NUMBER,
ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };
mCursor = managedQuery(ContactsContract.Contacts.CONTENT_URI, projection,
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" },
ContactsContract.Contacts.DISPLAY_NAME);
if (mCursor != null) {
mCursor.moveToFirst();
contact_read = new Contact[mCursor.getCount()];
// Add Contacts to the Array
int j = 0;
do {
contact_read[j] = new Contact(mCursor.getString(mCursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
j++;
} while (mCursor.moveToNext());
} else {
System.out.println("Cursor is NULL");
}
// Add Contact Class to the Arraylist
ArrayList<Contact> contactList = new ArrayList<Contact>();
contactList.addAll(Arrays.asList(contact_read));
// Set our custom array adapter as the ListView's adapter.
//listAdapter = new ArrayAdapter<Contact>(this,android.R.layout.simple_list_item_multiple_choice,contactList);
listAdapter = new ContactArrayAdapter(this,contactList);
mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mainListView.setAdapter(listAdapter);
}
#Override
public void onClick(View view) {
SparseBooleanArray checked = mainListView.getCheckedItemPositions();
ArrayList<Contact> selectedContacts = new ArrayList<Contact>();
for(int i = 0;i < checked.size();i++){
int position = checked.keyAt(i);
if(checked.valueAt(i))
selectedContacts .add(listAdapter.getItem(position));
}
String[] outputStrArr = new String[selectedContacts.size()];
for (int i =0;i < selectedContacts.size();i++)
{
outputStrArr[i] = String.valueOf(selectedContacts.get(i));
}
Intent i = new Intent(ContactDetails.this,Display.class);
Bundle b = new Bundle();
b.putStringArray("selectedContacts",outputStrArr);
i.putExtras(b);
startActivity(i);
Toast.makeText(this,"selectedcontacts",Toast.LENGTH_LONG).show();
}
/** Holds Contact data. */
#SuppressWarnings("unused")
public static class Contact {
private String name = "";
private boolean checked = false;
public Contact() {
}
public Contact(String name) {
this.name = name;
}
public Contact(String name, boolean checked) {
this.name = name;
this.checked = checked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String toString() {
return name;
}
public void toggleChecked() {
checked = !checked;
}
}
/** Holds child views for one row. */
#SuppressWarnings("unused")
private static class ContactViewHolder {
private CheckBox checkBox;
private TextView textView;
public ContactViewHolder() {
}
public ContactViewHolder(TextView textView, CheckBox checkBox) {
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public TextView getTextView() {
return textView;
}
public void setTextView(TextView textView) {
this.textView = textView;
}
}
/** Custom adapter for displaying an array of Contact objects. */
private static class ContactArrayAdapter extends ArrayAdapter<Contact> {
private LayoutInflater inflater;
public ContactArrayAdapter(Context context, List<Contact> contactList) {
super(context, R.layout.simplerow, R.id.rowTextView, contactList);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Contact to display
Contact cont = (Contact) this.getItem(position);
System.out.println(String.valueOf(position));
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null) {
convertView = inflater.inflate(R.layout.simplerow, null);
// Find the child views.
textView = (TextView) convertView
.findViewById(R.id.rowTextView);
checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);
// Optimization: Tag the row with it's child views, so we don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new ContactViewHolder(textView, checkBox));
// If CheckBox is toggled, update the Contact it is tagged with.
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Contact contact = (Contact) cb.getTag();
contact.setChecked(cb.isChecked());
}
});
}
// Reuse existing row view
else {
// Because we use a ViewHolder, we avoid having to call
// findViewById().
ContactViewHolder viewHolder = (ContactViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the Contact it is displaying, so that we
// can
// access the Contact in onClick() when the CheckBox is toggled.
checkBox.setTag(cont);
// Display Contact data
checkBox.setChecked(cont.isChecked());
textView.setText(cont.getName());
return convertView;
}
}
}
My next layout to display selected contacts is:
public class Display extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Bundle b = getIntent().getExtras();
String[] resultArr = b.getStringArray("selectedContacts");
ListView lv = (ListView)findViewById(R.id.outputList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,resultArr);
lv.setAdapter(adapter);
}
}

Cannot remove item from Shopping Cart android studio

I referred [this][1] and [this][2] site and tried to modify it according to my own needs. Problem is I can't remove an item from the cart. I have tried everything including searching for solutions in stackoverflow and google but no luck.
Here is my CatalogActivity.java
package com.comlu.sush.shoppingcart;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import java.util.List;
public class CatalogActivity extends AppCompatActivity {
private List<Product> mProductList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false,false));
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
startActivity(productDetailsIntent);
}
});
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
}
ShoppingCartHelper.java
package com.comlu.sush.shoppingcart;
import android.content.res.Resources;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
public class ShoppingCartHelper {
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
private static List<Product> catalog;
private static Map<Product, ShoppingCartEntry> cartMap = new HashMap<Product, ShoppingCartEntry>();
public static List<Product> getCatalog(Resources res){
if(catalog == null) {
catalog = new Vector<Product>();
catalog.add(new Product("Dead or Alive", res
.getDrawable(R.drawable.first),
"Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
catalog.add(new Product("Switch", res
.getDrawable(R.drawable.second),
"Switch by Chip Heath and Dan Heath", 24.99));
catalog.add(new Product("Watchmen", res
.getDrawable(R.drawable.third),
"Watchmen by Alan Moore and Dave Gibbons", 14.99));
}
return catalog;
}
public static void setQuantity(Product product, int quantity) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
// If the quantity is zero or less, remove the products
if(quantity <= 0) {
if(curEntry != null)
removeProduct(product);
return;
}
// If a current cart entry doesn't exist, create one
if(curEntry == null) {
curEntry = new ShoppingCartEntry(product, quantity);
cartMap.put(product, curEntry);
return;
}
// Update the quantity
curEntry.setQuantity(quantity);
}
public static int getProductQuantity(Product product) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
if(curEntry != null)
return curEntry.getQuantity();
return 0;
}
public static void removeProduct(Product product) {
cartMap.remove(product);
}
public static List<Product> getCartList() {
List<Product> cartList = new Vector<Product>(cartMap.keySet().size());
for(Product p : cartMap.keySet()) {
cartList.add(p);
}
return cartList;
}
}
ShoppingCartActiity.java
package com.comlu.sush.shoppingcart;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import java.util.List;
public class ShoppingCartActivity extends AppCompatActivity {
private List<Product> mCartList;
private ProductAdapter mProductAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
mCartList = ShoppingCartHelper.getCartList();
// Make sure to clear the selections
for(int i=0; i<mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true,true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mProductAdapter.toggleSelection(position);
}
});
removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProductAdapter.removeSelected();
}
});
}
#Override
protected void onResume() {
super.onResume();
// Refresh the data
if(mProductAdapter != null) {
mProductAdapter.notifyDataSetChanged();
}
}
}
ProductDetailsActivity.java
package com.comlu.sush.shoppingcart;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class ProductDetailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
final int result=0;
List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());
int productIndex = getIntent().getExtras().getInt(
ShoppingCartHelper.PRODUCT_INDEX);
final Product selectedProduct = catalog.get(productIndex);
// Set the proper image and text
ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
productImageView.setImageDrawable(selectedProduct.productImage);
TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
productTitleTextView.setText(selectedProduct.title);
TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
productDetailsTextView.setText(selectedProduct.description);
// Update the current quantity in the cart
TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
textViewCurrentQuantity.setText("Currently in Cart: "
+ ShoppingCartHelper.getProductQuantity(selectedProduct));
// Save a reference to the quantity edit text
final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);
Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
addToCartButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check to see that a valid quantity was entered
int quantity = 0;
try {
quantity = Integer.parseInt(editTextQuantity.getText()
.toString());
if (quantity < 0) {
Toast.makeText(getBaseContext(),
"Please enter a quantity of 0 or higher",
Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Please enter a numeric quantity",
Toast.LENGTH_SHORT).show();
return;
}
// If we make it here, a valid quantity was entered
ShoppingCartHelper.setQuantity(selectedProduct, quantity);
// Close the activity
finish();
}
});
}
}
ProductAdapter.java
package com.comlu.sush.shoppingcart;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
private boolean mShowCheckbox;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity, boolean showCheckbox) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
mShowCheckbox = showCheckbox;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();
item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);
item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);
item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);
item.productCheckbox = (CheckBox) convertView.findViewById(R.id.CheckBoxSelected);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
Product curProduct = mProductList.get(position);
item.productImageView.setImageDrawable(curProduct.productImage);
item.productTitle.setText(curProduct.title);
if(!mShowCheckbox) {
item.productCheckbox.setVisibility(View.GONE);
} else {
if(curProduct.selected == true)
item.productCheckbox.setChecked(true);
else
item.productCheckbox.setChecked(false);
}
// Show the quantity in the cart or not
if (mShowQuantity) {
item.productQuantity.setText("Quantity: "
+ ShoppingCartHelper.getProductQuantity(curProduct));
} else {
// Hid the view
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
public void toggleSelection(int position) {
Product selectedProduct = (Product) getItem(position);
if(selectedProduct.selected) { // no need to check " == true"
selectedProduct.selected = false;
}
else {
selectedProduct.selected = true;
}
notifyDataSetInvalidated();
}
public void removeSelected() {
for(int i=mProductList.size()-1; i>=0; i--) {
if(mProductList.get(i).selected) {
mProductList.remove(i);
}
}
notifyDataSetChanged();
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
CheckBox productCheckbox;
}
}
You should move data manipulation to the adapter, and design-wise it would make sense and might also fix the problem you're telling us.
Write this method in your ProductAdapter:
public void removeSelected() {
for(int i = mProductList.size()-1; i >= 0; i--) {
if(mProductList.get(i).selected) {
mProductList.remove(i);
}
}
notifyDataSetChanged();
}
Update your OnClickListener (in your ShoppingCartActiity of course):
removeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mProductAdapter.removeSelected();
}
});
Edit
I noticed that you aren't applying OOP's concept of encapsulation here. That is, ShoppingCartActiity shouldn't be making changes to the data which belongs to your adapter.
So, just create public methods inside the ProductAdapter for item for selection, etc and call them from ShoppingCartActiity as needed.
Copy this method in your ProductAdapter:
public void toggleSelection(int position) {
Product selectedProduct = (Product) getItem(position);
if(selectedProduct.selected) { // no need to check " == true"
selectedProduct.selected = false;
}
else {
selectedProduct.selected = true;
}
notifyDataSetInvalidated();
}
mProductAdapter.toggleSelection(position); will replace following code ShoppingCartActiity:
Product selectedProduct = mCartList.get(position);
if(selectedProduct.selected == true)
selectedProduct.selected = false;
else
selectedProduct.selected = true;
mProductAdapter.notifyDataSetInvalidated();
Edit2
The problem is that the ShoppingCartActiity takes items from ShoppingCartEntry on starting up, but it never writes back the changes to it when you remove items.
update your removeButton's onClick() to:
mProductAdapter.removeSelected();
if (product.selected) {
// set products which are remaining in the adapter
ShoppingCartHelper.setProducts(mProductAdapter.getProducts());
}
ShoppingCartHelper.setProducts() would replace the old data with the passed one:
public static void setProducts(ArrayList<Product> products) {
catalog = new Vector<Product>();
for (Product product : products) {
catalog.add(product);
}
}
mProductAdapter.getProducts() will just return the list of Products, like:
public List<Product> getProducts() {
return mProductList;
}
you just have to remove selected item from list, and after adapter.notifiyDataSetChanged() it will refresh the adapter.
removeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Loop through and remove all the products that are selected
// Loop backwards so that the remove works correctly
for(int i=mCartList.size()-1; i>=0; i--) {
if(mCartList.get(i).selected) {
mCartList.remove(i);
//mProductAdapter.removeSelected();
}
}
if(mProductAdapter!=null)
mProductAdapter.notifyDataSetChanged();
}
});

Adding and removing the item into wish list like flipkart

I want to add / remove the item into wishlist. I am getting one response from Api, so in that i have one tag is_wishlist=true/false, when I am launching an application based on that value I am showing its in wishlist by changing an icon, but now issue is if am changing that wishlist status like from adding to remobing to adding, in Api i am getting response sucessfully, but i am unable to change the icons. This is my code. can any one help me how to remove or add items into wishlist
package com.example.user.smgapp;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.List;
public class Prd_grid_adapter extends BaseAdapter {
List<HashMap<String, String>> Category_listData;
HashMap<String, String> map;
Context context;
Typeface face;
String wishList_url, remove_wishList_url;
Cursor cursor;
NavigationDrawer nav = new NavigationDrawer();
private static LayoutInflater inflater = null;
public Prd_grid_adapter(Activity context, List<HashMap<String, String>> aList) {
// TODO Auto-generated constructor stub
Category_listData = aList;
/*/for(int i=1;i<aList.size();i++)
{
Category_listData.add(aList.get(i));
}*/
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Category_listData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView name, price, original_price;
ImageView img, wish_list;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
final View rowView;
this.face = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
rowView = inflater.inflate(R.layout.grid_item_view, null);
holder.name = (TextView) rowView.findViewById(R.id.p_name);
holder.img = (ImageView) rowView.findViewById(R.id.p_img);
holder.wish_list = (ImageView) rowView.findViewById(R.id.wish_list);
holder.price = (TextView) rowView.findViewById(R.id.p_price);
holder.original_price = (TextView) rowView.findViewById(R.id.orginal_p);
map = Category_listData.get(position);
holder.name.setTypeface(face);
holder.name.setText(map.get("product_name"));
Log.e("wish list staus..", "wishlist status.." + map.get("is_wishlist"));
if (map.get("is_wishlist").equals("0")) {
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
} else {
holder.wish_list.setImageResource(R.drawable.wishlist);
}
holder.wish_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SingletonActivity.custidstr.isEmpty()) {
Toast.makeText(context, "Ur not logged in,Please Login", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Alert!");
builder.setMessage("Ur not logged in")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(context, Login.class);
context.startActivity(intent);
}
});
// Create the AlertDialog object and return it
builder.show();
} else {
wishList_url = SingletonActivity.API_URL + "api/add_wishlist.php?customer_id=" + SingletonActivity.custidstr + "&product_id=" + Category_listData.get(position).get("product_id");
remove_wishList_url = SingletonActivity.API_URL + "api/remove_item_wishlist.php?customerid=" + SingletonActivity.custidstr + "&productid=" + Category_listData.get(position).get("product_id");
Log.e("wishlist api..", "wish list api.." + wishList_url);
Log.e("remove wishlist api..", "remove wish list api.." + remove_wishList_url);
v.setActivated(!v.isActivated());
String wish_status = map.get("is_wishlist");
Log.e("wish status..", "wish status.." + wish_status);
int stat = Integer.parseInt(wish_status);
// notifyDataSetChanged();
/*if (wish_status=="Product already exists in wishlist"){
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}
else
{
nav.addTowishList(wishList_url);
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
}*/
if (stat == 0) {
nav.addTowishList(wishList_url);
Toast.makeText(context, "addedd..", Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
// notifyDataSetChanged();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
//
} else {
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
Toast.makeText(context, "removed....", Toast.LENGTH_SHORT).show();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
// notifyDataSetChanged();
}
/* v.setActivated(!v.isActivated());
if (v.isActivated()){
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
nav.addTowishList(wishList_url);
}
else {
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}*/
}
}
});
if (map.get("special_price").equals("0.00")) {
holder.price.setVisibility(View.INVISIBLE);
// holder.o_price.setVisibility(View.INVISIBLE);
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setTextAppearance(context, R.style.product_price_txt);
} else {
holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
/* holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs."+map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);*/
Picasso.with(context).load(map.get("product_image")).placeholder(R.drawable.loading)
.fit().into(holder.img);
return rowView;
}
}
Change this line
holder.wish_list.setImageResource(R.drawable.wishlist);
to this
Resources resources = getResources();
holder.wish_list.setImageDrawable(resources.getDrawable(R.drawable.wishlist));
and do the same in else part and check the output..
Note :
getResources().getDrawable is deprecated.
You can try ContextCompat.getDrawable:
holder.wish_list.setImageDrawable(ContextCompat.getDrawable(context,
R.drawable.wishlist));
UpDate :
check this way.
if(state == true){
// here is default icon and set api value and send it
}else{
// here is click wishlist icon and set api value and send it
}
UpDate 2 :
public class FragmentOne_Adapter extends CursorAdapter {
FragmentOne_DbAdapter dbHelper;
public FragmentOne_Adapter(Context context, Cursor c, int flags) {
super(context, c, flags);
// TODO Auto-generated constructor stub
dbHelper = new FragmentOne_DbAdapter(context);
dbHelper.open();
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
// TODO Auto-generated method stub
final ViewHolder holder = (ViewHolder) view.getTag();
final int _id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String artist = cursor.getString(cursor.getColumnIndexOrThrow("artist"));
String volume = cursor.getString(cursor.getColumnIndexOrThrow("volume"));
final String favorite = cursor.getString(cursor.getColumnIndexOrThrow("favorite"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
// Populate fields with extracted properties
holder.txtTitle.setText(title);
holder.txtArtist.setText(artist);
holder.txtVolume.setText(volume);
holder.txtNumber.setText(number);
if (favorite.matches("0")) {
holder.buttonHeart.setImageResource(R.drawable.heart);
} else {
if (favorite.matches("1")) {
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else {
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
holder.buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (arg0 != null) {
FragmentOne_DbAdapter database = new FragmentOne_DbAdapter(context);
database.open();
if (favorite.matches("0")) {
database.updateItemFavorite(_id, "1");
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else if (favorite.matches("1")) {
database.updateItemFavorite(_id, "0");
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
FragmentOne_Adapter.this.changeCursor(dbHelper.fetchAllPlayer1());
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
// View rowView = ((LayoutInflater) context
// .getSystemService("layout_inflater")).inflate(
// R.layout.fragment_fragment_one_slview, parent, false);
View rowView = LayoutInflater.from(context).inflate(R.layout.fragment_fragment_one_slview, parent, false);
ViewHolder holder = new ViewHolder();
holder.txtTitle = (TextView) rowView.findViewById(R.id.title);
holder.txtArtist = (TextView) rowView.findViewById(R.id.artist);
holder.txtVolume = (TextView) rowView.findViewById(R.id.volume);
holder.txtNumber = (TextView) rowView.findViewById(R.id.number);
holder.buttonHeart = (ImageButton) rowView.findViewById(R.id.heart);
rowView.setTag(holder);
return rowView;
}
class ViewHolder {
TextView txtTitle;
TextView txtArtist;
TextView txtVolume;
TextView txtNumber;
ImageButton buttonHeart;
}
}

Click Event Listeners in a ListActivity [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android: How to fire onListItemClick in Listactivity with buttons in list?
i have develop one app in which i have make ListActivity in which custome listview are going to display custom item list.all things are going to well but here i am confuse with itemOnClickListner. how can i add onclick listner in listActivity ? because there are not any listview that initialize and i can set listner trough that listview control... i have find out from here but its also not working for me
:Here is Code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update3
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends Activity implements OnClickListener, OnItemClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
lstFavrowlistv = (ListView)findViewById(R.id.lstFavrowlistv);
lstFavrowlistv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
});
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
lstFavrowlistv.setAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) lstFavrowlistv.getAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
use getListview() in list Activity to get List..........
in Oncreate
ListView lv = getListView();
http://www.mkyong.com/android/android-listview-example/
this link has both ways
1- overriding onListItemClick(
2- Setting you listener..
Try this way..
ListView lv = getListView();
lv. storelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
}
this are help you.
Thanks
Override the function onlistitemclick() for this. Here the integer position represents the postion of item that you had pressed
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
.......
}
Try this one
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
}
});

Categories

Resources