listview with increment and decrement buttons with quantity - android

In listview I have a increment and decrement buttons for change the quantity. increasing and decreasing operations are working fine. but quantity will display in array in other activity. please help me i am new to android development. Here first activity and second activity snaps
MainActivity
public class CatalogActivity extends Activity implements CustomButtonListener{
private List<Product> mProductList;
static int quantity2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Make sure to clear the selections
for(int i=0; i<mProductList.size(); i++) {
mProductList.get(i).selected = false;
}
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false));
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
ProductAdapter.setCustomButtonListener(this);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
#Override
public void onButtonClickListener(int position, TextView editText, int value) {
quantity2 = Integer.parseInt(editText.getText().toString());
quantity2 = quantity2+1*value;
if(quantity2<0)
quantity2=0;
editText.setText(quantity2+"");
}
}
Product Adapter
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
public static int quantity = 0;
public Context context;
public static ArrayList<Integer> quantity1 = new ArrayList<Integer>();
static CustomButtonListener customButtonListener;
public static int quant;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
for (int i = 0; i < list.size(); i++) {
quantity1.add(0);
}
}
public static void setCustomButtonListener(CustomButtonListener customButtonListner) {
customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Product getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final 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.productCost = (TextView) convertView
.findViewById(R.id.itemcost);
item.productbtn = (Button) convertView.findViewById(R.id.btn_plus);
item.textquanty = (TextView) convertView.findViewById(R.id.num);
item.productbtnminus = (Button) convertView.findViewById(R.id.btn_minus);
item.Layout = (View) convertView.findViewById(R.id.add);
getItem(position).setSelected(false);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
final Product product = getItem(position);
try {
item.textquanty.setText(quantity1.get(position) + "");
} catch (Exception e) {
e.printStackTrace();
}
item.productbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, item.textquanty, 1);
quantity1.set(position, quantity1.get(position) + 1);
ShoppingCartHelper.setQuantity(curProduct, quantity1, position);
}
}
});
item.productbtnminus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, item.textquanty, -1);
if (quantity1.get(position) > 0)
quantity1.set(position, quantity1.get(position) - 1);
ShoppingCartHelper.setQuantity(curProduct, quantity1, position);
}
}
});
item.productImageView.setImageDrawable(product.productImage);
item.productTitle.setText(product.title);
item.productCost.setText("" + product.price);
if (mShowQuantity) {
item.productQuantity.setText("Quantity: " + ShoppingCartHelper.getProductQuantity(product, position));
item.Layout.setVisibility(View.GONE);
} else {
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
public static Integer getProductQuantity(Product product, int position) {
ShoppingCartEntry curEntry = ShoppingCartHelper.cartMap.get(product);
if (curEntry != null)
quant=Integer.parseInt((quantity1.get(position)+""));
return quant;
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
TextView productCost;
public Button productbtn;
public Button productbtnminus;
View Layout;
public TextView textquanty;
}
}
Product
public class Product {
public String title;
public Drawable productImage;
public String description;
public double price;
private int quantity;
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Product(String title, Drawable productImage, String description,
double price) {
this.title = title;
this.productImage = productImage;
this.description = description;
this.price = price;
}
}
ShoppingCartEntry
public class ShoppingCartEntry {
private Product mProduct;
private ArrayList<Integer> mQuantity;
public ShoppingCartEntry(Product product, ArrayList<Integer> quantity1) {
mProduct = product;
mQuantity = quantity1;
}
public Product getProduct() {
return mProduct;
}
public ArrayList<Integer> getQuantity(int position) {
return mQuantity;
}
public void setQuantity(ArrayList<Integer> quantity1) {
mQuantity = quantity1;
}
}
ShoppingCartHelper
public class ShoppingCartHelper {
public static final String PRODUCT_INDEX = "PRODUCT_INDEX";
protected static List<Product> catalog;
public 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("Chiken Curry", res .getDrawable(R.drawable.deadoralive),"Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
catalog.add(new Product("Mutton Curry", res .getDrawable(R.drawable.switchbook), "Switch by Chip Heath and Dan Heath", 24.99));
catalog.add(new Product("Aloo Curry", res.getDrawable(R.drawable.watchmen), "Watchmen by Alan Moore and Dave Gibbons", 14.99));
catalog.add(new Product("ChikenBiryani", res .getDrawable(R.drawable.deadoralive),"Dead or Alive by Tom Clancy with Grant Blackwood", 25.99));
catalog.add(new Product("MuttonBiryani", res .getDrawable(R.drawable.switchbook), "Switch by Chip Heath and Dan Heath", 21.99));
catalog.add(new Product("Aloo Curry", res.getDrawable(R.drawable.watchmen), "Watchmen by Alan Moore and Dave Gibbons", 12.99));
catalog.add(new Product("Chiken Curry", res .getDrawable(R.drawable.deadoralive),"Dead or Alive by Tom Clancy with Grant Blackwood", 30.99));
catalog.add(new Product("Mutton Curry", res .getDrawable(R.drawable.switchbook), "Switch by Chip Heath and Dan Heath", 28.99));
catalog.add(new Product("Aloo Curry", res.getDrawable(R.drawable.watchmen), "Watchmen by Alan Moore and Dave Gibbons", 18.99));
}
return catalog;
}
public static void setQuantity(Product product, ArrayList<Integer> quantity1, int position) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
// If the quantity is zero or less, remove the products
if(ProductAdapter.quantity1.get(position) <= 0) {
if(curEntry != null)
removeProduct(product);
return;
}
// If a current cart entry doesn't exist, create one
if(curEntry == null) {
curEntry = new ShoppingCartEntry(product, quantity1);
cartMap.put(product, curEntry);
return;
}
// Update the quantity
curEntry.setQuantity(quantity1);
}
public static ArrayList<Integer> getProductQuantity(Product product, int position) {
// Get the current cart entry
ShoppingCartEntry curEntry = cartMap.get(product);
if(curEntry != null)
return curEntry.getQuantity(position);
return null;
}
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;
}
}

