1

I'm trying to make an app where users are able to signup for an account and they can upload images. I got the uploading part down pack but I want to retrieve those images to the user on their profile page but I don't know how to. Can someone show me how I can retrieve those images I want to use a recycler view for this. Thanks in advance. Below is my code

// Upload Image class

public class UploadImageActivity extends AppCompatActivity implements View.OnClickListener {

    int PICK_IMAGE_REQUEST=234;
    private Button upload,button2;
    private ImageView imageView;
    private Uri filepath;
    FirebaseAuth firebaseAuth;
    FirebaseUser firebaseUser;
    FirebaseDatabase firebaseDatabase;
    TextView next;

    FirebaseStorage firebaseStorage;
    StorageReference storageReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_ad);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);


        firebaseStorage=FirebaseStorage.getInstance();
        storageReference=firebaseStorage.getReference();
        next=findViewById(R.id.next0);

        firebaseUser= firebaseAuth.getInstance().getCurrentUser();
        firebaseDatabase.getInstance().getReference();



        upload=findViewById(R.id.button_upload);
        button2=findViewById(R.id.submit);
        imageView=findViewById(R.id.view_image);

        upload.setOnClickListener(this);


    }

    private void showFileChooser(){
        Intent intent=new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Choose an image"),PICK_IMAGE_REQUEST);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode== PICK_IMAGE_REQUEST && resultCode == RESULT_OK
                && data != null
                && data.getData() != null){
            next.setTextColor(Color.parseColor("#FF4500"));
            next.setEnabled(true);



            filepath=data.getData();




            try {
                // Bitmap bitmap=new Compressor(this).setMaxHeight(200) //Set height and width
                // .setMaxWidth(200)
                //.setQuality(100) // Set Quality
                //.compressToBitmap(file);
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),filepath);
                imageView.setImageBitmap(bitmap);
                // build alert dialog


            } catch (IOException e) {
                e.printStackTrace();
            }







        }


        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(filepath != null) {



                    final ProgressDialog progressDialog=new ProgressDialog(UploadAdActivity.this);
                    progressDialog.setTitle("Uploading");
                    progressDialog.show();


                    int aNumber = (int) (20 * Math.random()) + 1;


                    //StorageReference riversRef=storageReference.child(firebaseUser.getUid()+"/"+"image.png");
                    // StorageReference=firebaseStorage.getInstance().getReferenceFromUrl()
                    StorageReference riversRef = storageReference.child(System.currentTimeMillis()+"."+getExtension(filepath));

                    //final String url=riversRef.getDownloadUrl().getResult().toString();
                    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
                    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("Users");
                    final DatabaseReference update = rootRef.child(uid).child("images");





                    riversRef.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            progressDialog.dismiss();
                            Toast.makeText(UploadAdActivity.this,"Uploaded successfully",Toast.LENGTH_LONG).show();
                            storageReference.getDownloadUrl();
                            taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    String download_url=uri.toString();
                                    update.child("images").setValue(download_url);

                                }
                            });
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            progressDialog.dismiss();
                            Toast.makeText(UploadAdActivity.this,"Failed to upload",Toast.LENGTH_LONG).show();
                        }
                    }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
                            double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
                                    .getTotalByteCount());
                            progressDialog.setMessage("Uploaded "+(int)progress+"%");                }
                    });




                }


            }


        });

    }

    private String getExtension(Uri filepath) {
        ContentResolver contentResolver=getContentResolver();
        MimeTypeMap mimeTypeMap=MimeTypeMap.getSingleton();
        return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(filepath));

    };


    @Override
    public void onClick(View v) {

        if(v==upload){
            showFileChooser();
            //uploadImage();
            next.setTextColor(Color.parseColor("#FF4500"));



            /*
            Intent i = new Intent(UploadAdActivity.this, ActionActivity.class);
            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(i);

             */

        }



    }






}

//Users profile
 public class ProfileActivity extends AppCompatActivity implements View.OnClickListener {

   private RecyclerView recyclerView;
   private ImageAdapter mAdapter;

   private DatabaseReference databaseReference;
   private List<Upload> mUploads;
   FirebaseAuth firebaseAuth;
   FirebaseUser firebaseUser;
    int PICK_IMAGE_REQUEST=234;
    private Button upload,button2;
    private ImageView imageView;
    private Uri filepath;
    FirebaseDatabase firebaseDatabase;
    FirebaseStorage firebaseStorage;
    StorageReference storageReference;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
        overridePendingTransition(R.anim.slide_right, R.anim.slide_left);

        mUploads=new ArrayList<>();

        mAdapter=new ImageAdapter(ProfileActivity.this, mUploads);


        recyclerView=findViewById(R.id.recyclerView);
        //recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);

        firebaseStorage=FirebaseStorage.getInstance();
        storageReference=firebaseStorage.getReference();

        firebaseUser= firebaseAuth.getInstance().getCurrentUser();
        firebaseDatabase.getInstance().getReference();



        upload=findViewById(R.id.button_upload);
        button2=findViewById(R.id.submit);
        imageView=findViewById(R.id.view_image);
        upload.setOnClickListener(this);



        String uid=FirebaseAuth.getInstance().getCurrentUser().getUid();




        databaseReference=FirebaseDatabase.getInstance().getReference();
        //databaseReference.child("images");

        databaseReference.orderByChild(uid).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot postsnapshot:dataSnapshot.getChildren()){

                    Upload upload=postsnapshot.getValue(Upload.class);
                    mUploads.add(upload);


                }

                mAdapter.notifyDataSetChanged();




            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(ProfileActivity.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();

            }
        });




        recyclerView.setAdapter(mAdapter); //Again set adapter to recyclerview




    }

   //Adapter class
   public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder>{

    private Context mContext;
    private List<Upload> mUploads;

    public ImageAdapter(Context context,List<Upload> uploads){
        mContext = context;
        mUploads = uploads;

    }

    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View V = LayoutInflater.from(mContext).inflate(R.layout.cardview, parent, false);
        return new ImageViewHolder(V);


    }

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
        Upload uploadCurrent=mUploads.get(position);
        Picasso.get().load(uploadCurrent.getmImageUrl()).fit().centerCrop().into(holder.imageView);

    }

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

    }

    public class ImageViewHolder extends RecyclerView.ViewHolder{
        public ImageView imageView;

        public ImageViewHolder(@NonNull View itemView) {
            super(itemView);

            imageView=itemView.findViewById(R.id.imageview);
        }
    }
}

   //Upload class

  public class Upload {
    private String images;

    public Upload(){
        //Empty constructor needed
    }

    public Upload (String imageUrl){
        images=imageUrl;

    }

    public String getmImageUrl() {
        return images;
    }

    public void setmImageUrl(String images) {
        this.images = images;
    }
}

