Пользовательский список с текстом редактирования и кнопкой не работает

Я создал свой собственный многоколоночный список с текстом редактирования и кнопкой в ​​каждой строке. Я устанавливаю значение тега для каждой кнопки, чтобы определить, какая строка была нажата. Однако в методе onClick я пытаюсь прочитать значение и преобразовать его в int. Однако значение этого edittext всегда является пустой строкой. Вот код:

 wrapper.mySimpleAdapter = new SimpleAdapter(Chores.this, chores, R.layout.parent_list_format, new String[]{"chore","child_name","points"},new int[]{R.id.value_name,R.id.child_name,R.id.point_value })
                {
                    @Override
                    public View getView (final int position, View convertView, ViewGroup parent)
                    {
                        //Setting the tag for each button of the list to the chore name
                        //to be able to identify which chore is to be claimed
                        final View v = super.getView(position, convertView, parent);
                        Button b=(Button)v.findViewById(R.id.rate);
                        String names = ( v.findViewById(R.id.child_name)).toString();
                        names += ("::") + ( v.findViewById(R.id.value_name)).toString();
                        b.setTag(names);

                        //When one of the list buttons have been clicked
                        b.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {

                                try {
                                    //Sends the chore data to the php file to update the database and reload page
                                    String names = (String) view.getTag();
                                    String child = names.substring(0,names.indexOf(":"));
                                    String chore = names.substring(names.lastIndexOf(":"), names.length()-1);
                                    **EditText points = (EditText) findViewById(R.id.pointsGiven);
                                    int pointsGiven = Integer.parseInt (points.getText().toString());**
                                    Chore chores = new Chore(chore,pointsGiven,accountConnect.user.username,child);


                                    uploadChore(chores);
                                    startActivity(new Intent(v.getContext(), Chores.class));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        return v;
                    }
                };

Звезды указывают на две линии, о которых я говорю. Я предполагаю, что он читает этот текст редактирования при создании каждой строки, и поэтому он всегда возвращает пустую строку. Есть ли способ получить значение edittext при нажатии кнопки?

это XML-файл списка:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/value_name"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:typeface="sans"
    android:textColor="#000000"
    android:layout_weight="1"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"  />

<TextView
    android:id="@+id/child_name"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:typeface="sans"
    android:textColor="#000000"
    android:layout_weight="1"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"  />

<TextView
    android:id="@+id/point_value"
    android:layout_width="30dp"
    android:layout_height="wrap_content"
    android:typeface="sans"
    android:textColor="#000000"
    android:layout_weight="1"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"   />

<EditText
    android:layout_width="60dp"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:hint="points"
    android:ems="10"
    android:id="@+id/pointsGiven"
    />

<Button
    android:id="@+id/rate"
    android:layout_width="60dp"
    android:layout_height="wrap_content"
    android:text = "Rate"
    android:layout_weight="1" />


</LinearLayout>

person jacmurphy50    schedule 22.03.2016    source источник
comment
В каком макете находится идентификатор pointsGiven? В настоящее время вы пытаетесь найти его в действии, а не в макете строки списка.   -  person OneCricketeer    schedule 22.03.2016
comment
pointsGiven находится в xml-файле макета строки списка.   -  person jacmurphy50    schedule 22.03.2016
comment
Тогда вам нужно использовать v.findViewById вместо этого   -  person OneCricketeer    schedule 22.03.2016
comment
Кроме того, что вы пытаетесь сделать в ( v.findViewById(R.id.child_name)).toString();? Это не то, как вы получаете текст из Textview   -  person OneCricketeer    schedule 22.03.2016


Ответы (3)


Предполагая, что ваш EditText points находится внутри вашей строки, вам нужно найти его в своем представлении строки:

@Override
public void onClick(View view) {
    //your code
    EditText points = (EditText) view.findViewById(R.id.pointsGiven);
    //your code
}
person yennsarah    schedule 22.03.2016
comment
Когда я сделал это, я получил эту ошибку: java.lang.NullPointerException: попытка вызвать виртуальный метод «android.text.Editable android.widget.EditText.getText()» для нулевой ссылки на объект - person jacmurphy50; 22.03.2016
comment
Это означает, что в вашем файле макета нет EditText с данным id. Может быть, отредактировать исходный пост и показать макет строки? - person yennsarah; 22.03.2016
comment
@Amy - view - это кнопка, у которой действительно нет дочерних представлений (--> NPE). Вам нужно v, как сказал cricket_007: EditText points = (EditText) v.findViewById(R.id.pointsGiven); - person Bö macht Blau; 22.03.2016

 @Override
public View getView (final int position, View convertView, ViewGroup parent)
{
    //Setting the tag for each button of the list to the chore name
    //to be able to identify which chore is to be claimed
    final View v = super.getView(position, convertView, parent);
    Button b=(Button)v.findViewById(R.id.rate);
    String names = ( v.findViewById(R.id.child_name)).toString();
    names += ("::") + ( v.findViewById(R.id.value_name)).toString();
    b.setTag(names);
    EditText points = (EditText) v.findViewById(R.id.pointsGiven);
    //When one of the list buttons have been clicked
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            try {
                //Sends the chore data to the php file to update the database and reload page
                String names = (String) view.getTag();
                String child = names.substring(0,names.indexOf(":"));
                String chore = names.substring(names.lastIndexOf(":"), names.length()-1);

                int pointsGiven = Integer.parseInt (points.getText().toString());**
                Chore chores = new Chore(chore,pointsGiven,accountConnect.user.username,child);


                uploadChore(chores);
                startActivity(new Intent(v.getContext(), Chores.class));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    return v;
}

Инициализируйте EditText перед onClick в адаптере и попытайтесь получить такое же значение.

person Silvans Solanki    schedule 22.03.2016

Вы должны перейти к щелчку по позиции нажатого элемента, а затем получить элемент:

                  //When one of the list buttons have been clicked

                    b.setTag(position);
                    b.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View view) {
                        Item item = getItem((int)view.getTag());
                    }
person Master Fathi    schedule 22.03.2016