从Firebase检索图像以显示在我的Imageview中

时间:2018-08-31 01:15:07

标签: java android firebase firebase-realtime-database android-recyclerview

我希望能通过Firebase数据库的引用显示存储在Firebase Storage中的图像。

以下是我的Firebase数据结构 enter image description here

,我的存储结构是 enter image description here

下面是我的回收适配器代码,我正在从Firebase中检索图像

public class SubjectBooksAdapter extends RecyclerView.Adapter<SubjectBooksAdapter.MyViewHolder> {
    ArrayList<Books> bookslist;
    CardView cv;
    FirebaseAuth fauth;
    FirebaseDatabase database;
    DatabaseReference dbreference;
    Books b;

    public SubjectBooksAdapter(ArrayList<Books> bookslist){
        this.bookslist = bookslist;
    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView bookName,bookAuthor,bookDesc,bookPrice,bookCall;
        ImageView iv;

        MyViewHolder(final View itemView) {
            super(itemView);
            cv = (CardView) itemView.findViewById(R.id.my_card_view);

            iv = (ImageView) itemView.findViewById(R.id.imageView);

            database = FirebaseDatabase.getInstance();
            dbreference = database.getReference("books");
            bookName = (TextView) itemView.findViewById(R.id.bookName);
            bookAuthor = (TextView) itemView.findViewById(R.id.bookAuthor);
            bookDesc = (TextView) itemView.findViewById(R.id.bookDesc);
            bookPrice = (TextView) itemView.findViewById(R.id.bookPrice);
            bookCall = (TextView) itemView.findViewById(R.id.bookCall);
            fauth = FirebaseAuth.getInstance();
        }
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {

        database = FirebaseDatabase.getInstance();
        dbreference = database.getReference("books");

        b = bookslist.get(position);
        holder.bookName.setText(b.getBname());
        holder.bookAuthor.setText(b.getBauthor());
        holder.bookDesc.setText(b.getBdesc());
        holder.bookPrice.setText("Rs. "+b.getPrice());
        holder.bookCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Log.e("Current user is ", fauth.getCurrentUser().getEmail());
                b = bookslist.get(position);
                String[] arr = {b.getSelleremail(),b.getSellername(),b.getBname(),b.getBauthor()};
                //Log.e("Seller is ",b.getSellername());
                Intent in = new Intent(v.getContext(),Chat.class);
                in.putExtra("seller",arr);
                v.getContext().startActivity(in);
            }
        });
        Glide.with(cv.getContext()).load(Uri.parse(b.getPics())).placeholder(R.drawable.bshelf).error(R.drawable.bshelf).into(holder.iv);

    }

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

但是它显示所有其他细节,但是不显示图像...这是屏幕截图 enter image description here

因此它显示了可绘制文件夹中的默认bshel​​f.png。

2 个答案:

答案 0 :(得分:0)

使用您的Firebase存储中的下载网址替换您的图片。保存图像时,您应该从Firebase存储中获取图像的下载URL。

编辑:

在您的onActivityResult()

private byte[] imageByte;

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
        filePath = data.getData();
        iv1.setImageURI(filePath);
    }
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {
            Uri resultUri = result.getUri();

            iv1.setImageURI(resultUri);
            imageByte = uriToByteArray(resultUri);

        } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            Exception error = result.getError();
        }
    }
}

public byte[] uriToByteArray(Uri uri) {
InputStream iStream =   getContentResolver().openInputStream(uri);

     ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];

    int len = 0;
    while ((len = iStream.read(buffer)) != -1) {
        byteBuffer.write(buffer, 0, len);
    }
    return byteBuffer.toByteArray();
}

在类t2中扩展了AsyncTask:

        @Override
    protected Boolean doInBackground(final String... bookid) {
        if(filePath != null) {
            storageRef =  mStorageRef.child(bookid[0]);
        UploadTask uploadTask = storageRef.putBytes(imageByte);

    uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                storageReference.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        String download_url = task1.getResult().toString();
                  }
            });


             }
         });
}

当您要显示图像时:

Books b = list.get(position);
Glide.load(b.getPics);

我没有测试它,但是我认为将图像保存到Firebase时是更好的方法。希望对您有帮助

答案 1 :(得分:0)

尝试一下:

public class ShowImagesActivity extends AppCompatActivity {
//recyclerview object
private RecyclerView recyclerView;

//adapter object
private RecyclerView.Adapter adapter;

//database reference
private DatabaseReference mDatabase;

//progress dialog
private ProgressDialog progressDialog;

//list to hold all the uploaded images
private List<Upload> uploads;

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


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


    progressDialog = new ProgressDialog(this);

    uploads = new ArrayList<>();

    //displaying progress dialog while fetching images
    progressDialog.setMessage("Please wait...");
    progressDialog.show();
    mDatabase = FirebaseDatabase.getInstance().getReference(Constants.DATABASE_PATH_UPLOADS);

    //adding an event listener to fetch values
    mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            //dismissing the progress dialog 
            progressDialog.dismiss();

            //iterating through all the values in database
            for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                Upload upload = postSnapshot.getValue(Upload.class);
                uploads.add(upload);
            }
            //creating adapter
            adapter = new MyAdapter(getApplicationContext(), uploads);

            //adding adapter to recyclerview
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            progressDialog.dismiss();
        }
    });

}
}

请打开此链接,这对您非常有用:

https://www.simplifiedcoding.net/firebase-storage-example/