TextView в RecyclerView во фрагменте, не отображает тексты из Java или из XML-файлов - PullRequest
0 голосов
/ 04 июня 2018

Отредактировал мой вопрос Заголовок Я пытаюсь передать данные JSON в RecyclerView, который встроен во фрагмент, и я фактически сделал это ПРЕЖДЕ ЧЕМ я украсил list_items.xml RecyclerView.

Теперь я пытаюсьотображать некоторые обычные тексты в этом представлении Recycler, и AS всегда дает мне исключение NullPointerException в строке MyViewHolder ... после того, как я прокомментировал строку, приложение запускается, но RecyclerView не отображает никаких текстов, даже тексты в list_items RecyclerView.xml

Вот результат, который у меня есть до сих пор, recyclerView отображает ТОЛЬКО ImageView.И textView не работает.

enter image description here

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder> {
private Context context; private List<ForumsListItem> forumsListItems;
ForumsFragment fragment=new ForumsFragment();
//Define the constructor for both contenxt and listItem
public MyRecyclerAdapter(Context context, List<ForumsListItem> items) {
    this.context = context;
    forumsListItems =items;

}

@NonNull
@Override
public MyRecyclerAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v= LayoutInflater.from(parent.getContext())
            .inflate(R.layout.forums_listitems,parent,false);

    return new MyViewHolder(v);
}

/*Bind everything from te MyViewHolder*/
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    //Define listItem position
    ForumsListItem listItem=forumsListItems.get(position);

    //Calling the textView inside bindingViewHolder
    //holder.catListName.setText(listItem.getCatlistName());
    holder.numOfDailyNewPosts.setText(listItem.getNumOftodayPosts());
    holder.descriptTv.setText(listItem.getDescription());
}

@Override
public int getItemCount() {
    return forumsListItems.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder implements  View.OnClickListener{
    private TextView nameTv,descriptTv,numOfDailyNewPosts,catListName;

    private ImageView imgIcons;
    public MyViewHolder(View itemView) {
        super(itemView);
        //things to display in form of List

        descriptTv=(TextView)itemView.findViewById(R.id.item_detail);
        catListName=(TextView)itemView.findViewById(R.id.catListTxt);
        numOfDailyNewPosts=(TextView)itemView.findViewById(R.id.numOfDailyNewPosts);
        //can add Picaso loding images here
        itemView.setOnClickListener(this);
    }
    @Override
    public void onClick(View v){
        int pos=getAdapterPosition();
        //get the current position

        ForumsListItem items= forumsListItems.get(pos);

        Toast.makeText(context,items.getForumsTitles(),Toast.LENGTH_LONG).show();
        //On click functionality

    }
}

}

Мой list_items.xml

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

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/cardview_compat_inset_shadow"
    android:layout_marginTop="5dp"
    android:layout_marginEnd="5dp"
    android:layout_marginStart="5dp"
    android:padding="16dp" >
    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/color_light_yellow">
            <android.support.constraint.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <ImageView
                    android:id="@+id/forumsTitleImg"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    app:layout_constraintHorizontal_chainStyle="packed"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    android:src="@android:drawable/checkbox_on_background"/>
                <TextView
                    android:id="@+id/numOfDailyNewPosts"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="fdlksfjsdlkjf"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintStart_toEndOf="@id/forumsTitleImg"
                    android:layout_margin="10dp" />
            </android.support.constraint.ConstraintLayout>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/item_detail"
            android:layout_margin="10dp"
            app:layout_constraintTop_toBottomOf="@+id/frame"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>

