Danilo Silva
Danilo Silva

Reputation: 612

Get the EditText values from ListView

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

Upvotes: 3

Views: 19730

Answers (4)

Gayashan Perera
Gayashan Perera

Reputation: 21

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"

Upvotes: 0

MalhotraUrmil
MalhotraUrmil

Reputation: 86

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

Upvotes: 1

Antrromet
Antrromet

Reputation: 15414

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);
}

Upvotes: 16

Talha
Talha

Reputation: 12717

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

https://i.sstatic.net/DqKv3.png

Upvotes: 0

Related Questions