0

I really need your help guys as I am still learning Java. So to boost my skills I am following many tutorials and asking lots of questions especially here.

I have a profile activity that user upload image, text to firbase storage, and another activity that user can view all images, the image is uploaded fine as well as the text, but when to view them I am having problem and not even showing error just getting a blank grey image with the text (name). When I checked the ImageUrl is stored as com.google.android.gms.tasks.zzu@ac6375a. Here is my full activities.

MyProfile

public class MyProfile extends AppCompatActivity {

// Folder path for Firebase Storage.
String Storage_Path = "All_Image_Uploads/";

// Root Database Name for Firebase Database.
public static final String Database_Path = "DefaultImages";

// Creating button.
Button ChooseButton, UploadButton, DisplayImageButton;

// Creating EditText.
EditText ImageName ;

// Creating ImageView.
ImageView SelectImage;

// Creating URI.
Uri FilePathUri;

// Creating StorageReference and DatabaseReference object.
StorageReference storageReference;
DatabaseReference databaseReference;

// Image request code for onActivityResult() .
int Image_Request_Code = 7;

ProgressDialog progressDialog ;

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

    // Assign FirebaseStorage instance to storageReference.
    storageReference = FirebaseStorage.getInstance().getReference();

    // Assign FirebaseDatabase instance with root database name.
    databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);

    //Assign ID'S to button.
    ChooseButton = (Button)findViewById(R.id.ButtonChooseImage);
    UploadButton = (Button)findViewById(R.id.ButtonUploadImage);

    DisplayImageButton = (Button)findViewById(R.id.DisplayImagesButton);

    // Assign ID's to EditText.
    ImageName = (EditText)findViewById(R.id.ImageNameEditText);

    // Assign ID'S to image view.
    SelectImage = (ImageView)findViewById(R.id.ShowImageView);

    // Assigning Id to ProgressDialog.
    progressDialog = new ProgressDialog(MyProfile.this);

    // Adding click listener to Choose image button.
    ChooseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Creating intent.
            Intent intent = new Intent();

            // Setting intent type as image to select image from phone storage.
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Please Select Image"), Image_Request_Code);

        }
    });


    // Adding click listener to Upload image button.
    UploadButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling method to upload selected image on Firebase storage.
            UploadImageFileToFirebaseStorage();

        }
    });


    DisplayImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(MyProfile.this, DisplayImagesActivity.class);
            startActivity(intent);

        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == Image_Request_Code && resultCode == RESULT_OK && data != null && data.getData() != null) {

        FilePathUri = data.getData();

        try {

            // Getting selected image into Bitmap.
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);

            // Setting up bitmap selected image into ImageView.
            SelectImage.setImageBitmap(bitmap);

            // After selecting image change choose button above text.
            ChooseButton.setText("Image Selected");

        }
        catch (IOException e) {

            e.printStackTrace();
        }
    }
}

// Creating Method to get the selected image file Extension from File Path URI.
public String GetFileExtension(Uri uri) {

    ContentResolver contentResolver = getContentResolver();

    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();

    // Returning the file Extension.
    return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;

}

// Creating UploadImageFileToFirebaseStorage method to upload image on storage.
public void UploadImageFileToFirebaseStorage() {

    // Checking whether FilePathUri Is empty or not.
    if (FilePathUri != null) {

        // Setting progressDialog Title.
        progressDialog.setTitle("Image is Uploading...");

        // Showing progressDialog.
        progressDialog.show();

        // Creating second StorageReference.
        StorageReference storageReference2nd = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));

        // Adding addOnSuccessListener to second StorageReference.
        storageReference2nd.putFile(FilePathUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                        // Getting image name from EditText and store into string variable.
                        String TempImageName = ImageName.getText().toString().trim();

                        // Hiding the progressDialog after done uploading.
                        progressDialog.dismiss();

                        // Showing toast message after done uploading.
                        Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();

                        @SuppressWarnings("VisibleForTests")
                       ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());

                        // Getting image upload ID.
                        String ImageUploadId = databaseReference.push().getKey();

                        // Adding image upload id s child element into databaseReference.
                       databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
                    }
                })
                // If something goes wrong .
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {

                        // Hiding the progressDialog.
                        progressDialog.dismiss();

                        // Showing exception erro message.
                        Toast.makeText(MyProfile.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                    }
                })

                // On progress change upload time.
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

                        // Setting progressDialog Title.
                        progressDialog.setTitle("Image is Uploading...");

                    }
                });
    }
    else {

        Toast.makeText(MyProfile.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();

    }
}

}

