How to get sum from textview in list layout? - android

I'm having problem with coding how to count all numbers that user inserted in TextView in ListView...
Here is my app... All I need to now is how to get the sum from rows in list view and show them in another text view:
This is my Main Activity:
public class MainActivity extends Activity {
private Adapter adapter;
private ArrayList<Ruka> fetch = new ArrayList<Ruka>();
Button bt;
EditText et;
TextView tv;
TextView mi;
TextView vi;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Inflate the menu; this adds items to the action bar if it is present.
bt = (Button) findViewById(R.id.button1);
et = (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.textView1);
mi = (TextView) findViewById(R.id.textViewMi);
vi = (TextView) findViewById(R.id.textViewVi);
lv = (ListView) findViewById(R.id.lista);
// final String input = et.getText().toString();
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (et.getText().length() == 0) {
Toast.makeText(this, "test",
Toast.LENGTH_SHORT).show();
return;
}
if (Float.valueOf(et.getText().toString()) >= 12) {
Toast.makeText(this,
"test2", Toast.LENGTH_SHORT)
.show();
return;
}
String input = et.getText().toString();
if (null != input && input.length() > 0) {
String maxpunti = "11";
int a = Integer.parseInt(maxpunti);
int b = Integer.parseInt(input);
int c = a - b;
String input2 = String.valueOf(c);
Ruka one = new Ruka(input, input2);
fetch.add(one);
et.setText("");
adapter = new Adapter(MainActivity.this, R.id.lista, fetch);
lv.setAdapter(adapter);
}
}
});
}
}
This is my Adapter:
public class Adapter extends ArrayAdapter<Ruka>{
private ArrayList<Ruka> entries;
private Activity activity;
public Adapter(Activity a, int textViewResourceId, ArrayList<Ruka> entries) {
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.textView1);
holder.item2 = (TextView) v.findViewById(R.id.textView2);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final Ruka custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.getFirst());
holder.item2.setText(custom.getSecond());
}
return v;
}
}
UPDATE
Here is Ruka.java:
public class Ruka {
private String customBig;
private String customSmall;
public Ruka(String string, String string2) {
this.customBig = string;
this.customSmall = string2;
}
public String getFirst() { return customBig; }
public void setcustomBig(String getFirst) { this.customBig = getFirst; }
public String getSecond() { return customSmall; }
public void setcustomSmall(String getSecond) { this.customSmall = getSecond; }
}
If someone can find solution... Please... Anyone :)

I would say add a method to your adapter that does this:
public int getSum(){
int sum;
for(Ruka ruka: entries){
sum += ruka.getFirst();
}
}
Assuming ruka.getFirst() is a numeric value.

Related

Android - Delete an item from Custom Listview and update it when long clicked

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.
}

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.

Android custom listview layout

im new to android and java programming. Im having trouble getting my custom layout (currently with only one textview in it to work with my code. I have followed many tutorials and look and many examples but still Im getting confused as to how I would integrate it with my existing code.
Any help would be appreciated.
Here is my code:
public class checkListActivity extends MainActivity {
static String filename = "checkList";
String currentList;
SharedPreferences checkListData;
SharedPreferences.Editor checkListEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.checklist);
Button bAddItem = (Button) findViewById(R.id.bAddItem);
final EditText etItemName = (EditText) findViewById(R.id.etItemName);
final TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckLists);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String selectedItem = extras.getString("selectedItem");
// get the value based on the key
currentList = selectedItem;
}
tvTitle.setText(currentList);
checkListData = getSharedPreferences(filename, 0);
updateListView();
// Button Click Listener
bAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String checkListStringData = etItemName.getText().toString();
checkListData = getSharedPreferences(filename, 0);
SharedPreferences.Editor checkListEditor = checkListData.edit();
checkListEditor.putString(currentList + "ItemName",
checkListStringData);
checkListEditor.commit();
String checkListDataReturned = checkListData.getString(
currentList + "ItemName", currentList);
tvTitle.setText(checkListDataReturned);
updateListView();
etItemName.setText("");
};
});
}
private void updateListView() {
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckList);
Map<String, ?> keys = checkListData.getAll();
ArrayList<String> checkListStrings = new ArrayList<String>();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
if (entry.getValue() instanceof String) {
if (entry.getKey().equals(currentList + "ItemName")) {
checkListStrings.add((String) entry.getValue());
}
}
ArrayAdapter<String> checkListArrayAdapter = new ArrayAdapter<String>(
this, R.layout.single_listview_item);
lvCheckList.setAdapter(checkListArrayAdapter);
}
}
}
first create this custom adapter class...
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public Context con;
public String[] sms;
public EfficientAdapter(Context context,String[] rssFeed) {
mInflater = LayoutInflater.from(context);
this.con=context;
this.sms=rssFeed;
}
public int getCount() {
return sms.length;
}
public Object getItem(int position) {
return sms[position];
}
public long getItemId(int position) {
return position;
}
#SuppressLint({ "SdCardPath", "InflateParams", "ResourceAsColor" })
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder();
holder.text2 = (TextView) convertView.findViewById(R.id.text_list_f);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text2.setText(sms[position]);
}
return convertView;
}
}
static class ViewHolder {
TextView text2;
}
then use it in your activity ...
list.setAdapter(new EfficientAdapter(this, your array));

