微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有 Retrofit 和 Picasso 的 Android RecyclerView,图像未在视图空白屏幕显示中加载

如何解决带有 Retrofit 和 Picasso 的 Android RecyclerView,图像未在视图空白屏幕显示中加载

我有一个回收站视图,我正在尝试使用改造从 url 加载数据,并使用毕加索库在回收站视图中加载图像。我不知道一切对我来说都很好,我记录了它在 logcat 中显示的传入数据,但它没有在 UI 视图中膨胀。 URL 链接工作正常,我尝试在没有改造的情况下加载图像以检查它是否正常工作,但它很好。请告诉我可能是什么问题。

APIInterface.java

@Headers("Content-Type: application/json")
@GET("products/category")
Call<ArrayList<CategoryGridModel>> getCategories();

WebReq.java

    private static Retrofit retrofit = null;
    private static ProgressDialog pDialog;
    public static Retrofit getRetrofit() {

        if (retrofit == null) {
            Gson gson = new GsonBuilder()
                    .setLenient()
                    .create();
            HttpLoggingInterceptor httpLoggingInterceptor= new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(GlobalClass.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(okHttpClient)
                    .build();
        }
        return retrofit;
    }

    private WebReq() {
    }
    public static APIInterface getApiInterface(){
        APIInterface apiInterface= getRetrofit().create(APIInterface.class);
        return  apiInterface;
    }
    //concatenation of base url and file name
    public static String getAbsoluteUrl(String relativeUrl) {
        Log.d("response URL: ",GlobalClass.BASE_URL + relativeUrl + " ");
        return GlobalClass.BASE_URL + relativeUrl;
    }

    public static void showDialog() {

        if(pDialog != null && !pDialog.isShowing()) {
            pDialog.setIndeterminate(true);
            pDialog.setMessage("Loading...");
            pDialog.setCanceledOnTouchOutside(false);
            pDialog.show();
        }
    }

    public static void hideDialog() {

        if(pDialog != null && pDialog.isShowing())
            pDialog.dismiss();
    }

CategoryAdapter.java

 public class CategoryAdapter  extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>  {
    
        ArrayList<CategoryGridModel> listData;
        //CategoryGridModel listData;
        Context context;
        int resource;
        protected ItemListener itemListener;
    
        public CategoryAdapter(Context context,ArrayList<CategoryGridModel> listData,ItemListener itemListener) {
    
            //this.listData = listData;
            this.context = context;
            this.itemListener=itemListener;
        }
        public CategoryAdapter(Context context,ArrayList<CategoryGridModel> listData) {
    
            this.listData = listData;
            this.context = context;
    
        }
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {
            View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.categortlist_items,parent,false);
            return new ViewHolder(v);
        }
    
        @Override
        public void onBindViewHolder(ViewHolder viewHolder,int position) {
    
            CategoryGridModel categoryGridModel = listData.get(position);
    
            //viewHolder.icon.setimageResource(listData.get(position).getCat_image_link());
            Picasso.with(context)
                    .load(listData.get(position).getCat_image_link())
                    .placeholder(R.drawable.searchBox)
                    .into(viewHolder.icon,new Callback() {
                        @Override
                        public void onSuccess() {
                            Toast.makeText(context,"Loaded Successfully",Toast.LENGTH_SHORT).show();
                        }
    
                        @Override
                        public void onError() {
                            Toast.makeText(context,"Load Failed",Toast.LENGTH_SHORT).show();
                        }
                    });
            viewHolder.iconName.setText(listData.get(position).getCat_name());
        }
        public class ViewHolder extends RecyclerView.ViewHolder{
            ImageView icon;
            TextView iconName;
            public ViewHolder(View itemView) {
                super(itemView);
                icon = (ImageView) itemView.findViewById(R.id.catimg);
                iconName = (TextView) itemView.findViewById(R.id.catname);
            }
        }
    
        @Override
        public int getItemCount() {
    
            return listData.size();
        }
    
        public interface ItemListener {
            void onItemClick(CategoryGridModel item);
        }
    
    }

