Просмотр переработчика с помощью обхода

#android #android-recyclerview

#Android #android-recyclerview

Вопрос:

Я хочу создать recyclerview с использованием обхода. Сейчас есть некоторые проблемы, но я не знаю причины. когда я нажимаю кнопку, чтобы отобразить список обхода, движения нет. программа просто останавливается. Я хочу знать, в каких частях есть проблема.

  1. Хорошо ли реализован recyclerview?
  2. Есть ли проблема с частью обхода?

главная acticity.xml

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#faf0e6"
    tools:context=".recommend">

    <TextView
        android:id="@ id/textView12"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="121dp"
        android:layout_marginLeft="121dp"
        android:layout_marginTop="25dp"
        android:text="cosmetic"
        android:textColor="#550000"
        android:textSize="30sp"
        android:textStyle="bold"
        tools:layout_editor_absoluteX="153dp"
        tools:layout_editor_absoluteY="187dp" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@ id/recyclerview_main_list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintVertical_weight="9"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:scrollbarFadeDuration="0"
        android:scrollbarSize="5dp"
        android:scrollbarThumbVertical="@android:color/darker_gray"
        android:scrollbars="vertical"/>


</RelativeLayout>
  

основная активность

 package com.example.beauticreate;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Dictionary;


public class recommend extends AppCompatActivity {

    private ArrayList<ItemObject> mArrayList;
    private CustomAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recommend);



        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_main_list);
        LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);


        mArrayList = new ArrayList<>();

        mAdapter = new CustomAdapter( mArrayList);
        mRecyclerView.setAdapter(mAdapter);


        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mRecyclerView.getContext(),
                mLinearLayoutManager.getOrientation());
        mRecyclerView.addItemDecoration(dividerItemDecoration);

        new Description().execute();
    }

    @SuppressLint("StaticFieldLeak")
    private class Description extends AsyncTask<Void, Void, Void> {
        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = new ProgressDialog(recommend.this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setMessage("please wait.");
            progressDialog.show();
        }


        @Override
        protected Void doInBackground(Void... params) {
            try {
                Document doc = Jsoup.connect("https://www.sephora.com/search?keyword=1y01").get();
                Elements mElementDataSize = doc.select("div[class=css-dkxsdo]").select("div");
                int mElementDatasize = mElementDataSize.size();
 
                for (Element elem : mElementDataSize) {
                    String name = elem.select("div[class=1gughuu]").text();
                    String price = elem.select("span[class=css-0]").text();
                    String review = elem.select("div[class=css-t33ub8").text();
                    String img = elem.select("img[class=1rovmyu eanm77i0").attr("src");

                    mArrayList.add(new ItemObject(name, price, img, review));
                }

                Log.d("debug :", "List"   mElementDataSize);
      
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }


    }

}
  

Адаптер

 package com.example.beauticreate;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Dictionary;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;


public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {

    private ArrayList<ItemObject> mList;

    public class CustomViewHolder extends RecyclerView.ViewHolder {
        protected ImageView imageView15;
        protected TextView textView13, textView14, textView15;


        public CustomViewHolder(View view) {
            super(view);
            this.imageView15 = (ImageView) view.findViewById(R.id.imageView15);
            this.textView13 = (TextView) view.findViewById(R.id.textView13);
            this.textView14 = (TextView) view.findViewById(R.id.textView14);
            this.textView15 = (TextView) view.findViewById(R.id.textView15);
        }
    }

    public CustomAdapter(ArrayList<ItemObject> list) {
        this.mList = list;
    }


    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.item_list, viewGroup, false);

        return new CustomViewHolder(view);
    }




    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder viewholder, int position) {


        viewholder.textView13.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
        viewholder.textView14.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
        viewholder.textView15.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);

        viewholder.textView13.setGravity(Gravity.CENTER);
        viewholder.textView14.setGravity(Gravity.CENTER);
        viewholder.textView15.setGravity(Gravity.CENTER);

        viewholder.textView13.setText(mList.get(position).getName());
        viewholder.textView14.setText(mList.get(position).getPrice());
        viewholder.textView15.setText(mList.get(position).getReview());

        GlideApp.with(viewholder.itemView).load(mList.get(position).getImg())
                .override(300,400)
                .into(viewholder.imageView15);
    }

    @Override
    public int getItemCount() {
        return (null != mList ? mList.size() : 0);
    }

}
  

Ответ №1:

Проблема заключается в вашей асинхронной задаче. Несколько шагов:

 private ArrayList<ItemObject> mArrayList;
  

Этот массив заполняется AsyncTask, но никогда не используется. Это также может привести к сбоям в памяти, если к нему будут обращаться разные потоки, например doInBackground . Это поле можно удалить.

 mArrayList = new ArrayList<>();
mAdapter = new CustomAdapter( mArrayList);
  

Этот массив также никогда не используется, его также можно удалить. Замените его на:

 mAdapter = new CustomAdapter(null);
  

Теперь решение! Ваша AsyncTask должна вернуть свой результат. doInBackground возвращает массив и onPostExecute выполняется в основном потоке и может добавить его в адаптер.

 private class Description extends AsyncTask<Void, Void, List<ItemObject>> {
@Override
protected List<ItemObject> doInBackground(Void... params) {
    ArrayList<ItemObject> mArrayList = new ArrayList<ItemObject>();
    ...
    return mArrayList;
}

protected void onPostExecute(List<ItemObject> result) {
     mAdapter.mList = resu<
     mAdapter.notifyDataSetChanged();
}
  

В качестве последнего шага сделайте mList общедоступным. Дайте мне знать, если это сработает!