Related

How to call every object in adapter?

I have a list of array adapters that have the following layout which contains checkbox, textview increase, textview count, and textview decrease :
layout product adapter.
what the problem is how to call or implement clicklistener from ProdukActivity.java on each object that appears on the adapter. I just want to know how does it work with object in adapter so i can count the product price in every checkbox is checked.
Here is my adapter code :
public class ProductAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<ProductModel> productItems;
public ProductAdapter(Activity activity, List<ProductModel> productItems) {
this.activity = activity;
this.productItems = productItems;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int location) {
return productItems.get(location);
}
#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.list_produk, null);
CheckBox namaProduk = (CheckBox) convertView.findViewById(R.id.checkBox_productName);
TextView kurangProduk = (TextView) convertView.findViewById(R.id.decrease_product);
TextView hitungProduk = (TextView) convertView.findViewById(R.id.count_product);
TextView tambahProduk = (TextView) convertView.findViewById(R.id.increase_product);
TextView hargaProduk = (TextView) convertView.findViewById(R.id.product_price);
ProductModel produk = productItems.get(position);
namaProduk.setText(produk.getProduct_name());
hargaProduk.setText(produk.getProduct_price());
return convertView;
}
}
and here is my ProdukActivity.java :
public class ProdukLaundry extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
ActionBar actionBar;
ListView listProduk;
SwipeRefreshLayout swipeProduct;
List<ProductModel> productList = new ArrayList<ProductModel>();
ProductAdapter productAdapter;
int success;
AlertDialog.Builder dialog;
RadioButton radioReguler, radioExpress;
TextView tvTotal;
Button next;
String product_id, laundry_id, product_name, product_price, service_type;
private int offset = 0;
private static final String TAG = ProdukLaundry.class.getSimpleName();
private static String url_select = Server.URL + "selectproduk.php";
public static final String TAG_PRODUCT_ID = "product_id";
public static final String TAG_LAUNDRY_ID = "laundry_id";
public static final String TAG_PRODUCT_NAME = "product_name";
public static final String TAG_PRODUCT_PRICE = "product_price";
public static final String TAG_SERVICE_TYPE = "service_type";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
int countcheckBox = 0;
int totalCount = 0;
boolean regular = true;
boolean express = false;
boolean checkBox = false;
Transaction transaction;
String tag_json_obj = "json_obj_req";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produk);
// menghubungkan variablel pada layout dan pada java
listProduk = (ListView)findViewById(R.id.list_produk);
swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
radioExpress = (RadioButton)findViewById(R.id.radio_express);
radioReguler = (RadioButton)findViewById(R.id.radio_regular);
tvTotal = (TextView)findViewById(R.id.total);
next = (Button)findViewById(R.id.button_next);
actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);
// untuk mengisi data dari JSON ke dalam adapter
productAdapter = new ProductAdapter(ProdukLaundry.this, productList);
listProduk.setAdapter(productAdapter);
// menampilkan widget refresh
swipeProduct.setOnRefreshListener(this);
swipeProduct.post(new Runnable() {
#Override
public void run() {
swipeProduct.setRefreshing(true);
productList.clear();
productAdapter.notifyDataSetChanged();
callProduct();
}
}
);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onRefresh() {
productList.clear();
productAdapter.notifyDataSetChanged();
callProduct();
}
public void onClick(View view){
switch (view.getId()){
case R.id.increase_product:
countcheckBox++;
changeCheckBox();
hitung();
break;
case R.id.decrease_product:
if (countcheckBox>0){
countcheckBox--;
changeCheckBox();
hitung();
}
break;
case R.id.button_next:
save();
break;
default:
break;
}
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio_regular:
if (checked) {
regular = true;
express = false;
hitung();
}
break;
case R.id.radio_express:
if (checked){
regular = false;
express = true;
hitung();
}
break;
}
}
public void changeCheckBox(){
tvTotal.setText(countcheckBox+"");
}
public void hitung(){
int totalCount = 0;
int expressCost = 20000;
int harga = Integer.parseInt(product_price);
if (checkBox){
if (express){
totalCount+=(harga+expressCost)*countcheckBox;
}else{
totalCount+=harga*countcheckBox;
}
}
this.totalCount = totalCount;
tvTotal.setText(this.totalCount+"");
}
private void save() {
if (tvTotal.getText().toString().equals("0")){
Toast.makeText(this, "Choose Service.",
Toast.LENGTH_SHORT).show();
return;
}
String transId = "variabel transaksi id";
String uid = "variabel produk id";
String type;
if (regular) {
type = "regular";
} else {
type = "express";
}
transaction = new Transaction(transId, uid, type);
if (checkBox) {
transaction.setCheckBox(String.valueOf(countcheckBox));
}
transaction.total = String.valueOf(totalCount);
/*Intent intent = new Intent(this, LocationActivity.class);
intent.putExtra("transaction", transaction);
startActivity(intent);*/
}
Add listener for every object like below, inside getView of adapter. And inside the listener, do your handling
#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.list_produk, null);
final CheckBox namaProduk = (CheckBox) convertView.findViewById(R.id.checkBox_productName);
TextView kurangProduk = (TextView) convertView.findViewById(R.id.decrease_product);
TextView hitungProduk = (TextView) convertView.findViewById(R.id.count_product);
TextView tambahProduk = (TextView) convertView.findViewById(R.id.increase_product);
TextView hargaProduk = (TextView) convertView.findViewById(R.id.product_price);
ProductModel produk = productItems.get(position);
namaProduk.setText(produk.getProduct_name());
hargaProduk.setText(produk.getProduct_price());
namaProduk.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
//check here
}
}
}
);
kurangProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
hitungProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
tambahProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
hargaProduk.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
}
);
return convertView;
}