CategoryGridModel

public class CategoryGridModel {
        private String id;
        private String cat_name;
        private String cat_img_1;
        private String cat_image_link;
    
    
        public String getCat_img_1() {
            return cat_img_1;
        }
    
        public void setCat_img_1(String cat_img_1) {
            this.cat_img_1 = cat_img_1;
        }
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getCat_name() {
            return cat_name;
        }
    
        public void setCat_name(String cat_name) {
            this.cat_name = cat_name;
        }
    
        public String getCat_image_link() {
            return cat_image_link;
        }
    
        public void setCat_image_link(String cat_image_link) {
            this.cat_image_link = cat_image_link;
        }
    }

HomePage.java

public class HomePage extends AppCompatActivity  implements BaseSliderView.OnSliderClickListener,ViewPagerEx.OnPagechangelistener {
    private RecyclerView categoryRV;
    private AppBarConfiguration mAppBarConfiguration;
    HashMap<String,String> HashMapForURL;
     HashMap<String,Integer> HashMapForLocalRes ;
    //slider
    private SliderLayout sliderLayout ;
    //gridview
    private GridView gridView;
     CategoryAdapter categoryAdapter;
     ArrayList<CategoryGridModel> categoryGridModels;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home,R.id.nav_gallery,R.id.nav_slideshow)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this,R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this,navController,mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView,navController);
        //slider
        sliderLayout = (SliderLayout)findViewById(R.id.pslider);

        //images urls
        //Call this method if you want to add images from URL .
        getSliderImagesUrl();

        //Call this method to add images from local drawable folder .
        //AddImageUrlFormlocalRes();

        //Call this method to stop automatic sliding.
        //sliderLayout.stopAutoCycle();

        for(String name : HashMapForURL.keySet()){
            Log.d("SLiderlist---",name);
            Toast.makeText(this,name,Toast.LENGTH_SHORT).show();
            TextSliderView textSliderView = new TextSliderView(HomePage.this);

            textSliderView
                    .description(name)
                    .image(HashMapForURL.get(name))
                    .setScaleType(BaseSliderView.ScaleType.Fit)
                    .setonSliderClickListener(this);

            textSliderView.bundle(new Bundle());

            textSliderView.getBundle()
                    .putString("extra",name);



            sliderLayout.addSlider(textSliderView);
        }
        sliderLayout.setPresetTransformer(SliderLayout.Transformer.DepthPage);
        sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
        sliderLayout.setCustomAnimation(new DescriptionAnimation());

        sliderLayout.setDuration(10000);
        sliderLayout.addOnPagechangelistener(HomePage.this);
        //loading categories
        getCategoriesFromURL();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home_page,menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this,R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController,mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    public void AddImagesUrlOnline(){

        HashMapForURL = new HashMap<String,String>();

        

    }
    @Override
    public void onSliderClick(BaseSliderView slider) {

        Toast.makeText(this,slider.getBundle().get("extra") + "",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPageScrolled(int position,float positionOffset,int positionOffsetPixels) {}

    @Override
    public void onPageSelected(int position) {

        Log.d("Slider Demo","Page Changed: " + position);

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
    @Override
    protected void onStop() {

        sliderLayout.stopAutoCycle();

        super.onStop();
    }

    /**
     * Load images from url
     */
     public void getSliderImagesUrl(){
         Call<List<SliderModel>> call =WebReq.getApiInterface().getSliderImages();
         HashMapForURL = new HashMap<String,String>();
         //SliderModel sliderModel;
         call.enqueue(new Callback<List<SliderModel>>() {
             @Override
             public void onResponse(Call<List<SliderModel>> call,Response<List<SliderModel>> response) {
                 for(SliderModel sliderModel: response.body()) {
                     Log.d("Slider obj--",sliderModel.getS_name()+" URL : "+sliderModel.getimage_link());
                     HashMapForURL.put(sliderModel.getS_name(),sliderModel.getimage_link());
                 }
             }

             @Override
             public void onFailure(Call<List<SliderModel>> call,Throwable t) {
                 Toast.makeText(getApplicationContext(),"Error while loading slider",Toast.LENGTH_SHORT).show();
             }
         });

         //load images
         
         //HashMapForURL.put(sliderModel.getS_name(),sliderModel.getimage_link());
     }

    /**
     * get categories from url
     */
    public void getCategoriesFromURL(){
        //grid view
        categoryRV=(RecyclerView)findViewById(R.id.catrecycler_view);
        categoryRV.setHasFixedSize(true);
        categoryRV.setLayoutManager(new linearlayoutmanager(this));
        //GridLayoutManager manager = new GridLayoutManager(this,2,GridLayoutManager.VERTICAL,false);
        //categoryRV.setLayoutManager(manager);

        Call<ArrayList<CategoryGridModel>> call =WebReq.getApiInterface().getCategories();

        call.enqueue(new Callback<ArrayList<CategoryGridModel>>() {
            @Override
            public void onResponse(Call<ArrayList<CategoryGridModel>> call,Response<ArrayList<CategoryGridModel>> response) {

                categoryGridModels = response.body();
                categoryAdapter=new CategoryAdapter(HomePage.this,categoryGridModels);
                categoryRV.setAdapter(categoryAdapter);

                for(CategoryGridModel categoryGridModel: response.body()) {
                    Log.d("Slider obj--",categoryGridModel.getCat_name()+" URL: "+categoryGridModel.getCat_image_link());
                }
                categoryAdapter.notifyDataSetChanged();
                //categoryRV.setRefreshing(false);
            }

            @Override
            public void onFailure(Call<ArrayList<CategoryGridModel>> call,Throwable t) {
                Toast.makeText(getApplicationContext(),Toast.LENGTH_SHORT).show();
            }
        });
    }

}

我正在捕捉的回复

[
  {
    "id": "3","cat_name": "Apparel","cat_img_1": "clothes1.png","cat_image_link": "https:\/\/xyz.com\/uploads\/cat_images\/clothes1.png"
  },{
    "id": "2","cat_name": "Fresh vegetables","cat_img_1": "choco.jpg","cat_image_link": "https:\/\/xyz.com\/uploads\/cat_images\/choco.jpg"
  }
]

我有一个导航抽屉,所以我在这里使用。

<?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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/app_bar_main">
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

    <com.daimajia.slider.library.SliderLayout
        android:id="@+id/pslider"
        android:layout_marginTop="0dp"
        android:background="@drawable/searchBox"
        android:layout_width="fill_parent"
        android:layout_height="170dp"/>

        <RelativeLayout
            android:id="@+id/featuredTitle"
            android:layout_below="@id/pslider"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="30dp">
            <TextView
                android:id="@+id/cattitle"
                android:text="Product Category"
                android:layout_alignParentLeft="true"
                android:textSize="18sp"
                android:layout_width="wrap_content"
                android:fontFamily="sans-serif-condensed-medium"
                android:layout_height="30dp"/>
            <!--<TextView
                android:id="@+id/seeAlltext"
                android:text="See All"
                android:layout_alignParentRight="true"
                android:layout_width="wrap_content"
                android:fontFamily="sans-serif-condensed-medium"
                android:layout_height="20dp"/>-->
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_below="@id/cattitle"
                android:layout_height="match_parent">

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/catrecycler_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:scrollbars="vertical"
                    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

            </RelativeLayout>
        </RelativeLayout>


        </RelativeLayout>
    </ScrollView>

</RelativeLayout>

解决方法

终于在这里找到了解决方案:Here

问题是改造似乎在做异步任务,所以我的数据在我对它进行操作的那一刻就到达了,但是有延迟。

,

像这样修改 CategoryAdapter.java:

Picasso.with(context).load(listData.get(position).getCat_image_link()).placeholder(R.drawable.searchbox).into(viewHolder.icon);

您甚至可以使用以下方法分配错误图像:.error(R.drawable.placeholder_error)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。