I am working on a screen where i am populating a list view using base adapter.Each row of list view contains a circular image view,Text View and Check box .On clicking single tick on toolbar ,i am displaying the id of user corresponding to checked button But it is displayed wrongly.I am implementing the following screen:
1.Bean_Friends
public class Bean_Friends {
private String name, url, extension, friendsID;
private String friendSelected = "false";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getFriendsID() {
return friendsID;
}
public void setFriendsID(String friendsID) {
this.friendsID = friendsID;
}
public String getFriendSelected() {
return friendSelected;
}
public void setFriendSelected(String friendSelected) {
this.friendSelected = friendSelected;
}
}
2.Adapter_Friends_Group.java
public class Adapter_Friends_Group extends BaseAdapter {
private Context context;
public List<Bean_Friends> listBeanFriends;
private LayoutInflater inflater;
private ApiConfiguration apiConfiguration;
private Bean_Friends bean_friends;
public Adapter_Friends_Group(Context context, List<Bean_Friends> listBeanFriends) {
this.context = context;
this.listBeanFriends = listBeanFriends;
}
#Override
public int getCount() {
return listBeanFriends.size();
}
#Override
public Object getItem(int i) {
return listBeanFriends.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (inflater == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (view == null) {
view = inflater.inflate(R.layout.feed_item_friends, null);
}
//finding different views
ImageView pic = (ImageView) view.findViewById(R.id.friendsImage);
TextView txtName = (TextView) view.findViewById(R.id.nameFriends);
CheckBox chkFriends = (CheckBox) view.findViewById(R.id.chkFriends);
bean_friends = listBeanFriends.get(i);
String name = bean_friends.getName();
String url = bean_friends.getUrl();
String extension = bean_friends.getExtension();
apiConfiguration = new ApiConfiguration();
String api = apiConfiguration.getApi();
String absolute_url = api + "/" + url + "." + extension;
//loading image into ImageView iew
Picasso.with(context).load(absolute_url).error(R.drawable.default_avatar).into(pic);
//Setting name in the textview
txtName.setText(name);
//If check box is checked,then add true to bean else add false to bean
if (chkFriends.isChecked()) {
bean_friends.setFriendSelected("true");
} else {
bean_friends.setFriendSelected("false");
}
chkFriends.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
if (cb.isChecked()) {
bean_friends.setFriendSelected("true");
Toast.makeText(context, "Check Box is checked : " + cb.isChecked(), Toast.LENGTH_SHORT).show();
} else {
bean_friends.setFriendSelected("false");
}
}
});
return view;
}
}
3. Code of Activity containing view
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_new_group, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.createGroup:
createNewGroup();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void createNewGroup() {
Toast.makeText(NewGroupActivity.this, "clicked", Toast.LENGTH_SHORT).show();
List<Bean_Friends> listBeanFriends = new ArrayList<>();
//Log.e("Size of listbeanFriends", String.valueOf(listBeanFriends.size()));
listBeanFriends = adapter_friends_group.listBeanFriends;
// Log.e("Size of adapter_friends", String.valueOf(adapter_friends_group.listBeanFriends.size()));
Log.e("Size of listbeanFriends", String.valueOf(listBeanFriends.size()));
for (int i = 0; i < listBeanFriends.size(); i++) {
Log.e("Loop Working", String.valueOf(i));
Bean_Friends bean_friends = listBeanFriends.get(i);
String friendID = bean_friends.getFriendsID();
String friendSelected = bean_friends.getFriendSelected();
String friendName = bean_friends.getName();
Log.e("FriendsName", friendName);
Log.e("FriendID", friendID);
Log.e("friendSelected", friendSelected);
if (friendSelected.equals("true")) {
Toast.makeText(NewGroupActivity.this, friendID, Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(NewGroupActivity.this,"true",Toast.LENGTH_SHORT).show();
}
}
}
Updated code:
Solved the issue after doing the following changes:
Adapter
public class Adapter_Friends_Group extends BaseAdapter {
private Context context;
public List<Bean_Friends> listBeanFriends;
private LayoutInflater inflater;
private ApiConfiguration apiConfiguration;
private Bean_Friends bean_friends;
public Adapter_Friends_Group(Context context, List<Bean_Friends> listBeanFriends) {
this.context = context;
this.listBeanFriends = listBeanFriends;
}
private class ViewHolder {
ImageView imageView;
TextView txtName;
CheckBox chkFriend;
}
#Override
public int getCount() {
return listBeanFriends.size();
}
#Override
public Object getItem(int i) {
return listBeanFriends.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder = null;
if (inflater == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (view == null) {
view = inflater.inflate(R.layout.feed_item_friends, null);
viewHolder = new ViewHolder();
viewHolder.imageView = (ImageView) view.findViewById(R.id.friendsImage);
viewHolder.txtName = (TextView) view.findViewById(R.id.nameFriends);
viewHolder.chkFriend = (CheckBox) view.findViewById(R.id.chkFriends);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
bean_friends = listBeanFriends.get(i);
String name = bean_friends.getName();
String url = bean_friends.getUrl();
String extension = bean_friends.getExtension();
apiConfiguration = new ApiConfiguration();
String api = apiConfiguration.getApi();
String absolute_url = api + "/" + url + "." + extension;
//loading image into ImageView iew
Picasso.with(context).load(absolute_url).error(R.drawable.default_avatar).into(viewHolder.imageView);
//Setting name in the textview
viewHolder.txtName.setText(name);
//Setting boolean isSelected if the Checkbox is checked
viewHolder.chkFriend.setChecked(bean_friends.isSelected());
viewHolder.chkFriend.setTag(bean_friends);
viewHolder.chkFriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Bean_Friends bean_friends = (Bean_Friends) cb.getTag();
Toast.makeText(context, "Clicked on Checkbox: " + bean_friends.getName() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
bean_friends.setIsSelected(cb.isChecked());
}
});
return view;
}
}
Bean
public class Bean_Friends {
private String name, url, extension, friendsID;
boolean isSelected;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getFriendsID() {
return friendsID;
}
public void setFriendsID(String friendsID) {
this.friendsID = friendsID;
}
public boolean isSelected() {
return isSelected;
}
public void setIsSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
Method inside Activity
public void createNewGroup() {
StringBuffer responseText = new StringBuffer();
listBeanFriends = adapter_friends_group.listBeanFriends;
// Log.e("Size of adapter_friends", String.valueOf(adapter_friends_group.listBeanFriends.size()));
Log.e("Size of listbeanFriends", String.valueOf(listBeanFriends.size()));
for (int i = 0; i < listBeanFriends.size(); i++) {
Log.e("Loop Working", String.valueOf(i));
Bean_Friends bean_friends = listBeanFriends.get(i);
String friendID = bean_friends.getFriendsID();
String friendName = bean_friends.getName();
Log.e("FriendsName", friendName);
Log.e("FriendID", friendID);
Log.e("FriendSelected", String.valueOf(bean_friends.isSelected()));
if (bean_friends.isSelected()) {
responseText.append("\n" + bean_friends.getName() + " " + bean_friends.getFriendsID());
}
}
Toast.makeText(NewGroupActivity.this, responseText, Toast.LENGTH_SHORT).show();
}
I think the mistake is in this line :-
//If check box is checked,then add true to bean else add false to bean
if (chkFriends.isChecked()) {
bean_friends.setFriendSelected("true");
} else {
bean_friends.setFriendSelected("false");
}
Here you are setting 'setFriendSelected' based on whether the chkFriends is checked or not. In list View the views are reused and if say you have checked 'A' as friend and then you scrolls down then the view of 'A' maybe reused in 'C' and by this code 'C' now will be checked as friend. Here you instead want to inflate your checkBox view according to whether 'C' is your friend or not. Try this instead:-
//If check box is checked,then add true to bean else add false to bean
if (bean_friends.getFriendSelected().equals("true")) {
chkFriends.setChecked(true);
} else {
chkFriends.setChecked(false);
}
P.S : you can use view holder pattern here for better performance.
Related
In my App, I'm using Custom Listview, where I need to delete an item from Listview as well as corresponding row from CSV file simultaneously when Listview is long clicked.
My CSV file looks like this
2020/11/22,10:30PM,96.3°F,Normal,Body
2020/11/22,10:30PM,98.2°F,Normal,Body
2020/11/22,10:31PM,96.7°F,Normal,Body
2020/11/22,10:40PM,95.0°F,Normal,Body
For instance, if second item from Listview is removed when long clicked, the corresponding data row from CSV file above which is second row on CSV file should also be removed when Listview is long clicked.
Here's my Code:
LogViewActivity.java
public class LogViewActivity extends BaseAppCompatActivity {
private static final String TAG = "LogViewActivity";
private File logFile;
private Toolbar toolbar;
private ListView lvproducts;
ArrayList<Product> list;
ProductAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.log_view_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
public void onResume() {
super.onResume();
logFile = (File) getIntent().getExtras().get(Constants.EXTRA_LOG_FILE);
if (logFile != null) {
toolbar.setTitle(logFile.getName());
try {
setLogText(logFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_log_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.action_send_to:
intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(logFile), "text/plain");
startActivity(intent);
break;
default:
Log.e(TAG, "Unknown id");
break;
}
return super.onOptionsItemSelected(item);
}
private void setLogText(File file) throws FileNotFoundException {
// Textview visisbility is invisible and used only for setting up String data.
TextView textView1 = (TextView) findViewById(R.id.tvview1);
TextView textView2 = (TextView) findViewById(R.id.tvview2);
TextView textView3 = (TextView) findViewById(R.id.tvview3);
TextView textView4 = (TextView) findViewById(R.id.tvview4);
TextView textView5 = (TextView) findViewById(R.id.tvview5);
lvproducts = (ListView) findViewById(R.id.lvproducts);
list =new ArrayList<Product>();
Scanner inputStream;
inputStream = new Scanner(file);
while(inputStream.hasNext()){
String line= inputStream.next();
if (line.equals("")) { continue; } // <--- notice this line
String[] values = line.split(",");
String V = values[0];
String W= values[1];
String X= values[2];
String Y= values[3];
String Z= values[4];
// Textview visisbility is invisible and used only for setting up String data.
textView1.setText(Z);
textView2.setText(X);
textView3.setText(Y);
textView4.setText(V);
textView5.setText(W);
Product product1 = new Product(textView1.getText().toString(), textView2.getText().toString(), textView3.getText().toString(), textView4.getText().toString(), textView5.getText().toString());
list.add(product1);
adapter = new ProductAdapter(LogViewActivity.this, list);
lvproducts.setAdapter(adapter);
}
inputStream.close();
lvproducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int which_item = position;
new AlertDialog.Builder(LogViewActivity.this)
.setTitle(getResources().getString(R.string.delete_log_file_title))
.setMessage(getResources().getString(R.string.delete_log_file_text) + "\n"
+ getResources().getString(R.string.file_name))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(which_item);
adapter.notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
}
});
}
}
Product.java
public class Product {
private String mode;
private String temp;
private String condition;
private String dates;
private String times;
public Product(String mode, String temp, String condition, String dates, String times) {
this.mode = mode;
this.temp = temp;
this.condition = condition;
this.dates = dates;
this.times = times;
}
public String getMode() {
return mode;
}
public String getTemp() {
return temp;
}
public String getCondition() {
return condition;
}
public String getDates() {
return dates;
}
public String getTimes() {
return times;
}
}
ProductAdapter.java
public class ProductAdapter extends ArrayAdapter<Product> {
private final Context context;
private final ArrayList<Product> values;
public ProductAdapter(#NonNull Context context, ArrayList<Product> list) {
super(context, R.layout.row_layout, list);
this.context = context;
this.values = list;
}
#SuppressLint("ResourceAsColor")
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview = inflater.inflate(R.layout.row_layout, parent, false);
CardView cdview = (CardView) rowview.findViewById(R.id.cdview);
TextView tvtemp = (TextView) rowview.findViewById(R.id.tvtemp);
TextView tvcondition = (TextView) rowview.findViewById(R.id.tvcondition);
TextView tvdate = (TextView) rowview.findViewById(R.id.tvdate);
TextView tvtime = (TextView) rowview.findViewById(R.id.tvtime);
ImageView ivmode = (ImageView) rowview.findViewById(R.id.ivmode);
tvtemp.setText(values.get(position).getTemp());
tvcondition.setText(values.get(position).getCondition());
tvdate.setText(values.get(position).getDates());
tvtime.setText(values.get(position).getTimes());
if(values.get(position).getMode().equals("Object") && (values.get(position).getCondition().equals("None")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_blue);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.homewhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("Normal")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backgreen);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("Low-Grade-Fever")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backyellow);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("High-Fever")) && (!values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backred);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("HIGH")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.backred);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("LOW")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_low);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Body") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_black);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.headwhite);
}
else if(values.get(position).getMode().equals("Object") && (values.get(position).getCondition().equals("None")) && (values.get(position).getTemp().equals("No-Data")))
{
Drawable draw8 = cdview.getResources().getDrawable(R.drawable.back_black);
cdview.setBackground(draw8);
ivmode.setImageResource(R.drawable.homewhite);
}
return rowview;
}
}
Please help me out. Thank you!
You are only removing item from the loaded data set, therefore only list item is removing. You need to update your csv file on removal of list item
lvproducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int which_item = position;
new AlertDialog.Builder(LogViewActivity.this)
.setTitle(getResources().getString(R.string.delete_log_file_title))
.setMessage(getResources().getString(R.string.delete_log_file_text) + "\n"
+ getResources().getString(R.string.file_name))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(which_item);
adapter.notifyDataSetChanged();
updateCSVFile();
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
}
});
public void updateCSVFile() {
// Write your logic her to update CSV file after item removal.
}
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;
}
I am getting value from checking page adapter.If click the plus image in one list item the count value get increase.I want to update that particular value of child item in expandablelistview adapter.How to update that particular child value from checking page adapter.
Checkinapadater:
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Movie1 m = movieItems.get(position);
if (m.getfood_totalprice() != null) {
if (!m.getfood_totalprice().equals("null")) {
holder.amount.setText(m.getfood_totalprice());
}
}
if (m.getfood_count() != null) {
if (!m.getfood_count().equals("null")) {
holder.item_count.setText(m.getfood_count());
}
}
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = Integer.parseInt(holder.item_count.getText().toString());
if(i>=0){
int count = i + 1;
holder.item_count.setText(Integer.toString(count));
value = Integer.toString(count);
}
});
holder.minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = Integer.parseInt(holder.item_count.getText().toString());
if(i>0){
int count = i - 1;
holder.item_count.setText(Integer.toString(count));
}
});
}
Exapanadablelistapater:
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final Child child = (Child) getChild(groupPosition, childPosition);
final Child modelChild = groups.get(groupPosition).getItems().get(childPosition);
if (convertView == null) {
LayoutInflater inflator = LayoutInflater.from(parent.getContext());
convertView = inflator.inflate(R.layout.detail_list, null);
viewHolder = new ViewHolder();
viewHolder.minus = (ImageView) convertView.findViewById(R.id.minus);
viewHolder.plus = (ImageView) convertView.findViewById(R.id.plus);
viewHolder.green = (ImageView) convertView.findViewById(R.id.green);
viewHolder.red = (ImageView) convertView.findViewById(R.id.red);
viewHolder.item_count = (TextView) convertView.findViewById(R.id.count);
//viewHolder.txtView = (TextView) ((AppCompatActivity)context).findViewById(R.id.checked_item);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv.setText(child.getName());
viewHolder.amount.setText(child.getPrice());
viewHolder.item_count.setText(Integer.toString(child.getCount()));
viewHolder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(modelChild.getCount()>=0) // set your count default 0 when you bind data initially
{
int count = (modelChild.getCount()) + 1;
modelChild.setCount(count);
int s= Integer.parseInt(Detailpage.item.getText().toString());
itemname.setText(Integer.toString(count1));
// viewHolder.txtView.setText(Integer.toString(count1)+"items");
count1=s+1;
Detailpage.item.setText(Integer.toString(count1));
int foodprice=0;
foodprice=Integer.parseInt(child.getPrice());
total1=child.getPrice();
value=Integer.toString(modelChild.getcount());
//
name = modelChild.getName();
id=child.getId();
new AsyncT().execute(user_id,res_id,id,name,total1,value);
groups.get(groupPosition).getItems().set(childPosition, modelChild);
notifyDataSetChanged();
}
}});
viewHolder.minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(modelChild.getCount()>0) // set your count default 0 when you bind data initially
{ int count = modelChild.getCount() - 1;
modelChild.setCount(count);
int s= Integer.parseInt(Detailpage.item.getText().toString());
count1=s-1;
Detailpage.item.setText(Integer.toString(count1));
name=modelChild.getName();
//
int foodprice=0;
foodprice=Integer.parseInt(child.getPrice());
int total = foodprice * child.getcount();
total1=child.getPrice();
// total1=Integer.toString(total);
value=Integer.toString(count);
id=child.getId();
if(count>0) {
new AsyncT().execute(user_id, res_id, id, name, total1, value);
}
}
modelChild.setChildName(modelChild.getChildName());
// set your other items if any like above
groups.get(groupPosition).getItems().set(childPosition, modelChild);
notifyDataSetChanged();
}
});
return convertView;
}
Movie1 model(checkin page):`
public class Movie1 {
public String food_id,food_count,food_item,food_price,food_resid,food_totalprice;
public void setfood_id(String food_id) {
this.food_id = food_id;
}
public void setfood_count(String food_count) {
this.food_count = food_count;
}
public void setfood_price(String food_price) {
this.food_price = food_price;
}
public void setfood_item(String food_item) {
this.food_item = food_item;
}
public String getfood_item() {
return food_item;
}
public String getfood_count() {
return food_count;
}
public String getfood_price() {
return food_price;
}
public void setfood_resid(String food_resid) {
this.food_resid = food_resid;
}
public String getfood_resid() {
return food_resid;
}
public String getfood_id() {
return food_id;
}
public void setfood_totalprice(String food_totalprice) {
this.food_totalprice = food_totalprice;
}
public String getfood_totalprice() {
return food_totalprice;
}
}
`
Child model:(Expandable listview)
public class Child {
private String Name,childName,item_status,image1,available_from,available_to,price,id,status;
private int Image,count;
public Object getstatus;
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public int getImage() {
return Image;
}
public void setImage(int Image) {
this.Image = Image;
}
public void setcount(int count) {
this.count = count;
}
public int getcount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getChildName() {
return childName;
}
public int getCount() {
return count;
}
public void setChildName(String childName) {
this.childName = childName;
}
public void setItem_status(String item_status) {
this.item_status = item_status;
}
public void setImage1(String image1) {
this.image1 = image1;
}
public void setAvailable_to(String available_to) {
this.available_to = available_to;
}
public void setAvailable_from(String available_from) {
this.available_from = available_from;
}
public void setPrice(String price) {
this.price = price;
}
public void setId(String id) {
this.id = id;
}
public String getPrice() {
return price;
}
public String getImage1() {
return image1;
}
public String getItem_status() {
return item_status;
}
public String getId() {
return id;
}
public void setstatus(String status) {
this.status = status;
}
public String getstatus() {
return status;
}
}
`checkin
Expandablelist adapter
In my application have a listview where in i have to dispaly 4 values with a checkbox as each list item... the values are coming from the database.. the problem is the values from the database are not getting assigned to the listitem text views..;
This is the Activity where i am assigning
private List<PaymentDueModel> getModel() {
List<PaymentDueModel> list = new ArrayList<PaymentDueModel>();
try {
Cursor cursor = database.fetchCursor("member_dues", new String[] {
"INST_DUE_DATE", "PDI_AMOUNT", "TXNTYPE" },
"MEMBERSHIP_ID = '" + MEMBERSHIP_ID + "'", null, null,
null, null, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
do {
list.add(get(cursor.getString(0), cursor
.getString(1), cursor.getString(2)));
} while (cursor.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
list = null;
}
Log.e("list",list.toString());
return list;
}
private PaymentDueModel get(String n,String t, String s) {
return new PaymentDueModel(n,t,s);
}
This is the adapter:
public class PendingListAdapter extends ArrayAdapter<PaymentDueModel> {
private final List<PaymentDueModel> list;
private final Activity context;
public PaymentDueModel element;
public PendingListAdapter(Activity context, List<PaymentDueModel> list) {
super(context, R.layout.list_item_pending, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
TextView dueDate;
TextView amount;
TextView paymentType;
CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
try
{
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.list_item_pending, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.dueDate =(TextView)view.findViewById(R.id.txt_due_date);
viewHolder.amount=(TextView)view.findViewById(R.id.txt_amount);
viewHolder.paymentType=(TextView)view.findViewById(R.id.txt_payment_type);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check_Status);
// viewHolder.checkbox
// .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//
// #Override
// public void onCheckedChanged(CompoundButton buttonView,
// boolean isChecked) {
// PaymentDueModel element = (PaymentDueModel) viewHolder.checkbox
// .getTag();
//
// }
// });
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.checkbox.setChecked(list.get(position).isSelected());
holder.dueDate.setTag(list.get(position).getdueDate());
holder.amount.setTag(list.get(position).getamount());
holder.paymentType.setTag(list.get(position).getpaymentType());
}
catch(Exception e)
{
e.printStackTrace();
}
return view;
}
}
This the getter setter class:
public class PaymentDueModel {
private String dueDate;
private String amount;
private String paymentType;
private boolean selected;
public PaymentDueModel(String dueDate, String amount, String paymentType) {
this.dueDate = dueDate;
this.amount = amount;
this.paymentType = paymentType;
selected = false;
}
public String getdueDate() {
return dueDate;
}
// public void setdueDate(String dueDate) {
// this.dueDate = dueDate;
// }
public String getamount() {
return amount;
}
// public void setamount(String amount) {
// this.amount = amount;
// }
public String getpaymentType() {
return paymentType;
}
// public void setpaymentType(String paymentType) {
// this.paymentType = paymentType;
// }
public boolean isSelected() {
return selected;
}
public void setselected(boolean selected) {
this.selected = selected;
}
}
The adapter is set in onCreate.
Here i am setting the adapter..
pending_adapter = new PendingListAdapter(getActivity(), getModel());
member_pending_list.setAdapter(pending_adapter);
Please help...am not able to figure out the issue..
Instead of setTag
holder.dueDate.setTag(list.get(position).getdueDate());
holder.amount.setTag(list.get(position).getamount());
holder.paymentType.setTag(list.get(position).getpaymentType());
use setText
holder.dueDate.setText(list.get(position).getdueDate());
holder.amount.setText(list.get(position).getamount());
holder.paymentType.setText(list.get(position).getpaymentType());
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