java - 从 Firebase 存储到 Recycler View 的图像

标签 java android firebase firebase-storage

我正在尝试根据文档 ID 将图像从 Firebase 存储放入回收器 View 。当我明确地将 uri 传递给 shop 对象时,就会显示该图片。 但它没有从 Firebase 存储中获取图像。不知道为什么它不起作用。所有其他事情都工作正常。

这是我的 数据模型

package com.ufdstudios.ezyq;

import android.net.Uri;

public class Shops {

    private String ShopId;
    private String Name;
    private String Status;
    private Uri uri;

    public Shops(){}

    public Shops(String Name,String Status,Uri uri)
    {
        this.Name = Name;
        this.Status = Status;
        this.uri = uri;
    }


    public String getshopName() {
        return Name;
    }

    public String getShopStatus() {
        return Status;
    }

    public void setshopName(String Name) {
        this.Name = Name;
    }

    public void setShopStatus(String Status) {
        this.Status = Status;
    }

    public Uri getUri() {
        return uri;
    }

    public void setUri(Uri uri) {
        this.uri = uri;
    }

    public String getShopId() {
        return ShopId;
    }

    public void setShopId(String shopId) {
        ShopId = shopId;
    }
}

自定义适配器

package com.ufdstudios.ezyq;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.List;

public class ShopsListAdapter extends RecyclerView.Adapter<ShopsListAdapter.ViewHolder> {

    public List<Shops> shopsList;


    public ShopsListAdapter(List<Shops> shopsList)
    {
        this.shopsList = shopsList;
    }

    // sepcifying lauout style of list
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.shop_list_layout, parent, false);

        return new ViewHolder(view);

    }



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

    public class ViewHolder extends RecyclerView.ViewHolder
    {
        View mView;
        // views here
        public TextView tv_shop_id;
        public TextView tv_shop_name;
        public TextView tv_shop_status;
        public ImageView iv_shop_logo;

        public ViewHolder(View itemView) {
            super(itemView);
            mView =itemView;

            // linking views here
            tv_shop_id = mView.findViewById(R.id.tv_shop_id);
            tv_shop_status = mView.findViewById(R.id.tv_shop_status);
            tv_shop_name = mView.findViewById(R.id.tv_shop_name);
            iv_shop_logo = mView.findViewById(R.id.iv_shop_logo);

        }
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // setting values here
        holder.tv_shop_status.setText(shopsList.get(position).getShopStatus());
        holder.tv_shop_id.setText(shopsList.get(position).getShopId());
        holder.tv_shop_name.setText(shopsList.get(position).getshopName());
        // using picaso library to populate image from uri
        Picasso.get().load(shopsList.get(position).getUri()).into(holder.iv_shop_logo);


    }

}

fragment

//creating List View
         shopList =  new ArrayList<>();
// adaper
         shopsListAdapter = new ShopsListAdapter(shopList);
// setting up recycler view
        recycler_view = (RecyclerView)view.findViewById(R.id.recycler_view);
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recycler_view.setAdapter(shopsListAdapter);

        dbRef.collection("shop").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if(task.isSuccessful())
                {
                    QuerySnapshot querySnapshot = task.getResult();
                   List<DocumentSnapshot> docs = querySnapshot.getDocuments();
                    for (DocumentSnapshot document : docs) {

                        final Shops shops = new Shops();
                        shops.setshopName(document.get("Name").toString());
                        shops.setShopStatus(document.get("Status").toString());
                        shops.setShopId(document.getId());

                        String shop_id = document.getId();
                        storageRef = storage.getReference().child("/shops_logo/" + shop_id +".png"); // get reference of shop_id named logo
                        storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                // puttindg logo from Firebase Storage to Image View
                               shops.setUri(uri);
                            }
                        });

                        // adding to list
                        shopList.add(shops);
                        // change event listener for in databaess
                        shopsListAdapter.notifyDataSetChanged();
                    }

                }
            }
        });

这样也累了。但问题仍然没有解决:

 dbRef.collection("shop").addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(final QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
            if(e!=null)
            {
                // eror hangle here
            }
            for(DocumentChange doc: documentSnapshots.getDocumentChanges())
            {
                if(doc.getType() == DocumentChange.Type.ADDED) {
                    // getting data in Objects
                   // Shops shops = doc.getDocument().toObject(Shops.class);
                    final Shops shops = new Shops();
                    shops.setshopName(doc.getDocument().get("Name").toString());
                    shops.setShopStatus(doc.getDocument().get("Status").toString());

                    String shop_id = doc.getDocument().getId(); // geting shop id
                    shops.setShopId(shop_id);
                    //getting logo from databae
                    // using that shop id to let shops logo

                  //  shops.setUri(Uri.parse("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRYXVTbxmHQuOogxDeNx7U6z7neHX4kOQPZEBLG5nzQZoMMhkFN"));
                    storageRef = storage.getReference().child("/shops_logo/" + shop_id +".png"); // get reference of shop_id named logo

                    storageRef.getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
                                                                      @Override
                                                                      public void onSuccess(StorageMetadata storageMetadata) {
                                                                          shops.setUri(storageMetadata.getDownloadUrl());
                                                                      }
                                                                  });


                            // adding to list
                            shopList.add(shops);
                    // change event listener for in databaess
                    shopsListAdapter.notifyDataSetChanged();

                }
            }
        }
    });

数据库快照: Database

Storeage

有什么解决办法吗?谢谢

最佳答案

原因是您正在进行额外的异步调用来获取图像 uri,但 Shop 对象在图像 uri 加载完成之前已添加到列表中。

如下所示替换 for 循环

for (DocumentSnapshot document : docs) {

    final Shops shops = new Shops();
    shops.setshopName(document.get("Name").toString());
    shops.setShopStatus(document.get("Status").toString());
    shops.setShopId(document.getId());

    String shop_id = document.getId();
    storageRef = storage.getReference().child("/shops_logo/" + shop_id +".png"); // get reference of shop_id named logo
    storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            // puttindg logo from Firebase Storage to Image View
           shops.setUri(uri);// adding to list
           shopList.add(shops);
           // change event listener for in databaess
           shopsListAdapter.notifyDataSetChanged();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
           shopList.add(shops);
           // change event listener for in databaess
           shopsListAdapter.notifyDataSetChanged();
        }
    });
}

关于java - 从 Firebase 存储到 Recycler View 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51920090/

相关文章:

java - 尝试找到数组中的最小值并将其返回到 main

java - Xml 到 Json 到 xml 可逆转换 json-lib

Android R8 找不到方法

firebase - 弹出窗口出现然后立即关闭

java - Datasnapshot 未从 Firebase 返回正确的数据

java - 为什么匿名内部类不包含此代码生成的任何内容?

java - 在 Spring 中用另一个 Controller 重置 Controller

java - 数组数组(二维数组)没有像我想要的那样在 TextView 中打印。

android - 任务 ':app:compileDebugNdk' 执行失败

ios - Firebase 存储无法通过 Cocoapods 安装