Create favorite listview with shared preferences

I have a listview of ringtones .. I feed the list via mysql database.. (such as song names,song urls ...). I dynamically add products(ringtones) in my listview by adding new item in my database, so none of this data are inside my app except row icons.
This is the view
As you can see I have a bookmark border icon that when user clicks on it, it will turn into selected...This is how it works :
#Override
public void favOnClick(int position) {
Product product = productList.get(position);
if (product.faved) {
sharedPreference.addFavorite(activity,product);
product.setFavId(R.mipmap.bookmarked);
product.faved=false;
}else {
sharedPreference.removeFavorite(activity,product);
product.setFavId(R.mipmap.bookmark_border);
product.faved = true;
}
adapter.notifyDataSetChanged();
};
but nothing will happen in my "FAVORITES" tab .. Even the state of bookmark icon when it is selected will not be saved..
Custom Adapter
public class FunDapter<T> extends BaseAdapter {
public interface PlayPauseClick {
void favOnClick(int position);
}
private PlayPauseClick callback;
public void setPlayPauseClickListener(PlayPauseClick listener) {
this.callback = listener;
}
protected List<T> mDataItems;
protected List<T> mOrigDataItems;
protected final Context mContext;
private final int mLayoutResource;
private final BindDictionary<T> mBindDictionary;
public FunDapter(Context context, List<T> dataItems, int layoutResource,
BindDictionary<T> dictionary) {
this(context, dataItems, layoutResource, null, dictionary);
}
public FunDapter(Context context, List<T> dataItems, int layoutResource,
LongExtractor<T> idExtractor, BindDictionary<T> dictionary) {
this.mContext = context;
this.mDataItems = dataItems;
this.mOrigDataItems = dataItems;
this.mLayoutResource = layoutResource;
this.mBindDictionary = dictionary;
sharedPreference = new SharedPreference();
}
public void updateData(List<T> dataItems) {
this.mDataItems = dataItems;
this.mOrigDataItems = dataItems;
notifyDataSetChanged();
}
#Override
public int getCount() {
if (mDataItems == null || mBindDictionary == null) return 0;
return mDataItems.size();
}
#Override
public T getItem(int position) {
return mDataItems.get(position);
}
#Override
public long getItemId(int position) {
if(idExtractor == null) return position;
else return idExtractor.getLongValue(getItem(position), position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final GenericViewHolder holder;
if (null == v) {
LayoutInflater vi =
(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(mLayoutResource, null);
holder = new GenericViewHolder();
holder.root = v;
//init the sub views and put them in a holder instance
FunDapterUtils.initViews(v, holder, mBindDictionary);
v.setTag(holder);
}else {
holder = (GenericViewHolder) v.getTag();
}
final T item = getItem(position);
showData(item, holder, position);
Product product = (Product) mDataItems.get(position);
holder.favImage=(ImageView)v.findViewById(R.id.favImage);
holder.favImage.setImageResource(product.getFavId());
holder.favImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (callback != null) {
callback.favOnClick(position);
}
}
});
return v;
}
}
Product model class
#SuppressWarnings("serial")
public class Product implements Serializable {
#SerializedName("pid")
public int pid;
#SerializedName("name")
public String name;
#SerializedName("qty")
public int qty;
#SerializedName("price")
public String description;
#SerializedName("song_url")
public String song_url;
#SerializedName("date")
public String date;
public boolean paused = true;
public boolean faved = true;
private int favId;
public int getFavId() {
return favId;}
public void setFavId(int favId) {
this.favId = favId;}
}
SharedPreferences class
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<Product> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, Product product) {
List<Product> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<Product>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, Product product) {
ArrayList<Product> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<Product> getFavorites(Context context) {
SharedPreferences settings;
List<Product> favorites;
settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
Product[] favoriteItems = gson.fromJson(jsonFavorites,Product[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<Product>(favorites);
} else
return null;
return (ArrayList<Product>) favorites;
}
}
I'm stuck here for a few days, Can you help me please !
This is my project link if you would like to look into it for further info
http://symphonyrecords.ir/RingtoneApp.rar
There are two problems here (based on your project)
First (saving state of bookmark Imageview)
In adapter create a method that checks whether a particular product exists in SharedPreferences
public boolean checkFavoriteItem(Product checkProduct) {
boolean check = false;
List<Product> favorites = sharedPreference.getFavorites(null, mContext);
if (favorites != null) {
for (Product product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
Inside adapter check if a product exists in shared preferences then set bookmarked drawable and set a tag
if (checkFavoriteItem(product)) {
holder.favoriteImg.setImageResource(R.mipmap.bookmarked);
holder.favoriteImg.setTag("bookmarked");
} else {
holder.favoriteImg.setImageResource(R.mipmap.bookmark_border);
holder.favoriteImg.setTag("bookmark_border");
}
Then inside favOnClick callback method
#Override
public boolean favOnClick(int position ,View v) {
Product product = (Product) productList.get(position);
ImageView button = (ImageView) v.findViewById(R.id.favImage);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("bookmark_border")) {
sharedPreference.addFavorite(activity,product);
Toast.makeText(activity,"Added to Favorites",Toast.LENGTH_SHORT).show();
button.setTag("bookmarked");
button.setImageResource(R.mipmap.bookmarked);
} else {
sharedPreference.removeFavorite(activity,product);
button.setTag("bookmark_border");
button.setImageResource(R.mipmap.bookmark_border);
Toast.makeText(activity,"Removed from Favorites",Toast.LENGTH_SHORT).show();
}
return true;
}
Second (get favorite product and pass it to "FAVORITE" Fragment)
Inside getFavorite method add a String parameter
Then in your "FAVORITE" Fragment with processFinish(your AsyncResponse) call your getFavorite in order to get your Favorite product list then set your adapter :
Context mContext;
`mContext = getContext();`
#Override
public void processFinish(String s) {
productList = sharedPreference.getFavorites(s, mContext);
BindDictionary<Product> dict = new BindDictionary<Product>();
dict.addStringField(R.id.tvName, new StringExtractor<Product>() {
#Override
public String getStringValue(Product product, int position) {
return product.name;
}
});
dict.addStringField(R.id.tvDescription, new StringExtractor<Product>() {
#Override
public String getStringValue(Product product, int position) {
return product.description;
}
});
dict.addStringField(R.id.tvQty, new StringExtractor<Product>() {
#Override
public String getStringValue(Product product, int position) {
return "" + product.qty;
}
});
adapter = new FunDapter<>(getActivity(), productList, R.layout.d_layout_list_d, dict);
lvProduct.setAdapter(adapter);
}
Make sure favOnClick method change the object in FunDapter.mDataItems.
So, Change the callback method:
#Override
public void favOnClick(int position) {
Product product = adapter.get(position);
if (product.faved) {
sharedPreference.addFavorite(activity, product);
product.setFavId(R.mipmap.bookmarked);
product.faved=false;
}else {
sharedPreference.removeFavorite(activity, product);
product.setFavId(R.mipmap.bookmark_border);
product.faved = true;
}
adapter.notifyDataSetChanged();
};
Check this, 99% working code
On click Fav Btn
List< RvModel > favorites_list = storageFavorites.loadFavourite();
boolean exist = false;
if (favorites_list == null) {
favorites_list = new ArrayList<>();
}
for (int i = 0; i < favorites_list.size(); i++) {
if (favorites_list.get(i).getId().equals(rvModelArrayList.get(position).getId())) {
exist = true;
}
}
if (!exist) {
ArrayList< RvModel > audios = new ArrayList< RvModel >(favorites_list);
audios.add(rvModelArrayList.get(position));
storageFavorites.storeImage(audios);
holder.bookMarkBtn.setImageDrawable(activity.getResources().getDrawable(R.drawable.ic_bookmark_full));
} else {
ArrayList< RvModel > new_favorites = new ArrayList< RvModel >();
for (int i = 0; i < favorites_list.size(); i++) {
if (!favorites_list.get(i).getId().equals(rvModelArrayList.get(position).getId())) {
new_favorites.add(favorites_list.get(i));
}
}
if (favorites) {
Log.v("DOWNLOADED", "favorites==true");
rvModelArrayList.remove(position);
notifyDataSetChanged();
//holder.ripple_view_wallpaper_item.setVisibility(View.GONE);
}
storageFavorites.storeImage(new_favorites);
holder.bookMarkBtn.setImageDrawable(activity.getResources().getDrawable(R.drawable.ic_bookmark));
}
}

Not able to display selected multiple items on toast where the Checkbox is Checked

I am able to load data from database into my custom ListView, but not able to display the item(relevant, courseName to be precise) when the checkbox is checked(multiple checkboxes can be checked) on toast when I press button.
Here is my Adapter code:
public class CourseSelectionAdapter extends ArrayAdapter<CourseDisplay>{
private Context mContext;
private LayoutInflater mInflater;
int layoutResourceId;
public static List<CourseDisplay> mDataSource;
public static int checkBoxCounter;
public CourseSelectionAdapter(Context context, int layoutResourceId, List<CourseDisplay> items) {
super(context, layoutResourceId, items);
mContext = context;
mDataSource = items;
this.layoutResourceId = layoutResourceId;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
checkBoxCounter = 0;
}
#Override
public int getCount() {
return mDataSource.size();
}
#Override
public CourseDisplay getItem(int position) {
return mDataSource.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
//4
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
// Get view for row item
View row = convertView;
ViewHolder holder;
holder = null;
CourseDisplay courseDisplay = getCourse(position);
// 1
if (row == null) {
// 2
row = mInflater.inflate(R.layout.custom_listview_layout, parent, false);
// 3
holder = new ViewHolder();
holder.courseCodeTextView = (TextView) row.findViewById(R.id.course_id_display);
holder.courseNameTextView = (TextView) row.findViewById(R.id.course_name_display);
holder.courseSelectedCheckBox = (CheckBox) row.findViewById(R.id.course_selection_checkbox);
holder.courseCodeTextView.setText(courseDisplay.getCourseCode());
holder.courseNameTextView.setText(courseDisplay.getCourseName());
holder.courseSelectedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
checkBoxCounter++;
getCourse((Integer) buttonView.getTag()).getCourseSelected();
}else {
checkBoxCounter--;
}
System.out.println("Count is: "+ checkBoxCounter);
}
});
// 4
row.setTag(holder);
} else {
// 5
holder = (ViewHolder) row.getTag();
}
// 6
holder.courseSelectedCheckBox.setTag(position);
holder.courseSelectedCheckBox.setChecked(courseDisplay.getCourseSelected());
return row;
}
private static final class ViewHolder {
public TextView courseCodeTextView;
public TextView courseNameTextView;
public CheckBox courseSelectedCheckBox;
}
CourseDisplay getCourse(int position) {
return ((CourseDisplay) getItem(position));
}
List<CourseDisplay> getBox() {
List<CourseDisplay> box = new ArrayList<CourseDisplay>();
for (CourseDisplay p : mDataSource) {
if (p.getCourseSelected())
box.add(p);
}
return box;
}
}//end class
Here is my CourseDisplay code:
package com.example.android.shustudenthelper;
import static android.R.attr.checked;
public class CourseDisplay{
private String courseCode;
private String courseName;
private boolean courseSelected;
public CourseDisplay(String courseCode, String courseName, boolean courseSelected) {
this.courseCode = courseCode;
this.courseName = courseName;
this.courseSelected = courseSelected;
}
public String getCourseCode() {
return courseCode;
}
public String getCourseName() {
return courseName;
}
public boolean getCourseSelected(){
return courseSelected;
}
}//end class
Here is my database method that gets data from Database:
public List<CourseDisplay> getAllCoursesForRegistration() {
List<CourseDisplay> courses = new ArrayList<>();
openDataBase();
Cursor mCursor = database.query(TABLE_COURSES, new String[] {COLUMN_COURSE_CODE,COLUMN_COURSE_NAME,COLUMN_COURSE_SELECTED,COLUMN_COURSE_SELECTED }, null, null, null, null, null);
if(mCursor.moveToFirst()){
do{
String courseCode = mCursor.getString(0);
String courseName = mCursor.getString(1);
boolean courseSelected = Boolean.parseBoolean(mCursor.getString(2));
courses.add(new CourseDisplay(courseCode, courseName,courseSelected));
}while(mCursor.moveToNext());
}
mCursor.close();
close();//close Database
return courses;
}//end method
Here is my main activity:
public class CourseSelectionActivity extends AppCompatActivity {
public static Button confirm_Button;
public List<String> labels;
private static CheckBox saveCourseCheckBox;
public int checkAccumulator = 0;
private ListView myListView;
CourseSelectionAdapter newAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_selection);
DatabaseOpenHelper myDbHelper = new DatabaseOpenHelper(this);
try {
// check if database exists in app path, if not copy it from assets
myDbHelper.create();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
// open the database
myDbHelper.openDataBase();
myDbHelper.getWritableDatabase();
} catch (SQLException sqle) {
throw sqle;
}
//Display in ListView
populateListView();
// close the database
myDbHelper.close();
onClickConfirmButtonListener();
}//end OnCreate
private void populateListView(){
DatabaseOpenHelper myDbHelper = new DatabaseOpenHelper(this);//New Object of Database
List<CourseDisplay> courseDisplay_data = new ArrayList<CourseDisplay>();
courseDisplay_data = myDbHelper.getAllCoursesForRegistration();
newAdapter = new CourseSelectionAdapter(this,R.layout.custom_listview_layout,courseDisplay_data);
myListView = (ListView)findViewById(R.id.listview_courses);
myListView.setChoiceMode(2);
myListView.setAdapter(newAdapter);
}
public void onClickConfirmButtonListener() {
confirm_Button = (Button) findViewById(R.id.course_register_button);
confirm_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(checkBoxCounter < 1) && checkBoxCounter <= 4) {
showResult();//Show the courses selected.
Toast.makeText(CourseSelectionActivity.this, "You are directed to Notifications", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.example.android.shustudenthelper.NotificationSetupActivity");
startActivity(intent);}
else if (checkBoxCounter > 4){
Toast.makeText(CourseSelectionActivity.this, "You cannot select more than 4 courses", Toast.LENGTH_SHORT).show();
}else if (checkBoxCounter < 1){
Toast.makeText(CourseSelectionActivity.this, "You need to select at least one course", Toast.LENGTH_SHORT).show();
}
}
});
}
public void showResult() {
String result = "Selected Courses are :";
for (CourseDisplay p : newAdapter.getBox()) {
if (p.getCourseSelected()){
result += "\n" + p.getCourseName();
}
}
Toast.makeText(this, result+"\n",Toast.LENGTH_LONG).show();
}
}//end class
Please guide me through this.
First, add a setter method in CourseDisplay class
public boolean setCourseSelected(boolean value){
this.courseSelected = value;
}
In CourseSelectionAdapter class, when a checkbox is click, set the value of the checkbox with the method above
holder.courseSelectedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
checkBoxCounter++;
courseDisplay.setCourseSelected(isChecked);
}else {
checkBoxCounter--;
}
System.out.println("Count is: "+ checkBoxCounter);
}
});
Finally, change showResult() like this
public void showResult() {
String result = "Selected Courses are :";
for (CourseDisplay p : courseDisplay_data) {
if (p.getCourseSelected()){
result += "\n" + p.getCourseName();
}
}
Toast.makeText(this, result+"\n",Toast.LENGTH_LONG).show();
}

