0

При нажатии на startButton - GridView пустой. Где ошибка?

<EditText
    android:id="@+id/peopleCnt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:width="60dp"
    android:text="1"
    android:gravity="center_horizontal" />

<GridView
    android:id="@+id/countersGrid"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:numColumns="3"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</GridView>

list item

public class cnterItem {
    int num;
    int mils;
    boolean running;

    cnterItem(int num_){
        num=num_;
        mils=0;
        running=false;
    }
}

cnterItem.xml

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/itemContainer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/num"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            />

        <TextView
            android:id="@+id/cnter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:text="00:00:0" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

adapter

public class gridAdapter extends ArrayAdapter<cnterItem>{
    ArrayList<cnterItem> objects;

    public gridAdapter(Context ctx, ArrayList<cnterItem> items){
        super(ctx,0);
        objects=items;
    }

    @Override
    public cnterItem getItem(int position) {
        return objects.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        final cnterItem citem= getItem(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.cnter_item, parent, false);
        }
        LinearLayout l=convertView.findViewById(R.id.itemContainer);
        TextView num=convertView.findViewById(R.id.num);
        TextView cnter= convertView.findViewById((R.id.cnter));

        if(citem != null){
            num.setText(citem.num);
            int mins=(int)Math.floor(citem.mils/600);
            int secs=(int)Math.floor((citem.mils-mins*600)/10);
            int mils=citem.mils-(mins*600+secs*10);

            String m="",s="";
            if(mins<10) m="0"+mins;
            if(secs<10) s="0"+secs;

            cnter.setText(m+":"+s+":"+mils);
        }
        return convertView;
    }
}

startButton.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v){
        int pCnt=Integer.parseInt(peopleCnt.getText().toString());

        for(int i=0;i<pCnt;i++){
            cnterItems.add(new cnterItem(i+1));
        }
        gridAdapter adapter=new gridAdapter(getApplicationContext(),cnterItems);
        countersGrid.setAdapter(adapter);
    }
});

1 ответ 1

0

Если бы вы писали на котлине, фикс выглядил бы следующим образом:

дописать эту строчку после создания адаптера:

countersGrid.adapter = adapter

Но вы пишите на java, а значит нужно найти элемент countersGrid по id, привести его к типу и уже потом установить адаптер. Так или иначе, это путь неверный. Адаптер нужно создавать один раз в onCreate, потом присваивать его к countersGrid в onViewCreated. Сейчас, каждый раз, когда вы кликаете на кнопку, вы создаете новый адаптер (локально), и никак этот объект не используете.

По коду и стилю у вас +100500 замечаний, читайте что такое жизненный цикл, ознакомьтесь с код стайлом. Это очень важно и сразу бросаатся в глаза.

6
  • создал, привел, установил, данные из адаптера читать могу, но к гриду не применяются
    – axmed2004
    15 июл 2020 в 13:02
  • @axmed2004 Обновиите пожалуйста код, и добавьте часть из фрагмента - посмотрю еще раз 15 июл 2020 в 13:12
  • @axmed2004 notifyDatasetChange вызывали у адаптера после обновления данныех? 15 июл 2020 в 13:15
  • я это все уже сделал и не работает. notify зачем при первом присвоении адаптера?
    – axmed2004
    15 июл 2020 в 15:20
  • почему то у меня в вопросе отсутствовала строка countersGrid.setAdapter(adapter); добавил
    – axmed2004
    15 июл 2020 в 15:26

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.