i have 2 arrays productname and price. my each row in listview contains productname,price and an image button remove. when i click remove button,the selected productname and price should be removed from my array as well as from my listview. Please guide me doing this,is very important for me. If there is another way of doing this plz let me know.i m student only!
this is my CartActivity
public class CartActivity extends Activity implements View.OnClickListener {
CartAdapter contactAdapter;
ListView listView;
public String productname[]=new String[10];
public String price[]=new String[10];
int i=0,m;
CartActivity(String scanContent){
this.content = scanContent;
}
public CartActivity() {}
String product,Price;
String pri,prod;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
listView = (ListView) findViewById(R.id.cart_list_view);
contactAdapter = new CartAdapter(this,R.layout.activity_cart_list_view);
listView.setAdapter(contactAdapter);
intent = getIntent();
productname = intent.getStringArrayExtra("productname");
price = intent.getStringArrayExtra("price");
for(int j=0;j<price.length;j++) {
product = productname[j];
Price = price[j];
if (Price != null || product != null) {
Cart contacts = new Cart(product, Price);
contactAdapter.add(contacts);
}
}
}
this is my CartAdapter
public class CartAdapter extends ArrayAdapter {
List list = new ArrayList();
int ind,x=0;
public CartAdapter(CartActivity context, int resource) {
super(context, resource);
}
public void add(Cart object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
ContactHolder contactHolder;
if(row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_cart_list_view,parent,false);
contactHolder = new ContactHolder();
contactHolder.tx_name =(TextView) row.findViewById(R.id.product_name);
contactHolder.tx_price =(TextView) row.findViewById(R.id.price);
contactHolder.cancelButton = (ImageButton) row.findViewById(R.id.cancel_button);
row.setTag(contactHolder);
}
else
{
contactHolder = (ContactHolder)row.getTag();
}
cancelButton.setTag(position);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer index = (Integer) view.getTag();
list.remove(index.intValue());
notifyDataSetChanged();
}
});
Cart contacts = (Cart) this.getItem(position);
contactHolder.tx_name.setText(contacts.getItemname());
contactHolder.tx_price.setText(contacts.getPrice());
return row;
}
static class ContactHolder
{
TextView tx_name,tx_price;
ImageButton cancelButton;
}
}
this is my Cart
public class Cart {
private String itemname,price;
public Cart(String itemname,String price) {
this.setItemname(itemname);
this.setPrice(price);
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public void setPrice(String price) {
this.price = price;
}
public String getItemname() {
return itemname;
}
public String getPrice() {
return price;
}
}
my each row in a listview contains this
Just do this,
in your adapter class,
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
list.remove(position); //position is getView position
// above line will remove from arraylist
notifyDataSetChanged(); //this line reflects change in listview
}
});
To remove from Activity class,
better create an ArrayList first.
ArrayList<Cart> cardList = new ArrayList<Cart>();
add into arrayList,
if (Price != null || product != null) {
Cart contacts = new Cart(product, Price);
cardList.add(contacts);
contactAdapter.add(contacts); // this line should be removed if you work with arrayList
}
now create a method to remove from ActivityCard arrayList,
//call this method from cancelimage click in adapter class
public void removeFromList(int position){
cardList.remove(position); //this will remove from activity arraylist
}
At the end calculate your bill from existing cartList data.
*** You can also create adapter class object with cardList just changing your constructor. If you do this then just call removeFromList on cancelimage click and put,
adapter.notifyDataSetChanged();
after
cardList.remove(position);
it will refresh your listview also.
Related
I have created an android application. in that application when I click on add, item added to the array list and this array list I want to show in Cart Activity. how to do that.
here is my activity1
public void addShirt(View view) {
MainActivity.cartItems.add(getString(R.string.shirt));
}
public void addPant(View view) {
MainActivity.cartItems.add(getString(R.string.pant));
}
public void view(View view) {
Intent i =new Intent(OnlyIron.this,CartActivity.class);
startActivity(i);
}
and cart activity is
for(int i=0; i<MainActivity.cartItems.size();i++) {
Toast.makeText(this, "item : " + MainActivity.cartItems.get(i), Toast.LENGTH_SHORT).show();
}
it showing toast but I enter code here want this show in listview
First lets Create model class and store data in it.
public class Cart {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now to add items in that list i would call it this way :
private ArrayList<Cart > cart_array;
cart_array= new ArrayList<>();
Cart cart1 = new Cart ();
cart.setId("1");
cart.setName("first product");
Cart cart2 = new Cart ();
cart.setId("2");
cart.setName("first product");
Cart cart3 = new Cart ();
cart.setId("3");
cart.setName("first product");
//and than add your model into array
cart_array.add(cart1);
cart_array.add(cart2);
cart_array.add(cart3);
//and finaly set your adapter
Cart_Adapter adapter = new Cart_Adapter(cart_array, getActivity());
Recycler.setAdapter(adapter );
Please take a list view in CartActivity & create an Custom Adapter as according to your need(UI). Pass the MainActivity.cartItems this list to Adapter. It will start to show in your CartActivity.
You can see below example:
public class CustomAdapter extends BaseAdapter{
Activity mContext;
public ArrayList<String> mCartList = new ArrayList<String>();
private LayoutInflater mInflater=null;
public CustomAdapter(Activity activty, ArrayList<String> list)
{
this.mContext = activty;
mInflater = activty.getLayoutInflater();
this.mCartList=list;
}
#Override
public int getCount() {
if (mCartList != null){
return mCartList.size();
} else{
return 0;
}
}
#Override
public String getItem(int arg0) {
return mCartList.get(arg0);
}
#Override
public long getItemId(int index) {
return index;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
final ViewHolder holder;
if (convertView == null ) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_layout, null);
holder.mItemNameTV= (TextView) convertView.findViewById(R.id.itemtv);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.mNameTV.setText(mCartList.get(position));
return convertView;
}
private static class ViewHolder {
TextView mNameTV;
}
}
// Item Layout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/forty_dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/fieldTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/five_dp"
android:layout_weight="0.4"
android:padding="#dimen/ten_dp"
android:text="Custom Field"
android:textColor="#color/dark_gray_color"
android:textSize="#dimen/normal_font_size"
android:visibility="visible" />
</LinearLayout>
// Let Suppose your CartActivity is following:
ListView mListView = (ListView)findViewById(R.id.listview);
CustomAdapter adapter = new CustomAdapter(this, MainActivity.cartItems);
mListView.setAdapter(adapter);
I have a listview, from database (category list) and i want to load gridview (product gridview) when i click any button in the category listview, i'm able to make the listview and gridview, but cannot connect them, since im still new at android programming and have no clue to do it.
my main purpose is:
List category
on click on the category button will load gridview of product button
on click product button will add the product id to table cart
ps: if you notice i do SQL query in the mainActivity class, i still new at the code so i tried my best first before convert into better practice.
Any suggestion to do it?
Here i include my snippet:
Category.java (setter and getter)
public class Category {
private int _id;
private String _name;
public Category() {
}
public Category(int id, String name) {
this._id = id;
this._name = name;
}
public Category(String name) {
this._name = name;
}
public int getID() {
return this._id;
}
public void setID(int id) {
this._id = id;
}
public String get_name()
{
return this._name;
}
public void set_name(String name)
{
this._name = name;
}
}
CategoryListAdapter.java
public class CategoryListAdapter extends BaseAdapter {
private ArrayList<Category> listData;
private LayoutInflater layoutInflater;
public CategoryListAdapter(Context aContext, ArrayList<Category> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
CategoryListAdapter.ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_category, null);
holder = new CategoryListAdapter.ViewHolder();
holder.btnCategory = (Button) convertView.findViewById(R.id.btnCategory);
convertView.setTag(holder);
} else {
holder = (CategoryListAdapter.ViewHolder) convertView.getTag();
}
holder.btnCategory.setText(listData.get(position).get_name());
return convertView;
}
static class ViewHolder {
Button btnCategory;
}
}
listview_category.xml (layout that will be repeated)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:textStyle="bold"
android:textSize="16dp"
android:id="#+id/btnCategory"
android:focusable="false"
android:focusableInTouchMode="false"
android:background="#drawable/button_category"/>
</LinearLayout>
listview inside MainActivity
<ListView
android:id="#+id/listviewCategory"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
java inside MainActivity
protected void onCreate(Bundle savedInstanceState) {
...
/* LIST CATEGORY TO LOAD PRODUCT */
ArrayList list_category = getListCategory();
final ListView listview_category = (ListView) findViewById(R.id.listviewCategory);
listview_category.setAdapter(new CategoryListAdapter(this, list_category));
listview_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Log.d(TAG, "click cat");
//Give product list an id from category_id get from here
}
});
...
}
/* List Category for selecting category product */
private ArrayList getListCategory() {
SQLiteDatabase mydatabase = openOrCreateDatabase("posDb",MODE_PRIVATE,null);
Cursor resultSet = mydatabase.rawQuery("Select * from categories",null);
ArrayList<Category> results = new ArrayList<Category>();
if (resultSet.moveToFirst()) {
do {
Category categoriesData = new Category();
categoriesData.set_name(resultSet.getString(1));
results.add(categoriesData);
} while (resultSet.moveToNext());
}
return results;
}
The grid of product mostly the same as category, but load product from database which later i want to onclick the product button to save record to cart table
on Click on button will add the product id in to table_cart
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ArrayList list_category = getListCategory();
int id[]={1, 2, 3, 4, 5};
String categoryName[]={"category1","category2","category3","category4","category5"};
ArrayList<Category> listData=new ArrayList<>();
Category category;
for (int i=0; i<id.length; i++)
{
category=new Category();
category.set_id(id[i]);// setting Id
category.set_name(categoryName[i]);// setting category name
listData.add(category);
}
final ListView listview_category = (ListView) findViewById(R.id.listviewCategory);
listview_category.setAdapter(new CategoryListAdapter(this, listData ));
}
}
CategoryListAdapter.java
public class CategoryListAdapter extends BaseAdapter {
private ArrayList listData;
private LayoutInflater layoutInflater;
ArrayList table_cart = new ArrayList();
private static final String TAG = "CategoryListAdapter";
public CategoryListAdapter(Context aContext, ArrayList<Category> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final CategoryListAdapter.ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_category, null);
holder = new CategoryListAdapter.ViewHolder();
holder.btnCategory = (Button) convertView.findViewById(R.id.btnCategory);
convertView.setTag(holder);
} else {
holder = (CategoryListAdapter.ViewHolder) convertView.getTag();
}
holder.btnCategory.setText(listData.get(position).get_name());
holder.btnCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getting product id
int product_id = listData.get(position).getID();
Log.e(TAG, "product_id: " + product_id);
// now you can get category name as well
String category_name = listData.get(position).get_name();
Log.e(TAG, "category_name: " + category_name);
// now adding product id in to table_cart
table_cart.add(listData.get(position).getID());
}
});
return convertView;
}
static class ViewHolder {
Button btnCategory;
}
}
Category.java
public class Category {
private int _id;
private String _name;
public int getID() {
return this._id;
}
public void setID(int id) {
this._id = id;
}
public String get_name() {
return this._name;
}
public void set_name(String name) {
this._name = name;
}
public void set_id(int _id) {
this._id = _id;
}
}
there is no need to change layouts
Add on click listener for category button, add grid view in fragment and open fragment on button click.
holder.btnCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProductFragment nextFrag= new ProductFragment();
this.getFragmentManager().beginTransaction()
.replace(R.id.Layout_container, nextFrag,TAG_FRAGMENT)
.commit();
}
});
I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?
Note: I retrieve all the data from my server using json response.
Here's my Model :
public class Groups {
public String name;
public boolean selected= false;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Groups() {
}
}
My Adapter:
public class AdapterMainActivity extends BaseAdapter{
Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;
public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}
#Override
public int getCount() {
return groupsList.size();
}
#Override
public Object getItem(int position) {
return groupsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());
checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});
}
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listViewGroups;
Button buttonSentToActivity;
List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;
private AdapterMainActivity adapterMainActivity;
static MainActivity yourActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourActivity = this;
groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();
ReadGroup(37);
adapterMainActivity = new AdapterMainActivity(this, groupsList);
listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);
buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);
Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}
}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < readArray.length(); i++) {
Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);
String groupName = jssonRow.getString("name");
Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};
Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);
Log.e("out of the loop", "");
}
public static MainActivity getInstance() {
return yourActivity;
}
public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}
View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.Âștime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
Here's the solution for this Question:
My adapter:
public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;
public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
this.activity = activity;
this.contactsList = group;
}
#Override
public int getCount() {
return contactsList.size();
}
#Override
public Object getItem(int position) {
return contactsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
null);
final TextView fNAme = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);
checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);
checkBoxAdapter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Contacts contacts = (Contacts) cb.getTag();
contacts.setSelected(cb.isChecked());
Toast.makeText(activity.getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
final Contacts contacts = contactsList.get(position);
fNAme.setText(contacts.getContactFName());
LName.setText(contacts.getContactLName());
checkBoxAdapter.setChecked(contacts.isSelected());
checkBoxAdapter.setTag(contacts);
}
return convertView;
}
}
In my activity I have button to go from 1 activity to the 2 activity:
private View.OnClickListener buttonSubmitGroupListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
List <Integer> contactsIDArray= new ArrayList<Integer>();
List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
for(int i=0; i< arrayOfContacts.size(); i++){
Contacts contacts= arrayOfContacts.get(i);
if(contacts.isSelected()==true){
contactsIDArray.add(contacts.getContactID());
}
}
for (int i = 0; i < contactsIDArray.size(); i++) {
Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
}
intent = new Intent(getApplicationContext(), SendSMSActivity.class);
Bundle b = new Bundle();
b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
intent.putExtras(b);
startActivity(intent);
}
};
Second Activity add this code:
Bundle b = getIntent().getExtras();
List<Integer> result = new ArrayList<Integer>();
result = b.getIntegerArrayList("checkedContacts");
I have a custom listView that is empty in first time , from other side i have an activity which contains a product details such as picture, title, model .in this activity there is a button , so when user press this button i want to add the product into my custom listView and shows all the product details there,
my listView is:
public class ListViewShoppingBasketActivity extends Activity {
BaseAdapter adapter;
ArrayList<SingleRow> list;
Context context;
String[] titles;
Bitmap[] images;
String[] descriptions;
TextView title;
TextView description;
ImageView image;
String rowTitles;
String rowDescription;
Bitmap rowImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_shopping_basket_layout);
final ListView list = (ListView) findViewById(R.id.listView1);
list.setAdapter(new MyAdapter(this));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
if (id == 0) {
} else if (id == 1) {
} else if (id == 2) {
} else if (id == 3) {
} else if (id == 4) {
}
}
});
}
class SingleRow {
String rowTitles;
String rowDescription;
Bitmap rowImage;
public SingleRow(String rowTitles, String rowDescription, Bitmap rowImage) {
this.rowTitles = rowTitles;
this.rowDescription = rowDescription;
this.rowImage = rowImage;
}
}
class MyAdapter extends BaseAdapter {
public MyAdapter(Context c) {
context = c;
list = new ArrayList<SingleRow>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.shopping_basket_listview_row,
viewGroup, false);
title = (TextView) row.findViewById(R.id.textView1);
description = (TextView) row.findViewById(R.id.textView2);
image = (ImageView) row.findViewById(R.id.imageView1);
SingleRow temp = list.get(i);
title.setText(temp.rowTitles);
description.setText(temp.rowDescription);
image.setImageBitmap(temp.rowImage);
return row;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.list_view_shopping_basket, menu);
return true;
}
// // **********baraye add kardane item jadid be listview
public void addItems(View v) {
list.add(new SingleRow(rowTitles, rowDescription, rowImage));
adapter.notifyDataSetChanged();
}
}
and this is implementation of my button in other activity
b_add_to_cart = (Button) findViewById(R.id.b_add_to_cart);
b_add_to_cart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BarcodeDetailsActivity.this,
ListViewShoppingBasketActivity.class);
intent.putExtra("productID", proId);
intent.putExtra("productModel", proModel);
intent.putExtra("productTitle", proTitle);
intent.putExtra("productPictureUrl", mIcon11);
startActivity(intent);
}
});
my problem is , i dont know how and where i can assign my product details in my listview
You can put the next lines to the code of the ListViewShoppingBasketActivity:
Intent i = getIntent();
if (i.getExtras() != null){
int prodId = i.getExtras().getInt("productID");
....
}
You can put theese to an ArrayList, and use an BaseAdapter (http://developer.android.com/reference/android/widget/BaseAdapter.html) to display the data in the list.
Hai i'm trying to develop an app where by i can send sms and email to a particular group of people..
I have a listview showing the contacts which are in my group.Each row is of the form
TextView(Name)TextView(phone) Checkbox(sms)
TextView(email id) Checkbox(mail)
I have used custom adapter to display the contact details to the listview.ihave set the onitemclick listener to find the position of the row..
I have to send sms and email to those contacts for which checkboxes have been set as true.how can i find the state of each of the checkboxes.
Please help me..lotz of thanx in advance..
I hav added below the custom adapetr i hv created..
public class ContactInfoAdapter extends ArrayAdapter{
private ArrayList<Boolean> mChecked_sms,mChecked_email;
Context context;
int layoutResourceId;
ContactInfo data[] = null;
public ContactInfoAdapter(Context context, int layoutResourceId, ContactInfo[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
mChecked_sms = new ArrayList<Boolean>();
mChecked_email = new ArrayList<Boolean>();
for (int i = 0; i < this.getCount(); i++) {
mChecked_sms.add(i, false);
mChecked_email.add(i,false);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ContactHolder holder;
View row = convertView;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ContactHolder();
holder.txtName = (TextView)row.findViewById(R.id.textViewName);
holder.txtPhone = (TextView) row.findViewById(R.id.textViewPhone);
holder.txtEmail = (TextView) row.findViewById(R.id.textViewEmail);
holder.cb_sms_state = (CheckBox) row.findViewById(R.id.checkBox1);
holder.cb_email_state = (CheckBox) row.findViewById(R.id.checkBox2);
row.setTag(holder);
}
else
{
holder = (ContactHolder)row.getTag();
}
ContactInfo contact = data[position];
holder.txtName.setText(contact.name);
holder.cb_sms_state.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (holder.cb_sms_state.isChecked()) {
mChecked_sms.set(position, true);
Toast.makeText(getContext(), "checked", 2).show();
} else {
mChecked_sms.set(position, false);
}
}
});
holder.cb_sms_state.setChecked(mChecked_sms.get(position));
holder.cb_email_state.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (holder.cb_email_state.isChecked()) {
mChecked_email.set(position, true);
Toast.makeText(getContext(), "checked", 2).show();
} else {
mChecked_email.set(position, false);
}
}
});
holder.cb_email_state.setChecked(mChecked_email.get(position));
holder.txtPhone.setText(contact.number);
holder.txtEmail.setText(contact.email);
return row;
}
static class ContactHolder
{
TextView txtName;
TextView txtPhone;
TextView txtEmail;
CheckBox cb_sms_state;
CheckBox cb_email_state;
}
}
The ContactInfo class is :
public class ContactInfo {
public String name;
public String number;
public String email;
public boolean sms_state;
public boolean email_state;
public ContactInfo(){
super();
}
public ContactInfo(String name,String number,String email,boolean sms_state,boolean email_state) {
super();
this.name = name;
this.number = number;
this.email = email;
this.sms_state = sms_state;
this.email_state = email_state;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setNUmber(String number) {
this.number = number;
}
public String getNumber() {
return number;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setSms_state(Boolean sms_state)
{
this.sms_state = sms_state;
}
public Boolean getSms_state(){
return sms_state;
}
public void setEmail_state(Boolean email_state)
{
this.email_state = email_state;
}
public Boolean getEmail_state(){
return email_state;
}
Inside the getView() method, you have to implement a OnCheckedChangeListener for the CheckBox.
Here is a listener code, say for example:
ChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
See the doc.
I think you need :
checkbox.isChecked()
Here's a simple sample:
mContactListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
CheckBox chkContact = (CheckBox) view.findViewById(R.id.listrow_contact_chkContact);
if (chkContact.isChecked()) {
...
}
});
I've had this problem with my app Hasta La Vista I've create a with custom listview with checked items and I needed to get checked items this was the solution:
ListView lv = getListView(); //ver listview
if(lv != null){
final SparseBooleanArray checkedItems = lv.getCheckedItemPositions(); //get checked items
if (checkedItems == null) {
return;
}
final int checkedItemsCount = checkedItems.size();
for (int i = 0; i < checkedItemsCount; ++i) {
// This tells us the item position we are looking at
final int position = checkedItems.keyAt(i);
// This tells us the item status at the above position
final boolean isChecked = checkedItems.valueAt(i);
if(isChecked){
//get item from list and do something
lv.getAdapter().getItem(position);
}
}
}
As ListView views are recycled, you can not rely on listening on particular instance, you will have to store "checked" state in your data model. You will also need custom list adapter, where you create and populate individual entries. Following shall be done:
- in overriden getView(), either create new view ( in case no convertView was supplied ) or inflate new one
- populate viewv fields from you data model
- remove old onclick listener, and set new one ( can be anonymous inner class ) modifying your data model
PS: recycling views is important if your list is big