How to update the value of the textview inside the fragment on the click of the button present in the adapter class in android?

I have two buttons: + and -. I want that when I click on the button +, the value of the textview present in the fragment class (outside the listview) is changed. How can I do this ?
This is my Adapter class:
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
public CartBaseAdapter(Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
// viewHolder.mImgDelete.setTag(pojoCart.getmCategoryId());
/* try {
URL url = new URL(pojoCart.getmItemImage());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
viewHolder.mImgItem.setImageBitmap(bmp);
} catch (Exception e) {
e.printStackTrace();
// Log.e("exception", "" + e.getMessage());
}*/
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
mValue++;
viewHolder.mTvNumber.setText("" + mValue);
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
// viewHolder.Dish_rate.setVisibility(View.GONE);
Log.e("value1", value1);
Log.e("value2", value2);
z = x * y;
pojoCart.setmItemPrice(String.valueOf(z));
Log.e("z", "" + z);
if (x > 2) {
int n = x - 1;
int k = z / n;
Log.e("k", "" + k);
pojoCart.setmItemPrice(String.valueOf(k));
} else {
pojoCart.setmItemPrice(String.valueOf(z));
}
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
int total = dbh.getTotalOfAmount();
pojoCart.setmTotalPrice(total);
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
if (mValue > 0) {
mValue--;
viewHolder.mTvNumber.setText("" + mValue);
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
if (x >= 1) {
Log.e("value11", value1);
Log.e("value22", value2);
int n = x + 1;
Log.e("n", "" + n);
int k = y / n;
Log.e("k", "" + k);
z = k * x;
Log.e("z", "" + z);
pojoCart.setmItemPrice(String.valueOf(z));
} else {
pojoCart.setmItemPrice(pojoCart.getmItemPrice());
}
}
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
viewHolder.mImgDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
int categoryId = pojoCart.getmCategoryId();
// int id = (Integer) view.getTag();
// id++;
Log.e("removeIdFromTheTable", "" + categoryId);
dbh.delete_byID(categoryId);
mList.remove(position);
notifyDataSetChanged();
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
This is my Fragment Class:
public class Cart extends Fragment implements View.OnClickListener {
private ArrayList<PojoCart> mCartList;
private ListView mListView;
private CartBaseAdapter mCartBaseAdapter;
private DataBaseHandler dbh;
private List<PojoCartDataBase> pojoCartDataBase;
private TextView mTvProcesscheck, mTvTotalPrice;
private String ItemName, ItemPrice;
private String ItemImage;
private ArrayList<String> mTotalPrice;
private Toolbar toolbar;
private int ItemQuantity;
int id = 1;
private String categoryId;
private int sumOfPrice;
private PojoCart pojoCart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cart, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
// addData();
displayTotalAmount();
try {
getDataFromDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initialize() {
mTotalPrice = new ArrayList<String>();
mCartList = new ArrayList<PojoCart>();
mListView = (ListView) getActivity().findViewById(R.id.listview_cart);
mCartBaseAdapter = new CartBaseAdapter(getContext(), mCartList);
Parcelable state = mListView.onSaveInstanceState();
mListView.setAdapter(mCartBaseAdapter);
mListView.onRestoreInstanceState(state);
mTvProcesscheck = (TextView) getActivity().findViewById(R.id.tv_checkout);
mTvTotalPrice = (TextView) getActivity().findViewById(R.id.tv_total_price);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
dbh = new DataBaseHandler(getContext());
mTvProcesscheck.setOnClickListener(this);
toolbar.setTitle("Cart");
mCartBaseAdapter.notifyDataSetChanged();
final RippleView rippleView = (RippleView) getActivity().findViewById(R.id.ripple_view_cart);
rippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
#Override
public void onComplete(RippleView rippleView) {
Log.d("Sample", "Ripple completed");
Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();
toolbar.setTitle("Restaurant List");
}
});
}
/* private void addData() {
for (int i = 0; i < mItemName.length; i++) {
PojoCart pojoCart = new PojoCart();
pojoCart.setmItemName(mItemName[i]);
pojoCart.setmItemPrice(mItemPrice[i]);
pojoCart.setmItemImage(mItemImage[i]);
mCartList.add(pojoCart);
}
// mCartList.add(pojoCartDataBase);
}
*/
private void getDataFromDatabase() throws IOException {
Cursor c = dbh.getAllRows();
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
// int id = c.getInt(0);
int id = c.getInt(1);
Log.e("id.....", "" + id);
ItemName = c.getString(2);
ItemPrice = c.getString(3);
Log.e("itemname", ItemName);
Log.e("itemprice", ItemPrice);
ItemQuantity = c.getInt(4);
Log.e("itemquantity", "" + ItemQuantity);
ItemImage = c.getString(5);
Log.e("itemimage.........", ItemImage);
pojoCart = new PojoCart();
pojoCart.setmItemName(ItemName);
pojoCart.setmItemPrice(ItemPrice);
pojoCart.setmItemImage(ItemImage);
pojoCart.setmQuantity(ItemQuantity);
pojoCart.setmCategoryId(id);
mCartList.add(pojoCart);
mCartBaseAdapter.notifyDataSetChanged();
c.moveToNext();
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_checkout:
/* Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();*/
// toolbar.setTitle("Checkout");
}
}
public void displayTotalAmount() {
int total = dbh.getTotalOfAmount();
mTvTotalPrice.setText(String.valueOf(total));
}
}
I want to change the value of the mTvTotalPric (Textview) on click of the button + and -, which is present at the listview. And the textview which the value I want to change is outside the listview.
In your Adapter class create one interface
Adapter.class
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
private SendDataToFragment sendDataToFragment;
public CartBaseAdapter(FragmentCart fragmentCart, Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
sendDataToFragment = (SendDataToFragment) fragmentCart;
}
//Interface to send data from adapter to fragment
public interface SendDataToFragment {
void sendData(String Data);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
Inside your fragment implement that interface so as soon as your button is clicked in your adapter you will get the data inside your fragment.
Fragment.class
public class FragmentCart extends Fragment implements
View.OnClickListener, CartBaseAdapter.SendDataToFragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout, null);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
CartBaseAdapter adapter = new CartBaseAdapter(FragmentCart.this, getActivity(), yourList);
}
#Override
public void onClick(View v) {
}
#Override
public void sendData(String Data) {
//set this data to your textView
}
}
Create a interface :
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(View view, int value);
}
In your listview adapter use interface like below on click of button + or - like :
MyListener ml;
ml = (MyListener) context;
ml.callback(this, "success");
In activity implements MyListener than callback method override there and than you get performed action from fragment to activity.