06-03 23: 07: 30,752 2964-2964 /?I / art: Позднее включение -Xcheck: jni 06-03 23: 07: 30.930 2964-2964 / com.yamibo.bbs.splashscreen W / art: Ошибка execv (/ system / bin / dex2oat --runtime-arg -classpath--runtime-arg --debuggable --instruction-set = arm --instruction-set-features = smp, div, atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image = / system / framework / boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m - набор инструкций-вариант = krait - набор-инструкций-возможностей = по умолчанию --dex-файл = / data / app / com.yamibo.bbs.splashscreen-2 / split_lib_dependencies_apk.apk --oat-file = / data / dalvik-cache / arm / data @ app @ com.yamibo.bbs.splashscreen-2 @ split_lib_dependencies_apk.apk @ classes.dex), так как состояние выхода не равно 0 06-03 23: 07: 31.416 2964-2964 / com.yamibo.bbs.splashscreen W / art: Ошибка execv (/ system / bin / dex2oat --runtime-arg -classpath --runtime-arg --debuggable --instruction-set= arm --instruction-set-features = smp, div, atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image = / system / framework / boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m--instrucion-set-option = krait --instruction-set-features = по умолчанию --dex-file = / data / app / com.yamibo.bbs.splashscreen-2 / split_lib_slice_0_apk.apk --oat-file = / data / dalvik-cache / arm / data @ app @ com.yamibo.bbs.splashscreen-2 @ split_lib_slice_0_apk.apk @ classes.dex), так как состояние выхода не равно 0 06-03 23: 07: 31.493 2964-2964 / com.yamibo.bbs.splashscreen W / art: Ошибка execv (/ system / bin / dex2oat --runtime-arg -classpath --runtime-arg --debuggable --instruction-set = arm --instruction-set-features = smp, div, atomic_ldrd_strd--runtime-arg -Xrelocate --boot-image = / system / framework / boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-option = krait --instruction-set-features = по умолчанию --dex-file = / data / app / com.yamibo.bbs.splashscreen-2 / split_lib_slice_1_apk.apk --oat-file = / data / dalvik-cache / arm / data @ app @ com.yamibo.bbs.splashscreen-2 @ split_lib_slice_1_apk.apk @ classes.dex), так как статус выхода не равен 0 06-03 23: 07: 31.594 2964-2964 / com.yamibo.bbs.splashscreen W / art: Ошибка выполнения (/ system / bin/ dex2oat --runtime-arg -classpath --runtime-arg --debuggable --instruction-set = arm --instruction-set-features = smp, div, atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image = / system / framework / boot.art--runtime-arg -Xms64m --runtime-arg -Xmx512m --инструкция-набор-вариант = krait --инструкция-набор-функции = по умолчанию --dex-файл = / data / app / com.yamibo.bbs.splashscreen-2 / split_lib_slice_2_apk.apk --oat-file = / data / dalvik-cache / arm / data @ app @ com.yamibo.bbs.splashscreen-2 @ split_lib_slice_2_apk.apk @ classes.dex), так как статус выхода не равен 0 06-03 23: 07: 31.666 2964-2964 / com.yamibo.bbs.splashscreen W / art: Ошибка execv (/ system / bin / dex2oat --runtime-arg -classpath --runtime-arg --debuggable --instruction-set = arm --instruction-set-features = smp, div, atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image = / system / framework / boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variable = krait --instruction-set-features = default --dex-file = / data / app / com.yamibo.bbs.splashscreen-2 / split_lib_slice_3_apk.apk --oat-file = /данные / декалитровvik-cache / arm / data @ app @ com.yamibo.bbs.splashscreen-2 @ split_lib_slice_3_apk.apk @ classes.dex), поскольку состояние выхода не равно 006-03 23: 07: 31.738 2964-2964 / com.yamibo.bbs.splashscreen W / art: Ошибка execv (/ system / bin / dex2oat --runtime-arg -classpath --runtime-arg --debuggable --instruction-set = arm --instruction-set-features = smp, div, atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image = / system / framework / boot.art --runtime-arg -Xms64m --runtime-arg-Xmx512m - набор-инструкций-вариантов = krait - -инструмент-набор инструкций = по умолчанию - -dex-файл = / data / app / com.yamibo.bbs.splashscreen-2 / split_lib_slice_4_apk.apk --oat-file =/data/dalvik-cache/arm/data@app@com.yamibo.bbs.splashscreen-2@split_lib_slice_4_apk.apk@classes.dex), так как статус выхода не 0 06-03 23: 07: 31.913 2964-2964 / com.yamibo.bbs.splashscreen W / art: Сбой execv (/ system / bin / dex2oat --runtime-arg -classpath --runtime-arg --debuggable --instruction-set = arm --instruction-set-features = smp, div, atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image = / system / framework / boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m - инструкция-набор-вариант = крэйт -набор инструкций-феatures = по умолчанию --dex-file = / data / app / com.yamibo.bbs.splashscreen-2 / split_lib_slice_5_apk.apk --oat-file = / data / dalvik-cache / arm / data @ app @ com.yamibo.bbs.splashscreen-2 @ split_lib_slice_5_apk.apk @ classes.dex), так как статус выхода не равен 0 06-03 23: 07: 31.957 2964-2964 / com.yamibo.bbs.splashscreen W / art: Ошибка выполнения (/ system / bin/ dex2oat --runtime-arg -classpath --runtime-arg - отладка --instruction-set = arm --instruction-set-features = smp, div, atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image =/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-option = krait --instruction-set-features = по умолчанию --dex-file = / data / app/com.yamibo.bbs.splashscreen-2/split_lib_slice_6_apk.apk --oat-file = / data / dalvik-cache / arm / data @ app @ com.yamibo.bbs.splashscreen-2 @ split_lib_slice_6_apk.apk @ classes.dex) потому что состояние выхода не равно 0 06-03 23: 07: 32.037 2964-2964 / com.yamibo.bbs.splashscreen W / art: Ошибка execv (/ system / bin / dex2oat --runtime-arg -classpath --runtime-arg --debuggable --instruction-set = arm --instruction-set-features = smp, div, atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image = / system / framework / boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-option = krait --instruction-set-features = по умолчанию --dex-file = / data / app / com.yamibo.bbs.splashscreen-2 / split_lib_slice_7_apk.apk --oat-file= / data / dalvik-cache / arm / data @ app @ com.yamibo.bbs.splashscreen-2 @ split_lib_slice_7_apk.apk @ classes.dex), поскольку состояние выхода не равно 0 06-03 23: 07: 32.203 2964-2964 /com.yamibo.bbs.splashscreen W / art: Ошибка execv (/ system / bin / dex2oat --runtime-arg -classpath --runtime-arg --debuggable --instruction-set = arm --instruction-set-features =smp, div, atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image = / system / framework / boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m - инструкция-набор-вариант = крэйт --instruction-set-features = по умолчанию --dex-file = / data / app / com.yamibo.bbs.splashscreen-2 / split_lib_slice_8_apk.apk --oat-file = / data / dalvik-cache / arm / data @ app@ com.yamibo.bbs.splashscreen-2 @ split_lib_slice_8_apk.apk @ classes.dex), потому что состояние выхода не равно 0 06-03 23: 07: 32.324 2964-2964 / com.yamibo.bbs.splashscreen W / art: Ошибка execv (/ system / bin / dex2oat--runtime-arg -classpath --runtime-arg --debuggable --instruction-set = arm --instruction-set-features = smp, div, atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image = / system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-option = krait --instruction-set-features = default --dex-file = / data / app / com.yamibo.bbs.splashscreen-2 / split_lib_slice_9_apk.apk --oat-file = / data / dalvik-cache / arm / data @ app @ com.yamibo.bbs.splashscreen-2 @ split_lib_slice_9_apk.apk @ classes.dex), так каксостояние выхода не 0 06-03 23: 07: 32.326 2964-2964 / com.yamibo.bbs.splashscreen W / System: ClassLoader ссылается на неизвестный путь: /data/app/com.yamibo.bbs.splashscreen-2/lib/arm 06-03 23: 07: 32.331 2964-2964 / com.yamibo.bbs.splashscreen I / InstantRun: запуск сервера мгновенного запуска: это основной процесс06-03 23: 07: 32.571 2964-2964 / com.yamibo.bbs.splashscreen W / art: до Android 4.1, метод android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter (android.graphics.PorDuffC), android.content.res.ColorStateList, android.graphics.PorterDuff $ Mode) неправильно переопределил бы метод приватного пакета в android.graphics.drawable.Drawable 06-03 23: 07: 32.603 2964-3043 / com.yamibo.bbs.splashscreen D / OpenGLRenderer: Использовать EGL_SWAP_BEHAVIOR_PRESERVED: true 06-03 23: 07: 32.662 2964-3043 / com.yamibo.bbs.splashscreen I / Adreno-EGL:: EGL 1.4, сборка QUALCOMM: Nondem.I741a3d36ca) OpenGL ES Shader Compiler Версия: E031.29.00.00 Дата сборки: 04.04.16 Пн Локальная ветвь: mybranch19053788 Удаленная ветвь: quic / LA.BF.1.1.3_rb1.12 Локальные исправления: НЕТ Реконструировать ветвь: НИЧТО 06-03 23: 07: 32.677 2964-3043 / com.yamibo.bbs.splashscreen I / OpenGLRenderer: Инициализированный EGL, версия 1.4 06-03 23: 07: 32.863 2964-2964 / com.yamibo.bbs.splashscreen I / Временная шкала: Временная шкала: Идентификатор Activity_idle: android.os.BinderProxy@1c32706 time: 11829580 06-03 23: 07: 36.591 2964-2964 / com.yamibo.bbs.splashscreenI / Временная шкала: Хронология: Activity_launch_request id: com.yamibo.bbs.splashscreen время: 11833307 06-03 23: 07: 37.435 2964-2964 / com.yamibo.bbs.splashscreen D / TEST2: 10 06-03 23:07:37.460 2964-3123 / com.yamibo.bbs.splashscreen W / System: ClassLoader ссылается на неизвестный путь: /system/framework/tcmclient.jar 06-03 23: 07: 37.692 2964-2964 / com.yamibo.bbs.splashscreen E /RecyclerView: адаптер не подключен;пропускающий макет 06-03 23: 07: 37.773 2964-2964 / com.yamibo.bbs.splashscreen I / Хореограф: пропущено 40 кадров!Приложение может выполнять слишком много работы в своем основном потоке.06-03 23: 07: 37.980 2964-2964 / com.yamibo.bbs.splashscreen W / art: до Android 4.1 метод int android.support.v7.widget.DropDownListView.lookForSelectablePosition (int, boolean) некорректно перекрывалзакрытый для пакета метод в android.widget.ListView 06-03 23: 07: 38.084 2964-2964 / com.yamibo.bbs.splashscreen E / RecyclerView: адаптер не подключен;пропускающий макет 06-03 23: 07: 38.112 2964-2964 / com.yamibo.bbs.splashscreen I / Временная шкала: Временная шкала: Идентификатор Activity_idle: android.os.BinderProxy@b5d7e1c время: 11834828 06-03 23: 07: 38.672 2964-3123 / com.yamibo.bbs.splashscreen W / System.err: org.json.JSONException: индекс 2 вне диапазона [0..2) в org.json.JSONArray.get (JSONArray.java:293) в орг.json.JSONArray.getJSONObject (JSONArray.java:521) на com.yamibo.bbs.splashscreen.ForumsFragment $ ForumsJSONParser.doInBackground (ForumsFragment.java:150) на com.yamibo.bbs.splashscreen.ForumsFragmentInBB.JBJava: 126) на android.os.AsyncTask $ 2.call (AsyncTask.java:295) на java.util.concurrent.FutureTask.run (FutureTask.java:237) на android.os.AsyncTask $ SerialExecutor $ 1.run (Asynckas.java: 234) в java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1113) в java.util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor.java:588) в java.lang.thThread.java:818)

