I am using ArrayAdapter When I delete the first item from Listview.Its delete perfectly.But When I do delete the second item from the listview. Its not perfectly delete.
how can i do it?
Adapter coding
import android.widget.ArrayAdapter;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// final CartBean beans = getItem(position);
View view = convertView;
final ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_cart_row, parent, false);
viewHolder = new ViewHolder();
viewHolder.row_price = (TextView) view.findViewById(R.id.row_price);
viewHolder.et_quantity = (EditText) view.findViewById(R.id.cart_quantity);
viewHolder.row_item_name = (TextView) view.findViewById(R.id.row_item_name);
viewHolder.deleteButton = (ImageView) view.findViewById(R.id.iv_delete);
// viewHolder.rastaurantoffer = (ImageView) view.findViewById(R.id.rastaurantname2);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (viewHolder.textWatcher != null)
viewHolder.et_quantity.removeTextChangedListener(viewHolder.textWatcher);
final CartBean bean = getItem(position);
viewHolder.textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.length()>0) {
viewHolder.row_price.setText(String.valueOf(df.format(Double.parseDouble(bean.getTotal_price()) * Integer.parseInt(charSequence.toString()))));
AppConstants.cartBeanArrayList.get(position).setQuantity(Integer.parseInt(charSequence.toString()));
}
}
#Override
public void afterTextChanged(Editable editable) {
Double totalPrice=0.0;
for (int i=0;i<AppConstants.cartBeanArrayList.size();i++)
{
totalPrice=totalPrice+(Double.parseDouble(AppConstants.cartBeanArrayList.get(i).getTotal_price()) * AppConstants.cartBeanArrayList.get(i).getQuantity());
Log.i("total_price12356",""+total_price);
}
ActivityCart.tv_sub_total.setText("£. "+String.valueOf(df.format(totalPrice)));
}
};
viewHolder.row_price.setText("£."+String.valueOf(df.format(Double.parseDouble(cartBeans.get(position).getTotal_price()) * cartBeans.get(position).getQuantity())));
viewHolder.et_quantity.setText(String.valueOf(cartBeans.get(position).getQuantity()));
viewHolder.row_item_name.setText(cartBeans.get(position).getItem_name());
viewHolder.et_quantity.addTextChangedListener(viewHolder.textWatcher);
if(isDeleteRequired){
viewHolder.deleteButton.setVisibility(View.VISIBLE);
viewHolder.et_quantity.setInputType(InputType.TYPE_CLASS_NUMBER);
viewHolder.et_quantity.setFocusableInTouchMode(true);
viewHolder.et_quantity.setCursorVisible(true);
viewHolder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppConstants.cartBeanArrayList.remove(position);
notifyDataSetChanged();
for (int i = 0; i < AppConstants.cartBeanArrayList.size(); i++) {
// String price = AppConstants.cartBeanArrayList.get(i).getTotal_price().substring(3, AppConstants.cartBeanArrayList.get(i).getTotal_price().length());
// Log.i("total_price123",""+price);
total_price = total_price + ActivityCart.getTotal(i);
Log.i("total_price123",""+total_price);
Log.i("total_price1237",""+AppConstants.cartBeanArrayList.size());
// AppConstants.cartBeanArrayList.clear();
}
Log.i("total_price1234",""+total_price);
ActivityCart.tv_sub_total.setText("£. "+String.valueOf(total_price));
if (AppConstants.cartBeanArrayList.size()==0)
{
ActivityCart.tv_sub_total.setText("£.0.00");
}
// AppConstants.addressBeanArrayList.setText(String.valueOf(total_price));
}
});
}else{
viewHolder.deleteButton.setVisibility(View.GONE);
}
return view;
}
class ViewHolder {
TextView row_item_name;
TextView row_price;
EditText et_quantity;
ImageView deleteButton;
public TextWatcher textWatcher;
}
public void setIsDeleteRequired(boolean isDeleteRequire){
isDeleteRequired = isDeleteRequire;
}
}
And getTotal() method coding is:
public static Double getTotal(int i) {
total =(Double.parseDouble(AppConstants.cartBeanArrayList.get(i).getTotal_price()) * AppConstants.cartBeanArrayList.get(i).getQuantity());
Log.i("totalsunder", "" +total);
return total;
}
Yes I got the answer myself.
Here my code
viewHolder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppConstants.cartBeanArrayList.remove(position);
for (int i = 0; i < AppConstants.cartBeanArrayList.size(); i++) {
total_price = total_price + ActivityCart.getTotal(i);
}
ActivityCart.tv_sub_total.setText("£. "+String.valueOf(total_price));
total_price =0.0;
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//removing from database
int i =impl_cart.deleteRow(data_cart.get(position).get_id());
//removing from adapter
data_cart.remove(position);
notifyDataSetChanged();
}
});
Related
hello to every one i have a custom list view with a search and animation all works cool but in search i have a little problem . I would like to, for example, I search for a word in a sentence.
But the way I used to enter the letters i have to put them in sequence.
here is my code:
public class MainActivity extends Activity {
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] country;
Typeface tf;
ArrayList<WorldPopulation> arraylist = new ArrayList<WorldPopulation>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
editsearch = (EditText) findViewById(R.id.search);
list = (ListView) findViewById(R.id.listview);
tf = Typeface.createFromAsset(getAssets(), "fonts/BKOODB.TTF");
country = new String[54];
for (int x = 1; x < 54 + 1; x = x + 1) {
String this_subject = "mo_" + String.valueOf(x);
int resID = getResources().getIdentifier(this_subject, "string", getPackageName());
country[x - 1] = getResources().getString(resID);
}
for (int i = 0; i < 54; i++) {
WorldPopulation wp = new WorldPopulation(country[i]);
// Binds all strings into an array
arraylist.add(wp);
}
adapter = new ListViewAdapter(this, arraylist);
list.setAdapter(adapter);
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
});
list.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
hideKeyboard();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
new CountDownTimer(500, 500) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
hideKeyboard();
}
}.start();
}
public class WorldPopulation {
private String country;
public WorldPopulation(String country) {
this.country = country;
}
public String getCountry() {
return this.country;
}
}
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<WorldPopulation> worldpopulationlist = null;
private ArrayList<WorldPopulation> arraylist;
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_in_right);
public ListViewAdapter(Context context, List<WorldPopulation> worldpopulationlist) {
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<WorldPopulation>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView country;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public WorldPopulation getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listview_item, parent, false);
TextView textview = (TextView) row.findViewById(R.id.country);
ImageView im = (ImageView) row.findViewById(R.id.imageitem);
im.setImageResource(R.drawable.hair);
textview.setText(worldpopulationlist.get(position).getCountry());
textview.setTypeface(tf);
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_in_right);
row.startAnimation(animation);
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// *********************************************************
// in here it does not send right number to secend activity*
// *********************************************************
int orgPos = 0;
if (country.length != worldpopulationlist.size()) {
notifyDataSetChanged();
// The list on which we clicked is sorted!
String clickedText = worldpopulationlist.get(position).toString();
int i1 = 0;
boolean found = false;
while (i1 < country.length && found == false) {
if (clickedText == country[i1]) {
orgPos = i1;
found = true;
} else {
i1++;
}
}
Intent i2 = new Intent(mContext, SingleItemView.class);
String Subject_number = String.valueOf(orgPos + 1);
i2.putExtra("subject_number", Subject_number);
startActivity(i2);
} else {
Intent i = new Intent(mContext, SingleItemView.class);
String Subject_number = String.valueOf(position + 1);
i.putExtra("subject_number", Subject_number);
startActivity(i);
}
}
});
return row;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (final WorldPopulation wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault()).contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
private void hideKeyboard() {
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
try doing it in afterTextChanged Method because this allows you to enter all the text. and follow this link
public void afterTextChanged(Editable s) {
}
Try with custom adapter.
this will help you.Link
Here is my adapter code where on edit field edited am calculating the 2 other fields and displaying through TextWatcher. There are 2 issues here.
1. On scroll the values are changing to default values
2. How can I take the new values updated on click of a button
Please help...thanks.
public class ItemListAdapter extends BaseAdapter {
private ArrayList<Itemlist> mProductList,medicineList;
private LayoutInflater mInflater;
String newEditValu[];
Itemlist curProduct;
Itemlist list;
DataTranrfer df;
public ItemListAdapter(ArrayList<Itemlist> list, LayoutInflater inflater) {
mProductList = list;
mInflater = inflater;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewItem item;
final int pos=position;
medicineList=new ArrayList<Itemlist>();
if (convertView == null) {
convertView = mInflater.inflate(R.layout.activity_medicine_list,null);
item = new ViewItem();
item.medicineTitle = (TextView) convertView.findViewById(R.id.tvMedicineName);
item.medcineQuantity =(EditText)convertView.findViewById(R.id.etQuantity);
item.itemDaily=(TextView)convertView.findViewById(R.id.tvDailyText);
item.itemNdays=(TextView)convertView.findViewById(R.id.tvNodays);
item.itemTotal = (TextView)convertView.findViewById(R.id.tvCost);
convertView.setTag(item);
ImageButton b2 = (ImageButton) convertView.findViewById(R.id.thumbnail);
b2.setTag(position);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
int pos = (int)arg0.getTag();
mProductList.remove(pos);
ItemListAdapter.this.notifyDataSetChanged();
}
});
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
curProduct = mProductList.get(position);
item.ref=position;
item.medicineTitle.setText(curProduct.getmedicineName());
item.itemDaily.setText("Daily: " + curProduct.getMedicineDaily());
item.itemNdays.setText("Days: " + curProduct.medicineNoDays);
item.itemTotal.setText("Rs." + curProduct.getMedicineTotal());
item.medcineQuantity.setText("" + curProduct.getMedicineQuantity());
ItemListAdapter.this.notifyDataSetChanged();
item.medcineQuantity.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//ItemListAdapter.this.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
System.out.print("edit response" + s.toString());
Itemlist curProduct = mProductList.get(position);
if (item.medcineQuantity.getText().length() >= 0) {
double dItemcost = Double.parseDouble(curProduct.getMedicineCost());
double dItemDaily = Double.parseDouble(curProduct.getMedicineDaily());
double dItemQuantity = Double.parseDouble(item.medcineQuantity.getText().toString());
//double dItemQuantity = Double.parseDouble(myList.get(pos));
double dItemDays = (dItemQuantity / dItemDaily);
double dItemTotal = (dItemQuantity * dItemcost);
item.medcineQuantity.setText("" +myList.get(pos));
item.itemNdays.setText("Days: " + dItemDays);
item.itemTotal.setText("Rs." + dItemTotal);
list=new Itemlist();
list.setmedicineName(curProduct.getmedicineName());
list.setMedicineDaily(curProduct.getMedicineDaily());
list.setMedicineQuantity(dItemQuantity);
list.setMedicineCost("" + dItemcost);
list.setMedicineTotal(dItemTotal);
medicineList.add(list);
for(int i=0;i<medicineList.size();i++)
{
System.out.println("medicine list"+medicineList.toString());
System.out.println("medicine total at"+i+":"+medicineList.get(i).getMedicineTotal());
}
}
}
});
return convertView;
}
private class ViewItem {
TextView medicineTitle,itemDaily,itemNdays,itemTotal;
EditText medcineQuantity;
int ref;
}
}
"Don't use edittext inside a listview" this is what most of the people say.. now I am thinking should have listened to them. I had a problem earlier when I added an EditText inside a ListView and encountered a problem related to click and I also posted a question regarding this(EditText and ListView are not working together) and also found a solution for that in(Focus on EditText in ListView when block descendants (Android)). After having so many obstacles I have been able to implement this,
But now I am having a recycle issue problem, I have an addTextChangedListener for the EditText in the ListView. Most of the people are suggesting to use setOnFocusChangeListener, but that is not an option for me as i have to change the EditText value of one row depending the value entered in the EditText of the other row.
The problem currently I am facing is when I enter the value in the last row of the EditText, the same thing is reflecting in the first row. Can anybody help me to solve this issue.
Here is the code snippet (Sorry for bad english)
public class MyBaseAdapter extends BaseAdapter {
ArrayList < ListData > myList = new ArrayList < > ();
LayoutInflater inflater;
Activity activity;
ListView lvDetail;
TextView total_amount;
TextView spendAmount;
Button proceed;
HashMap < Integer, ListData > selectedRow = new HashMap < > ();
public MyBaseAdapter(Activity activity, ArrayList < ListData > myList, ListView lvDetail) {
this.myList = myList;
this.activity = activity;
this.lvDetail = lvDetail;
inflater = LayoutInflater.from(this.activity);
total_amount = (TextView) activity.findViewById(R.id.total_amount);
spendAmount = (TextView) activity.findViewById(R.id.spendAmount);
proceed = (Button) activity.findViewById(R.id.proceed);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Object getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public void setItem(int position, ListData data) {
myList.set(position, data);
}#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final MyViewHolder mViewHolder;
final ListData currentListData = (ListData) getItem(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_list_item, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
mViewHolder.enterAmount.setText("");
mViewHolder.enterAmount.setVisibility(View.INVISIBLE);
mViewHolder.tvDesc.setText("");
mViewHolder.tvTitle.setText("");
mViewHolder.ivIcon.setImageResource(R.drawable.ic_launcher_1);
}
if (selectedRow.containsKey(position)) {
mViewHolder.enterAmount.setVisibility(View.VISIBLE);
mViewHolder.enterAmount.setText(currentListData.getEditTextValue());
mViewHolder.ivIcon.setImageResource(R.drawable.ic_check_orange);
} else if (currentListData.getEditTextValue().toString().length() == 0) {
mViewHolder.enterAmount.setVisibility(View.INVISIBLE);
mViewHolder.enterAmount.setText(currentListData.getEditTextValue());
mViewHolder.ivIcon.setImageResource(currentListData.getImgResId());
}
mViewHolder.tvTitle.setText(currentListData.getTitle());
mViewHolder.tvDesc.setText(currentListData.getDescription());
mViewHolder.enterAmount.addTextChangedListener(new TextWatcher() {
String enterAmount, enterDescption;#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
enterAmount = s.toString();
enterDescption = mViewHolder.tvDesc.getText().toString().trim();
if ((count == 1 && start == 0) && (before == 1)) {
mViewHolder.enterAmount.setText("");
currentListData.setEditTextValue("");
setItem(position, currentListData);
}
}
#Override
public void afterTextChanged(Editable s) {
String[] separated;
int totalBal = 0;
if ((enterAmount.length() != 0 && enterDescption.length() != 0)) {
separated = enterDescption.split(":");
totalBal = Integer.parseInt(separated[1]);
if ((Integer.parseInt(enterAmount) > totalBal)) {
mViewHolder.enterAmount.setText("");
currentListData.setEditTextValue("");
setItem(position, currentListData);
new AlertDialog.Builder(activity)
.setTitle("Alert")
.setMessage("You do not have sufficient balance")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.setCancelable(false)
.show();
} else if (Integer.parseInt(enterAmount) >= 0) {
System.out.println(position + "positioninside else if enterAmount:" + Integer.parseInt(enterAmount));
currentListData.setEditTextValue(enterAmount);
setItem(position, currentListData);
}
}
}
});
convertView.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View view) {
int i = selectedRow.size();
if (selectedRow.containsKey(position)) {
selectedRow.remove(position);
mViewHolder.enterAmount.setVisibility(View.INVISIBLE);
mViewHolder.enterAmount.setText("");
mViewHolder.ivIcon.setImageResource(R.drawable.ic_launcher1);
} else if (i < 2) {
ListData currentListData = (ListData) getItem(position);
selectedRow.put(position, currentListData);
mViewHolder.enterAmount.setVisibility(View.VISIBLE);
mViewHolder.ivIcon.setImageResource(R.drawable.ic_check_orange);
} else if (i >= 2) {
Toast.makeText(activity, "Select only two cards", Toast.LENGTH_SHORT).show();
}
}
}
);
return convertView;
}
private static class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
EditText enterAmount;
public MyViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
tvDesc = (TextView) item.findViewById(R.id.tvDesc);
ivIcon = (ImageView) item.findViewById(R.id.ivIcon);
enterAmount = (EditText) item.findViewById(R.id.edittext);
}
}
}
I am have a small problem in my custom dialog.
When the user search for an item in the listview, the list shows the right items, but if the user for example wants to search again, the listview shows the results from the previous search.
The problem:
How do I restore the listview after the first search?
My activity with the custom dialog
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
}
});
}
}
private void showDialog() {
dialog = new Dialog(this);
View view = getLayoutInflater().inflate(R.layout.material_list, null);
searchList = (ListView) view.findViewById(R.id.searchList);
dialog.setTitle("Välj ny artikel");
final MaterialAdapter adapter = new MaterialAdapter(
InformationActivity.this, materialList);
dialog.setContentView(view);
searchList.setAdapter(adapter);
searchList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Materials itemMat = materialList.get(position);
resultProduct = itemMat.materialName;
resultProductNo = itemMat.materialNo;
result = resultProduct + " " + resultProductNo;
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_SHORT).show();
}
});
search = (EditText) dialog.findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
cancel = (Button) dialog.findViewById(R.id.btnCancel);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
ok = (Button) dialog.findViewById(R.id.btnOK);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
product.setText(resultProduct);
productNo.setText(resultProductNo);
dialog.dismiss();
}
});
dialog.show();
}
}
My adapter
public class MaterialAdapter extends BaseAdapter {
LayoutInflater inflater;
Context context;
List<Materials> searchItemList = null;
ArrayList<Materials> materialList = new ArrayList<Materials>();
public MaterialAdapter(Context context, List<Materials> searchItemList) {
this.context = context;
inflater = LayoutInflater.from(context);
this.searchItemList = searchItemList;
this.materialList = new ArrayList<Materials>();
this.materialList.addAll(searchItemList);
}
#Override
public int getCount() {
return searchItemList.size();
}
#Override
public Object getItem(int position) {
return searchItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.d, null);
viewHolder = new ViewHolder();
viewHolder.tvMaterialName = (TextView) convertView
.findViewById(R.id.tvMaterialName);
viewHolder.tvMaterialNo = (TextView) convertView
.findViewById(R.id.tvMaterialNo);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tvMaterialName.setText((searchItemList.get(position))
.getMaterialName());
viewHolder.tvMaterialNo.setText((searchItemList.get(position))
.getMaterialNo());
return convertView;
}
public class ViewHolder {
TextView tvMaterialName;
TextView tvMaterialNo;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
searchItemList.clear();
if (charText.length() == 0) {
searchItemList.addAll(materialList);
} else {
for (Materials wp : materialList) {
if (wp.getMaterialName().toLowerCase(Locale.getDefault())
.startsWith(charText)) {
searchItemList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Thanks for the help :)
Try to change search.getText() to s.toString()
public void onTextChanged(CharSequence s, int start, int before,
int count) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
to
public void onTextChanged(CharSequence s, int start, int before, int count) {
resultText = s.toString().toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
A secondary thing, make materialList = searchItemList; And searchItemList empty which will be filled with search items (first run will be same elements of materialList.)
P.S Your adapter should implement Filterable in this case (implements Filterable)
#Override
public void afterTextChanged(Editable s) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
Try this and check whether it helps
I'm trying to get the values from the EditTexts in a ListView, but its not working. The values set to my array of 'lista' in the afterTextChanged method are apparently lost. I'm new in android programming, someone can help me? (sorry for bad English)
Heres the code for the getView in my adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final int posicao = position;
if (convertView == null) {
LayoutInflater inflater = contexto.getLayoutInflater();
convertView = inflater.inflate(R.layout.produtos, null);
holder = new ViewHolder();
holder.texto = (TextView) convertView.findViewById(R.id.txtDescricao);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.chkProduto);
holder.edit = (EditText) convertView.findViewById(R.id.txtValor);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.texto.setText(getItem(position).getTexto());
holder.edit.setText("0");
holder.edit.setTag(new LinhaItemTag(getItem(position), position));
//here a get an exception just setting the focus on edit
holder.edit.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
int posicao = v.getId();
EditText e = ((EditText) v);
if (!e.getText().toString().equals("")) {
if (hasFocus) {
if(e.getText().toString().length() != 0)
lista.get(posicao).setValor(Double.parseDouble(e.getText().toString()));
}
}
}
});
holder.edit.addTextChangedListener( new TextWatcher() {
public void afterTextChanged(Editable s)
{
if(s.length() != 0)
{
lista.get(posicao).setValor(Double.parseDouble(s.toString()));
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
});
holder.checkbox.setOnCheckedChangeListener(null);
holder.checkbox.setChecked(getItem(position).Selecionado());
holder.checkbox.setTag(new LinhaItemTag(getItem(position), position));
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
LinhaItemTag elemento = (LinhaItemTag) buttonView.getTag();
elemento.item.setSelecionado(isChecked);
if (isChecked) {
pegos[elemento.position] = true;
} else {
pegos[elemento.position] = false;
}
boolean checados = true;
for (int i = 0; i < lista.size(); i++) {
if (!pegos[i]) {
checados = false;
break;
}
}
if (checados) {
for(int i = 0; i < lista.size(); i++)
{
total += lista.get(i).getValor();
}
Toast.makeText(contexto, "Compra finalizada - Valor Total: " + total, Toast.LENGTH_LONG).show();
}
}
});
return convertView;
}
}
I managed to get values from the EditTexts looking at this post: how to retrieve value from all EditText in ListView
Bu now, i faced with other problem: when i roll my list down, the values from the EditTexts are lost.
This is like my code looks now:
public class MeuAdapter extends ArrayAdapter<LinhaItem> {
private final List<LinhaItem> lista;
private final Activity contexto;
private final boolean[] pegos;
private final double[] valores;
double total;
public MeuAdapter(Activity contexto, List<LinhaItem> lista) {
super(contexto, 0, lista);
this.contexto = contexto;
this.lista = lista;
pegos = new boolean[lista.size()];
valores = new double[lista.size()];
for (int i = 0; i < lista.size(); i++) {
pegos[i] = false;
valores[i] = 0;
}
total = 0;
}
public class ViewHolder
{
protected TextView texto;
protected CheckBox checkbox;
protected EditText edit;
}
public class LinhaItemTag {
LinhaItem item;
int position;
LinhaItemTag(LinhaItem item, int position) {
this.item = item;
this.position = position;
}
}
private class MeuTextWatcher implements TextWatcher {
private View v;
public MeuTextWatcher(View v)
{
this.v = v;
}
#Override
public void afterTextChanged(Editable e) {
String s = e.toString();
LinhaItemTag lTag = (LinhaItemTag) v.getTag();
if(s.length() != 0)
{
valores[lTag.position] = Double.parseDouble(s);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = contexto.getLayoutInflater();
convertView = inflater.inflate(R.layout.produtos, null);
holder = new ViewHolder();
holder.texto = (TextView) convertView.findViewById(R.id.txtDescricao);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.chkProduto);
holder.edit = (EditText) convertView.findViewById(R.id.txtValor);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.texto.setText(getItem(position).getTexto());
holder.edit.setText("");
holder.edit.setTag(new LinhaItemTag(getItem(position), position));
holder.edit.addTextChangedListener(new MeuTextWatcher(holder.edit));
holder.checkbox.setOnCheckedChangeListener(null);
holder.checkbox.setChecked(getItem(position).Selecionado());
holder.checkbox.setTag(new LinhaItemTag(getItem(position), position));
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
LinhaItemTag elemento = (LinhaItemTag) buttonView.getTag();
elemento.item.setSelecionado(isChecked);
if (isChecked) {
pegos[elemento.position] = true;
} else {
pegos[elemento.position] = false;
}
boolean checados = true;
for (int i = 0; i < lista.size(); i++) {
if (!pegos[i]) {
checados = false;
break;
}
}
String vlrs = "";
if (checados) {
for(int i = 0; i < lista.size(); i++)
{
total += valores[i];
}
Toast.makeText(contexto, "Total da compra: " + total, Toast.LENGTH_LONG).show();
}
}
});
return convertView;
}
}
I change the line:
holder.edit.setText("");
to:
//the valores array is where i store the values in the afterTextChanged method in the TextWatcher class implementation.
holder.edit.setText(**Double.toString(valores[position])**);
But this not working as i expect, for example, if i set a value to the EditText of the first row of the ListView, this value, after i roll down the list, is setted to EditText in the third row of the list...
To get the values from the EditText in your ListView, you could do that in your activity. You must need the values on some view click or something. So whenever that happens, just write the following code
View view=listView.getChildAt(position);
EditText editText=view.findViewById(R.id.editText);
String string=editText.getText().toString();
Here, the above code will give you the text of the EditText that is present in the position position of your ListView. It seems that you need the sum of the of the values of the EditTexts when all are checked right? You can use something like this then
for(int i=0;i<items.size();i++){
View view=listView.getChildAt(i);
EditText editText=view.findViewById(R.id.editText);
String string=editText.getText().toString();
if(!string.equals(""))
total+=Double.parseDouble(string);
}
change in adapter class getView() methods look like.
#Override
public View getView(final int position, View view, ViewGroup parent) {
TextView txt_id, txt_courny_symbol, txt_member_view;
EditText edit_member_amount;
final int posicao = position;
Log.v("ConvertView", String.valueOf(posicao));
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_member_layout, null);
txt_id = (TextView) view.findViewById(R.id.txt_id);
txt_courny_symbol = (TextView) view.findViewById(R.id.txt_courny_symbol);
edit_member_amount = (EditText) view.findViewById(R.id.edit_member_amount);
edit_member_amount.setTag(new LinhaItemTag(getItem(posicao), posicao));
edit_member_amount.addTextChangedListener(new MeuTextWatcher(edit_member_amount));
if (al_contact.size() != 0) {
MemberClass memberClass = al_contact.get(position);
txt_id.setText(memberClass.getName());
txt_courny_symbol.setText(sym);
}
return view;
}
erase the our ViewHolder class
hi you can use the code below to do this, listview cannot save the controllers state on the row, so you need to use settag and gettag of controls.
for source: https://dl.dropbox.com/u/68130108/ListViewEditItem.rar
Losing the values from EditTexts can be annoying as far. I have found this solution while working.
In your android manifest, pick the activity which your list view is in. Then put this code-block there.
android:windowSoftInputMode="adjustPan"
Then go to your ListView, and navigate to the xml layout and put this block there.
android:descendantFocusability="beforeDescendants"