从Firebase存储中检索图像

时间:2019-05-22 20:54:10

标签: firebase google-cloud-firestore firebase-storage

我已经将一些照片上传到了Firebase存储中,我需要将这些图像中的每个图像与Cloud Firestore中的文档相关联,然后在recyclerView中显示它们。我是否要获取每个图像的网址,并向Firestore中的每个文档中添加一个字段“图像”,并将该网址用作值?然后如何将它们放入RecyclerView中?

我已经使用FirestoreUI从Firestore成功检索了其他数据,但是我不确定如何对图像执行相同的操作。

RecyclerViewAdapter类

public class FirebaseRecyclerViewAdapter extends 
FirestoreRecyclerAdapter<Buildings, 
FirebaseRecyclerViewAdapter.FirebaseRecyclerViewHolder> {

public FirebaseRecyclerViewAdapter(FirestoreRecyclerOptions<Buildings> 
options) {
    super(options);
}

@Override
protected void onBindViewHolder(FirebaseRecyclerViewHolder holder, int 
position, Buildings model) {
    holder.textViewName.setText(model.getName());
}

@NonNull
@Override
public FirebaseRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup 
parent, int viewType) {
    View v = 
 LayoutInflater.from(parent.getContext()).inflate
(R.layout.buildings_row_item, parent, false);
    return new FirebaseRecyclerViewHolder(v);
}

class FirebaseRecyclerViewHolder extends RecyclerView.ViewHolder {
    TextView textViewName;

    public FirebaseRecyclerViewHolder(View itemView) {
        super(itemView);
        textViewName = itemView.findViewById(R.id.building_name);


    }
}
}

MainActivity类

public class MainActivity extends AppCompatActivity {


private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference buildingRef = db.collection("Building");
StorageReference storageReference = 
FirebaseStorage.getInstance().getReference();
private FirebaseRecyclerViewAdapter adapter;

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

    setUpRecyclerView();


    getSupportActionBar().hide();
}

private void setUpRecyclerView() {

    Query query = buildingRef.orderBy("name", Query.Direction.DESCENDING);

    FirestoreRecyclerOptions<Buildings> options = new 
FirestoreRecyclerOptions.Builder<Buildings>()
            .setQuery(query, Buildings.class)
            .build();
    adapter = new FirebaseRecyclerViewAdapter(options);

    RecyclerView recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);

}

@Override
protected void onStart() {
    super.onStart();
    adapter.startListening();

}

@Override
protected void onStop() {
    super.onStop();
    adapter.stopListening();
}

}

1 个答案:

答案 0 :(得分:1)

首先,您需要使用

将所需的图像上传到Firestore存储
StorageReference

然后您必须使用

保存网址
getDownloadUrl()

下一步是将URL保存到文档的字段中,这里是一个示例

  

上传图片

 private void uploadFile() {

    if (mImageUri != null) {
        StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
                + "." + getFileExtension(mImageUri));

        mUploadTask = fileReference.putFile(mImageUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                          @Override
                                          public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                              Toast.makeText(context, "Upload successful", Toast.LENGTH_LONG).show();
                                                fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                                    @Override
                                                    public void onSuccess(Uri uri) {
                                                        image=new Images(mID+"",Objects.requireNonNull( uri.toString()));
                                                    }
                                                })
                                                .addOnFailureListener(new OnFailureListener() {
                                                    @Override
                                                    public void onFailure(@NonNull Exception e) {
                                                        Toast.makeText(context, "Upload Failed", Toast.LENGTH_LONG).show();
                                                    }
                                                });

                                          }
                                      }
                )

                .addOnFailureListener(e ->
                        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show())

        .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(context, "Uploading...", Toast.LENGTH_LONG).show();
            }
        });

    } else {
        Toast.makeText(context, "No file selected", Toast.LENGTH_SHORT).show();

    }


}
  

将URL保存到Firestore文档

  if(!TextUtils.isEmpty(image.getmImageUrl()))
         mProperty  = new Property(mID, username,mCity ,mDesc,mPrice,noRooms,noBathrooms,address,date,area,parking,Objects.requireNonNull(image.getmImageUrl()));
    else
         mProperty = new Property(mID, username,mCity ,mDesc,mPrice,noRooms,noBathrooms,address,date,area,parking);
        db.collection("Property").document(mProperty.getmID() + "").set(mProperty)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(context, "done",
                                Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {

                        Toast.makeText(context, "Failed",
                                Toast.LENGTH_SHORT).show();
                    }
                });


        boolean flag;

    } else {
        mError.setText("Empty Fields");
        mError.setVisibility(View.VISIBLE);
    }

我正在使用模型将数据插入Firestore中,您也应该这样做

  

,并且在RecyclerAdapter中,您可以使用Picasso或Bitmap将图像绑定到Recyclerview

Picasso.get().load(model.getmImageDrawable()).
            fit().placeholder(R.drawable.placeholder_image).
            error(R.drawable.no_img).into(holder.mImage)