首页 > 解决方案 > 将 Firebase 图像作为可绘制对象检索并显示在回收站视图中

问题描述

我已经实现了 RecyclerView 可以成功显示图像并且现在在我的 Fragment 中一切正常我想从 Firebase 加载图像(图像已经存储在实时数据库中及其 url)这是我的片段代码

public RecyclerView youthRecycler;
public RecyclerView.Adapter recyclerAdapter;
public RecyclerView.LayoutManager recyclerManager;


//i just want to populate this array with drawables from images stored on firebase
int[] imagesArray={R.drawable.youthtable1,R.drawable.youthtable2,R.drawable.youthtable3};

public tableYouthFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_table_youth, container, false);
}

@Override
public void onStart() {
    super.onStart();
    //all code goes here
    init();
}
public void init()
{
    youthRecycler=getActivity().findViewById(R.id.youthRecycler);
    youthRecycler.setHasFixedSize(true);
    recyclerManager=new LinearLayoutManager(getContext());
    youthRecycler.setLayoutManager(recyclerManager);
    recyclerAdapter =new MyRecyclerAdpater(getActivity(),imagesArray);
    youthRecycler.setAdapter(recyclerAdapter);
}

这个问题已经在这里问过,但没有任何经过验证的答案,并且在 kotlin 和 java 答案中的经过验证的答案要求我更改我的 RecyclerView 整个实施。我也跟进了许多关于 glide 库的教程,但不知道是否可以将图像加载为可绘制对象,或者我必须更改我的整个适配器实现

标签: javaandroidfirebase

解决方案


你的 recyclerView 应该获取一个 url 列表,你可以在 Glide 中加载它们,为什么你需要将它们加载为 drawable 而 glide 可以将它们加载为 url:

在 onBindViewHolder() 中:

Glide.with(context).load(url).into(holder.imageYouWantToShow);

现在在片段中获取网址:

 DatabaseRefernce imagesRef = FirebaseDatabase.getInstance().getReference();
 ValueEventListener imagesListner = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot imageUrl: dataSnapshot.getChildren()) {
           String image = imageUrl.getValue(String.class);
           imagesArray.add(image);
      }
  
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
    Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

    }
};
imagesRef.addValueEventListener(imagesListner );

recyclerManager=new LinearLayoutManager(getContext());
youthRecycler.setLayoutManager(recyclerManager);
recyclerAdapter = new MyRecyclerAdpater(this,imagesArray);
youthRecycler.setAdapter(recyclerAdapter);

推荐阅读