ListView with different layouts with two different objects

I want to populate a ListView with different layouts for odd and even rows. It should look like this:
I use two objects "OddListItem" and "EvenListItem" to store/access the data. I do not know how to pass both objects to my custom listview adapter and get the correct view.
My object classes:
public class OddListItem {
private String time_start;
private String time_end;
private String location;
public OddListItem(String time_start, String time_end, String location) {
super();
this.time_start = time_start;
this.time_end = time_end;
this.location = location;
}
// getters and setters
void setTimeStart(String time_start) {
this.time_start = time_start;
}
void setTimeEnd(String time_end) {
this.time_end = time_end;
}
void setLocation(String location) {
this.location = location;
}
public String getTimeStart() {
return time_start;
}
public String getTimeEnd() {
return time_end;
}
public String getLocation() {
return location;
}
}
public class EvenListItem {
private String image;
private String location;
public EvenListItem (String image, String location) {
super();
this.image = image;
this.location = location;
}
// getters and setters
void setImage(String image) {
this.image = image;
}
void setLocation(String location) {
this.location = location;
}
public String getImage() {
return image;
}
public String getLocation() {
return location;
}
}
MyCustomAdapter:
public class MyCustomAdapter extends BaseAdapter {
// Tag for Logging
private static final String TAG = "MyCustomAdapter";
int type;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<OddListItem> mData = new ArrayList<OddListItem>();
private LayoutInflater mInflater;
//private TreeSet mSeparatorsSet = new TreeSet();
private Context context;
public MyCustomAdapter(Context context) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
}
public void addItem(final OddListItem item) {
mData.add(item);
//The notification is not necessary since the items are not added dynamically
//notifyDataSetChanged();
}
public void addSeparatorItem(final OddListItem item) {
mData.add(item);
//The notification is not necessary since the items are not added dynamically
//notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
/*if ((position%2) == 0){
type = TYPE_ITEM;
} else {
type = TYPE_SEPARATOR;
}
return type;*/
return position%2;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public OddListItem getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
Log.d(TAG, "getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
//inflate the new layout
convertView = mInflater.inflate(R.layout.detail_list_row_odd, parent, false);
holder.tv_time_from = (TextView) convertView.findViewById(R.id.tv_time_from);
holder.tv_time_to = (TextView) convertView.findViewById(R.id.tv_time_to);
holder.tv_current_location_odd = (TextView) convertView.findViewById(R.id.tv_current_location_odd);
//fill the layout with values
/*holder.tv_time_from.setText("12:34");
holder.tv_time_to.setText("12:37");
holder.tv_current_location_odd.setText("Aktueller Standort");*/
holder.tv_time_from.setText(mData.get(position).getTimeStart());
holder.tv_time_to.setText(mData.get(position).getTimeEnd());
holder.tv_current_location_odd.setText(mData.get(position).getLocation());
break;
case TYPE_SEPARATOR:
//inflate the new layout
convertView = mInflater.inflate(R.layout.detail_list_row_even, parent, false);
holder.tv_current_location_even = (TextView) convertView.findViewById(R.id.tv_current_location_even);
holder.img_transport = (ImageView) convertView.findViewById(R.id.img_transport);
//fill the layout with values
holder.tv_current_location_even.setText("Hauptbahnhof");
holder.img_transport.setImageDrawable(context.getResources().getDrawable(R.drawable.rollator));
break;
default:
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
private static class ViewHolder {
public TextView tv_time_from;
public TextView tv_time_to;
public TextView tv_current_location_odd;
public TextView tv_current_location_even;
public ImageView img_transport;
}
}
Here I generate the data and call the adapter:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_connection);
generateData();
//fill ListView with custom content from MyCustomAdapter class
mAdapter = new MyCustomAdapter(getApplicationContext());
for (int i = 1; i < odd_items.size(); i++) {
mAdapter.addItem(odd_items.get(i));
if (i % 1 == 0) {
mAdapter.addSeparatorItem(odd_items.get(i));
}
}
setListAdapter(mAdapter);
//set duration text
tv_duration = (TextView)findViewById(R.id.tv_duration);
tv_duration.setText("Dauer: 22 Minuten");
}
private void generateData() {
odd_items = new ArrayList<OddListItem>();
odd_items.add(new OddListItem("12:34", "", "Aktueller Standort"));
odd_items.add(new OddListItem("12:37", "12:37", "TUM"));
odd_items.add(new OddListItem("12:42", "12:42", "Hauptbahnhof Nord"));
odd_items.add(new OddListItem("12:48", "12:48", "Hauptbahnhof"));
even_items = new ArrayList<EvenListItem>();
even_items.add(new EvenListItem("R.drawable.rollator", "3 Minuten Fußweg"));
even_items.add(new EvenListItem("R.drawable.bus", "Richtung Hauptbahnhof Nord"));
even_items.add(new EvenListItem("R.drawable.rollator", "6 Minuten Fußweg"));
mData = new Data(odd_items, even_items);
}
Any help would be great. Maybe there is also a better approach then please let me know.
I would create a Single list of Items
public class Items {
private String time_start;
private String time_end;
private String location;
private int image;
private String locationeven;
private int oddoreven;
public String getTime_start() {
return time_start;
}
public void setTime_start(String time_start) {
this.time_start = time_start;
}
public String getTime_end() {
return time_end;
}
public void setTime_end(String time_end) {
this.time_end = time_end;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getLocationeven() {
return locationeven;
}
public void setLocationeven(String locationeven) {
this.locationeven = locationeven;
}
public int getOddoreven() {
return oddoreven;
}
public void setOddoreven(int oddoreven) {
this.oddoreven = oddoreven;
}
}
In onCreate of Activity call
generateData() ;
Then
ArrayList<Items> oddorevenlist = new ArrayList<Items>();
private void generateData() {
Items item1 = new Items();
item1.setTime_start("12:34");
item1.setTime_end("");
item1.setLocation("Aktueller Standort");
item1.setOddoreven(0);
oddorevenlist.add(item1);
Items item2 = new Items();
item2.setImage(R.drawable.ic_launcher);
item2.setLocationeven("3 Minuten Fußweg");
item2.setOddoreven(1);
oddorevenlist.add(item2);
Items item3 = new Items();
item3.setTime_start("12:37");
item3.setTime_end("12:37");
item3.setLocation("Tum");
item3.setOddoreven(0);
oddorevenlist.add(item3);
Items item4 = new Items();
item4.setImage(R.drawable.ic_launcher);
item4.setLocationeven("Richtung Hauptbahnhof Nord");
item4.setOddoreven(1);
oddorevenlist.add(item4);
Items item5 = new Items();
item5.setTime_start("12:42");
item5.setTime_end("12:42");
item5.setLocation("Hauptbahnhof Nord");
item5.setOddoreven(0);
oddorevenlist.add(item5);
Items item6 = new Items();
item6.setImage(R.drawable.ic_launcher);
item6.setLocationeven("R6 Minuten Fußweg");
item6.setOddoreven(1);
oddorevenlist.add(item6);
Items item7 = new Items();
item7.setTime_start("12:48");
item7.setTime_end("12:48");
item7.setLocation("HHauptbahnhof");
item7.setOddoreven(0);
oddorevenlist.add(item7);
MyCustomAdapter mAdapter = new MyCustomAdapter(this,oddorevenlist);
setListAdapter(mAdapter);
}
Adapter code
public class MyCustomAdapter extends BaseAdapter {
// Tag for Logging
private static final String TAG = "MyCustomAdapter";
int type;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private ArrayList<Items> oddorevenlist ;
private LayoutInflater mInflater;
private Context context;
public MyCustomAdapter(Context context, ArrayList<Items> oddorevenlist) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.oddorevenlist = oddorevenlist;
}
#Override
public int getItemViewType(int position) {
if (oddorevenlist.get(position).getOddoreven()==0){
type = TYPE_ITEM;
} else if (oddorevenlist.get(position).getOddoreven()==1) {
type = TYPE_SEPARATOR;
}
return type;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return oddorevenlist.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
Log.d(TAG, "getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
//inflate the new layout
convertView = mInflater.inflate(R.layout.row_odd, parent, false);
holder.tv_time_from = (TextView) convertView.findViewById(R.id.tv_time_from);
holder.tv_time_to = (TextView) convertView.findViewById(R.id.tv_time_to);
holder.tv_current_location_odd = (TextView) convertView.findViewById(R.id.tv_current_location_odd);
holder.tv_time_from.setText(oddorevenlist.get(position).getTime_start());
holder.tv_time_to.setText(oddorevenlist.get(position).getTime_end());
holder.tv_current_location_odd.setText(oddorevenlist.get(position).getLocation());
break;
case TYPE_SEPARATOR:
//inflate the new layout
convertView = mInflater.inflate(R.layout.row_even, parent, false);
holder.tv_current_location_even = (TextView) convertView.findViewById(R.id.tv_current_location_even);
holder.img_transport = (ImageView) convertView.findViewById(R.id.img_transport);
//fill the layout with values
holder.tv_current_location_even.setText(oddorevenlist.get(position).getLocationeven());
holder.img_transport.setImageResource(R.drawable.ic_launcher);
break;
default:
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
private static class ViewHolder {
public TextView tv_time_from;
public TextView tv_time_to;
public TextView tv_current_location_odd;
public TextView tv_current_location_even;
public ImageView img_transport;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
}
Snap

Categories

Resources