and here is DisplayImage

public class DisplayImagesActivity extends AppCompatActivity {

// Creating DatabaseReference.
DatabaseReference databaseReference;

// Creating RecyclerView.
RecyclerView recyclerView;

// Creating RecyclerView.Adapter.
RecyclerView.Adapter adapter ;

// Creating Progress dialog
ProgressDialog progressDialog;

// Creating List of ImageUploadInfo class.
List<ImageUploadInfo> list = new ArrayList<>();


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

    // Assign id to RecyclerView.
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

    // Setting RecyclerView size true.
    recyclerView.setHasFixedSize(true);

    // Setting RecyclerView layout as LinearLayout.
    recyclerView.setLayoutManager(new LinearLayoutManager(DisplayImagesActivity.this));

    // Assign activity this to progress dialog.
    progressDialog = new ProgressDialog(DisplayImagesActivity.this);

    // Setting up message in Progress dialog.
    progressDialog.setMessage("Loading Images From Firebase.");

    // Showing progress dialog.
    progressDialog.show();

    // Setting up Firebase image upload folder path in databaseReference.
    // The path is already defined in MainActivity.
    databaseReference = FirebaseDatabase.getInstance().getReference(MyProfile.Database_Path);

    // Adding Add Value Event Listener to databaseReference.
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                ImageUploadInfo imageUploadInfo = postSnapshot.getValue(ImageUploadInfo.class);

                list.add(imageUploadInfo);
            }

            adapter = new RecyclerViewAdapter(getApplicationContext(), list);

            recyclerView.setAdapter(adapter);

            // Hiding the progress dialog.
            progressDialog.dismiss();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

            // Hiding the progress dialog.
            progressDialog.dismiss();

        }
    });

}

}

and the HolderView

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

Context context;
List<ImageUploadInfo> MainImageUploadInfoList;

public RecyclerViewAdapter(Context context, List<ImageUploadInfo> TempList) {

    this.MainImageUploadInfoList = TempList;

    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items2, parent, false);

    ViewHolder viewHolder = new ViewHolder(view);

    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ImageUploadInfo UploadInfo = MainImageUploadInfoList.get(position);

    holder.imageNameTextView.setText(UploadInfo.getImageName());

    //Loading image from Glide library.
 //Picasso.with(context).load(UploadInfo.getImageURL()).into(holder.imageView);
Glide.with(context).load(UploadInfo.getImageURL()).into(holder.imageView);
}

@Override
public int getItemCount() {

    return MainImageUploadInfoList.size();
}

class ViewHolder extends RecyclerView.ViewHolder {

    public ImageView imageView;
    public TextView imageNameTextView;

    public ViewHolder(View itemView) {
        super(itemView);

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

        imageNameTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView);
    }
}

}

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
altin bana
  • 101
  • 1
  • 12
  • You're not using getDownloadUrl correctly. See the dup and documentation for the correct way. – Doug Stevenson Mar 19 '20 at 03:05
  • Thanks for the link but I have already tried that also this was three years ago and getDownloadURL is depreciated so maybe this is where I am going wrong? Strange that this code was copied from a working tutorial but not sure why its showing blank image. – altin bana Mar 19 '20 at 04:10
  • It's not really deprecated. The way you use it has just changed. Follow the instructions in the other question, which is derived from the documentation. – Doug Stevenson Mar 19 '20 at 04:11
  • This (ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()); ) using version 16 or lower didnt work , but using version 11 or lower like this " (ImageUploadInfo imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getDownloadUrl().toString());" worked, so problem was getDownload is changed now and I am stack with older version. – altin bana Mar 21 '20 at 03:45
  • Ok! I finally got the problem solved, this code was copied from a working example but two years old, I have managed to fix it by changing my firebase versions, the issue was getDownloadUrl the way the latest firebase was written, I am totally newbie and I was hoping to get a quick answer here, I'am sure this would help others like me who are trying to learn. Not sure when using " imageUploadInfo = new ImageUploadInfo(TempImageName, taskSnapshot.getDownloadUrl().toString()); " I get cannot resolve getDownloadUrl its red with version 16 but with lower version like 11 works and link is correct. – altin bana Mar 21 '20 at 04:36

0 Answers0