1 Ответ

0 голосов
/ 04 июня 2018

@ Kira:

Пожалуйста, замените файл list_items.xml следующим кодом и проверьте еще раз:

<RelativeLayout 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">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="5dp"
    android:layout_marginStart="5dp"
    android:layout_marginTop="5dp"
    android:padding="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/frame"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/forumsTitleImg"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    android:src="@android:drawable/checkbox_on_background" />

                <TextView
                    android:id="@+id/numOfDailyNewPosts"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="10dp"
                    android:text="fdlksfjsdlkjf" />
            </LinearLayout>
        </FrameLayout>

        <TextView
            android:id="@+id/item_detail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp" />
    </LinearLayout>
</android.support.v7.widget.CardView></RelativeLayout>

и вот файл Java со статическими данными:

    public class SampleActivity extends Activity{
    RecyclerView sampleRecycle;
    MyRecyclerAdapter myRecyclerAdapter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_activity);

        sampleRecycle = (RecyclerView) findViewById(R.id.sampleRecycle);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        sampleRecycle.setLayoutManager(mLayoutManager);
        myRecyclerAdapter = new MyRecyclerAdapter(this);
        sampleRecycle.setAdapter(myRecyclerAdapter);
    }


    public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder> {
        private Context context;
//        private List<ForumsListItem> forumsListItems;
//        ForumsFragment fragment = new ForumsFragment();

        //Define the constructor for both contenxt and listItem
        public MyRecyclerAdapter(Context context) {
            this.context = context;
//            forumsListItems = items;

        }

        @NonNull
        @Override
        public MyRecyclerAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_items, parent, false);

            return new MyViewHolder(v);
        }

        /*Bind everything from te MyViewHolder*/
        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            //Define listItem position
//            ForumsListItem listItem = forumsListItems.get(position);

            //Calling the textView inside bindingViewHolder
            //holder.catListName.setText(listItem.getCatlistName());
//            holder.numOfDailyNewPosts.setText(listItem.getNumOftodayPosts());
//            holder.descriptTv.setText(listItem.getDescription());
        }

        @Override
        public int getItemCount() {
            return 20;
        }

        public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            private TextView nameTv, descriptTv, numOfDailyNewPosts, catListName;

            private ImageView imgIcons;

            public MyViewHolder(View itemView) {
                super(itemView);
                //things to display in form of List

                descriptTv = (TextView) itemView.findViewById(R.id.item_detail);
//                catListName = (TextView) itemView.findViewById(R.id.catListTxt);
                numOfDailyNewPosts = (TextView) itemView.findViewById(R.id.numOfDailyNewPosts);
                //can add Picaso loding images here
                itemView.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                int pos = getAdapterPosition();
                //get the current position

//                ForumsListItem items = forumsListItems.get(pos);

//                Toast.makeText(context, items.getForumsTitles(), Toast.LENGTH_LONG).show();
                //On click functionality

            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...