Updated Database Structure

Firebase storage

t5050
  • 69
  • 8
  • See here:https://stackoverflow.com/questions/60520000/ – MMG Mar 12 '20 at 04:09
  • @MohammadMoeinGolchin I tried the answers nothing is working – t5050 Mar 12 '20 at 04:56
  • I had the same problem. Its reason is that when firebase hasn't read data from realtime database yet, recyclerview has been made; and it hasn't have any data yet. For solving that you should make recyclerview when you are sure that firebase has read data. Then recyclerview will be made with correct data. – MMG Mar 12 '20 at 05:02
  • Make your recyclerview after finishing reading data. – MMG Mar 12 '20 at 05:03
  • @MohammadMoeinGolchin Can you show me how I should do that? Example will be helpful – t5050 Mar 12 '20 at 05:16
  • Put mAdapter.notifyDataSetChanged(); into for(DataSnapshot postsnapshot:dataSnapshot.getChildren()){ Upload upload=postsnapshot.getValue(Upload.class); mUploads.add(upload); } – MMG Mar 12 '20 at 05:20
  • Have you saved images correctly? – MMG Mar 12 '20 at 05:28
  • Yes images are saved correctly in firebase storage – t5050 Mar 12 '20 at 05:31
  • Did Changing place of mAdapter.notifyDataSetChanged() work for you? – MMG Mar 12 '20 at 05:33
  • No sadly it did not. I really don't know what the problem is – t5050 Mar 12 '20 at 05:38
  • You just have not any image for first time or you never have images so that images don't upload at all? – MMG Mar 12 '20 at 05:40
  • I have images look I just edited my question and added a screenshot of the firebase storge theres two images there – t5050 Mar 12 '20 at 05:45
  • You have images in your database, but my question is do you read it correctly form database? Try that – MMG Mar 12 '20 at 05:48
  • I think I read it correctly sir – t5050 Mar 12 '20 at 05:55

2 Answers2

1

Put recyclerView.setAdapter(mAdapter);

after

databaseReference.orderByChild(uid).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot postsnapshot:dataSnapshot.getChildren()){

                    Upload upload=postsnapshot.getValue(Upload.class);
                    mUploads.add(upload);

                }

                mAdapter.notifyDataSetChanged();



            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(ProfileActivity.this,databaseError.getMessage(),Toast.LENGTH_LONG).show();

            }
        });
MMG
  • 3,226
  • 5
  • 16
  • 43
  • No it dosen't work. Still no images being displayed – t5050 Mar 12 '20 at 05:58
  • You should test and be sure first that you can read images at all or not. – MMG Mar 12 '20 at 05:59
  • Sorry for the late reply . How do I make sure of that? for my firebase storage rules i have this written rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow write: if request.auth != null; allow read, write: if request.auth != null; } } } – t5050 Mar 12 '20 at 18:38
  • 1
    You can show image without recyclerview? You should test this first. Then you can give images to recyclerview. – MMG Mar 12 '20 at 18:57
  • Ok i tried to do it without using a recycler view I dont get any errors, I just get warning messages. I just posted the warning messages i'm getting. Can you help me with that? I think its telling me it unable to load the image – t5050 Mar 12 '20 at 19:48
  • You see your images or not? – MMG Mar 12 '20 at 20:00
  • No images sir. I also updated my databse structure I posted that so you can see – t5050 Mar 12 '20 at 20:04
  • Your problem is not showing data in recyclerview, you haven't read images correctly yet. – MMG Mar 12 '20 at 20:50
  • Sir my problem still wasn’t solved the images still are not displaying. How can I read it correctly? What am I suppose to do here? Can you show what has to be done? – t5050 Mar 12 '20 at 21:02
  • I think you should ask another question about showing images – MMG Mar 12 '20 at 21:04
  • Ok sir I will. Thank you so much for being very patient with me and taking your time out to help me. Have a great day – t5050 Mar 12 '20 at 21:29
  • I just did that for you – t5050 Mar 12 '20 at 21:33
0

create a refresh function in adaptor

public void refresh(List<Upload> uploads){
    this.uploads=uploads;
    notifyDataSetChanged();
 }

call this where you get the data from server or firebase using adaptor like this

mAdapter.refresh(mUploads);
Amit pandey
  • 1,149
  • 1
  • 4
  • 15