Search code examples
androidfirebaseandroid-recyclerviewgoogle-cloud-firestoredata-retrieval

Retrieve images in recyclerview from Firebase Firestore


I am trying to retrieve images from Firebase Firestore. I am able to retrieve text in RecyclerView successfully however I'm not sure how to retrieve the images.

I had a look at similar questions unfortunately none helped.

ListActivity :

    //initialize firestore
    db = FirebaseFirestore.getInstance();

    //initialize views
    mRecyclerView = findViewById(R.id.resultRecycle);
    //set recycler view properties
    mRecyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(layoutManager);

    //show  data in recycler view
    showData();
}

private void showData() {

    db.collection("Item")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {

                    //called when data is retrieved
                    //show data
            for(DocumentSnapshot doc: task.getResult()){

                        Model model = new 
                    Model(doc.getString("id"),
                                doc.getString("Title"),
                                doc.getString("Location"),
                                //STUCK HERE
                        );


                        modelList.add(model);
                    }

                    //adapter
                    adapter = new CustomAdapter(ListActivity.this, modelList);
                    //set adapter to recycler view
                    mRecyclerView.setAdapter(adapter);

                }
            });

CustomAdapter :

public void onItemClick(View view, int position) {
            //this will be called when user clicks an item

            //show data on toast when clicking
            String title = modelList.get(position).getTitle();
            String location = modelList.get(position).getLocation();
            String  url = modelList.get(position).getUrl();
        }

        @Override
        public void onItemLongClick(View view, int position) {
            //this will be called when user clicks long item
        }
    });

    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int i) {
    //bind views /set data
    holder.mTitle.setText(modelList.get(i).getTitle());
    holder.mLocation.setText(modelList.get(i).getLocation());
    Picasso.get().load(modelList.get(i).getUrl()).into(holder.mUrl);

}

Please see the image below link, thank you enter image description here


Solution

  • Use fileuploader code to upload the image in Firebase Database.

    But make sure you put the Fileuploader run on the click of any button. Or it will throw nullpointer Exception if your edittext are empty.

    private void Fileuploader(){ 
        if(imguri != null ) { 
            StorageReference ref = mStorageRef.child("Item"); 
            Toast.makeText(UploadActivity.this, "Upload in progress", Toast.LENGTH_LONG).show(); 
            ref.putFile(imguri) 
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { 
                    @Override 
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { 
                            Toast.makeText(UploadActivity.this, "Image uploaded successfully!", Toast.LENGTH_LONG).show(); 
                            Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
                            while (!urlTask.isSuccessful());
                            Uri downloadUrl = urlTask.getResult();
                            saveData(downloadUrl); 
                        } 
                    }) 
                .addOnFailureListener(new OnFailureListener() { 
                    @Override 
                        public void onFailure(@NonNull Exception exception) { 
                            Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show(); 
                        } 
                }); 
        } 
    }
    

    The function will automatically start when file upload successfully done.

    private void saveData(Uri imguri) { 
        Map<String, String> data = new HashMap<>(); 
        EditText title = findViewById(R.id.etv_1); 
        EditText shortDesc = findViewById(R.id.etv_2); 
        TextView location = findViewById(R.id.etv_3); 
        String eTitle = title.getText().toString(); 
        String eShortDesc = shortDesc.getText().toString(); 
        String eLocation = location.getText().toString(); 
        String eUrl = imguri.toString(); 
        userid = FirebaseAuth.getInstance().getUid(); 
        getCate(); 
        data.put("Img", eUrl); 
        data.put("Title", eTitle); 
        data.put("Location", eLocation); 
        data.put("Short Description", eShortDesc); 
        data.put("Category", cate ); 
        data.put("id", userid); 
        db.collection("Item").add(data); 
        Toast.makeText(this, "Successfully saved your item", Toast.LENGTH_SHORT).show(); 
        Intent i = new Intent(this, Home.class); 
        startActivity(i);
    }