Android - How to delete multiple items from listView with checkBox ?

i have an issue when i try to delete multiple checked items from my listView. If i start deleting from down to up items are removed from my list, but there is a problem when i do it from up to down or if random items are checked. The problem is the checked items are not deleted, but the unchecked items are deleted.
public class MainActivity extends ActionBarActivity {
private EditText etn,etl,etd;
private Button add;
private Button rmv;
private ListView listView;
private ArrayList<Data> list;
private MyCustomAdapter dataAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
listView = (ListView) findViewById(R.id.listView1);
list = new ArrayList<Data>();
add = (Button) findViewById(R.id.btn_add);
etn = (EditText) findViewById(R.id.edit_name);
eta = (EditText) findViewById(R.id.edit_lastname);
etd = (EditText) findViewById(R.id.edit_document);
rmv = (Button) findViewById(R.id.btn_delete);
displayView();
}
public class Data {
long document;
String name;
String lastname;
boolean selected = false;
public Data(long document, String name, String lastname, boolean selected){
this.document=document;
this.name=nom;
this.lastname=lastname;
this.selected = selected;
}
public String getName(){
return name;
}
public String getLastName(){
return lastname;
}
public long getDocument(){
return document;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
public void displayView(){
String name = etn.getText().toString();
String lastname= eta.getText().toString();
long document = Integer.valueOf(etd.getText().toString());
Data edata = new Data(document,name,lastname,false);
list.add(edata);
dataAdapter = new MyCustomAdapter(this,
R.layout.list_info, list);
listView.setAdapter(dataAdapter);
}
public void delete(View view){
deleteListItem();
}
private void deleteListItem(){
if(list.isEmpty()){
Toast.makeText(getApplicationContext(),
"No items to delete.",
Toast.LENGTH_LONG).show();
return;
}
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = list.get(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
dataAdapter.notifyDataSetChanged();
}
private class MyCustomAdapter extends ArrayAdapter<Data> {
private ArrayList<Data> list;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Data> list) {
super(context, textViewResourceId, list);
this.list = new ArrayList<Data>();
this.list.addAll(list);
}
private class ViewHolder {
TextView name;
TextView lname;
TextView doc;
CheckBox ck;
}
#Override
public View getView(int position, View convertView, ViewGroupparent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.ck = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.lname = (TextViewconvertView.findViewById(R.id.lastname);
holder.doc = (TextView)convertView.findViewById(R.id.document);
convertView.setTag(holder);
holder.ck.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Data edata = (Data) cb.getTag();
Toast.makeText(getApplicationContext(),
"Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
edata.setSelected(cb.isChecked());
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
Data aux = list.get(position);
long document = aux.getDocument();
holder.doc.setText("Doc:" + Long.toString(document));
holder.name.setText (" " + "Name:" + aux.getName()+ " ");
holder.lname.setText("Last name:" + aux.getLastName());
holder.ck.setTag(aux);
holder.ck.setChecked(aux.isSelected());
return convertView;
}
}
I think problem resides in this block :
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = list.get(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
Try like this :
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = dataAdapter.getItem(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
Note : I am not sure, Please try and let me know the result .:)

how to listen on click of a button in array adapter

I am adding one button per row to show off map in that row in array adapter . I want to get hold of value in that row when that button is clicked . How can I get those values on click of button .
my class:
public class MyListAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<HashMap<String, ArrayList<String>>> pjclist;
private final ArrayList<PermJorneyCycleBean> pjcarraylist ;
String villagename;
int black = Color.WHITE;
float village = 20f;
float depot = 16f;
int red = Color.RED;
int count;
ArrayList<String> Deoptname;
public MyListAdapter(Context context,ArrayList<HashMap<String, ArrayList<String>>>pjcretrivelist, String [] villagename,ArrayList<PermJorneyCycleBean>itempjcarraylist) {
// public MyListAdapter(Context context,ArrayList<PermJorneyCycleBean> pjcretrivelist, String [] villagename) {
super(context, R.layout.scheduleplan,villagename);
this.context = context;
this.pjcarraylist=itempjcarraylist;
this.pjclist=pjcretrivelist;
count =pjcretrivelist.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout rowView1=null;
LinearLayout rowView=null;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (position<count){
rowView1= (LinearLayout) inflater.inflate(R.layout.scheduleplan, null, true);
rowView= (LinearLayout) rowView1.findViewById(R.id.plan);
HashMap<String, ArrayList<String>> depotlistnew = new HashMap<String, ArrayList<String>>();
depotlistnew = pjclist.get(position);
Iterator<Entry<String, ArrayList<String>>> itr = depotlistnew.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry pairs = (Map.Entry) itr.next();
villagename = pairs.getKey().toString();
createNewRow(rowView, villagename, black, village);
Deoptname = (ArrayList) pairs.getValue();
for (int i = 0; i < Deoptname.size(); i++) {
String depotname = new String();
depotname = Deoptname.get(i);
createNewRow(rowView, depotname, red, depot);
}
}
Button mapbutton = createbutton(rowView, "Locate on Map");
mapbutton.setTag(position);
mapbutton.setClickable(true);
mapbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), " This is to depot map"+villagename,Toast.LENGTH_LONG).show();
}
});
}
else if (position==count){
rowView1 = (LinearLayout) inflater.inflate(R.layout.schedulemap, null, true);
Button villagebutton = (Button)rowView1.findViewById(R.id.getBack);
villagebutton.setClickable(true);
villagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "This is for Map"+villagename,Toast.LENGTH_LONG).show();
}
});
}
else if (position==count+1)
{
rowView1 = (LinearLayout) inflater.inflate(R.layout.scheduleplanlast, null, true);
Button backbutton = (Button)rowView1.findViewById(R.id.getBackHome);
backbutton.setClickable(true);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), " This is to test it",Toast.LENGTH_LONG).show();
}
});
}
return rowView1;
}
public void createNewRow(LinearLayout ll1, String value, Integer color,float size) {
TextView tv = new TextView(ll1.getContext());
tv.setTextColor(color);
tv.setTextSize(size);
tv.setText(value);
ll1.addView(tv);
}
public Button createbutton(LinearLayout ll1, String value) {
Button backbutton = new Button(ll1.getContext());
backbutton.setText(value);
backbutton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ll1.addView(backbutton);
return backbutton;
}
public TextView createTextView(LinearLayout ll1, String value){
TextView lattextview = new TextView(ll1.getContext());
lattextview.setVisibility(0);
lattextview.setText(value);
lattextview.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ll1.addView(lattextview);
return lattextview;
}
}
I am not able to get hold of position on click of those buttons .
For your reference i have the following code snippet for button click on Array Adapter
class MySimpleArrayAdapter extends ArrayAdapter<String> {
private Context context;
public MySimpleArrayAdapter(Context context) {
super(context, R.layout.buddy_list);
this.context = context;
}
public int getCount() {
return speedList.size();
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.speeddial_list, null);
}
TextView name = (TextView) rowView.findViewById(R.id.Name);
TextView buddyId = (TextView) rowView.findViewById(R.id.sipid);
Button btn = (Button)rowView.findViewById(R.id.speeddialbtn);
name.setText(speedList.get(position).getName());
buddyId.setText(speedList.get(position).getNumber());
btn.setText(Integer.toString(speedList.get(position).getSPDIndex()));
/*name.setText(names.get(position).toString());
buddyId.setText(buddyIds.get(position).toString());
btn.setText(numberButton.get(position).toString());*/
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (!speedList.get(0).getName().equals(" No SpeedDial Found")) {
registerForContextMenu(getListView());
getListView().showContextMenu();
} else {
unregisterForContextMenu(getListView());
}
selected_name_fromlist = speedList.get(position).getName();
selected_number_fromlist = speedList.get(position).getNumber();
System.out.println(" selected :" + selected_name_fromlist);
}
});
return rowView;
}
}
Here is a good Handling Button clicks in a ListView Row tutorial.

Categories

Resources