Unable to retrieve image from Firebase


Samsul Islam |

I'm trying to build a messenger type app. For this, I have uploaded the image from my phone to Firebase. The image is successfully stored in Firebase Storage. I am trying to display an image on my phone. I'm using both Picasso and Glide to retrieve images from Firebase. But my photo is not showing. However, when I add the placeholder, I can see the default image set by the placeholder. How can I solve this problem? My code is as follows:

package com.example.ichat;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.util.HashMap;

import de.hdodenhof.circleimageview.CircleImageView;

public class SettingsActivity extends AppCompatActivity {
    private Button UpdateAccountSetting;
    private EditText userName, userStatus;
    private CircleImageView userProfileImage;
    private String currentUserId;
    private FirebaseAuth mAuth;
    private DatabaseReference RootRef;
    private static final int GalleryPick = 1;
    private StorageReference UserProfileImagesRef;
    private ProgressDialog loadingBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        FirebaseApp.initializeApp(this);
        mAuth = FirebaseAuth.getInstance();
        currentUserId = mAuth.getCurrentUser().getUid();
        RootRef = FirebaseDatabase.getInstance().getReference();
        UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");

        InitializeFields();

        UpdateAccountSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateSettings();
            }
        });

        RetrieveUserInfo();

        userProfileImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent();
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent,GalleryPick);
            }
        });
    }

    private void RetrieveUserInfo() {
        RootRef.child("Users").child(currentUserId).addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")) && (dataSnapshot.hasChild("image"))){
                    String retrieveUserName = dataSnapshot.child("name").getValue().toString();
                    String retrieveStatus = dataSnapshot.child("status").getValue().toString();
                    String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();

                    userName.setText(retrieveUserName);
                    userStatus.setText(retrieveStatus);
                    Glide.with(SettingsActivity.this).load(retrieveProfileImage).placeholder(R.drawable.profile_image).into(userProfileImage);
                    //Picasso.get().load(retrieveProfileImage).into(userProfileImage);
                    //Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profile_image).resize(100,100).centerCrop().into(userProfileImage);
                }
                else if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
                    String retrieveUserName = dataSnapshot.child("name").getValue().toString();
                    String retrieveStatus = dataSnapshot.child("status").getValue().toString();

                    userName.setText(retrieveUserName);
                    userStatus.setText(retrieveStatus);
                }
                else {
                    userName.setVisibility(View.VISIBLE);
                    Toast.makeText(getApplicationContext(),"Please set & update your profile information...",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        /*
        RootRef.child("Users").child(currentUserId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")) && (dataSnapshot.hasChild("image"))){
                    String retrieveUserName = dataSnapshot.child("name").getValue().toString();
                    String retrieveStatus = dataSnapshot.child("status").getValue().toString();
                    String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();

                    userName.setText(retrieveUserName);
                    userStatus.setText(retrieveStatus);
                    Glide.with(SettingsActivity.this).load(retrieveProfileImage).placeholder(R.drawable.profile_image).into(userProfileImage);
                    //Picasso.get().load(retrieveProfileImage).into(userProfileImage);
                    //Picasso.get().load(retrieveProfileImage).placeholder(R.drawable.profile_image).resize(100,100).centerCrop().into(userProfileImage);
                }
                else if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))){
                    String retrieveUserName = dataSnapshot.child("name").getValue().toString();
                    String retrieveStatus = dataSnapshot.child("status").getValue().toString();

                    userName.setText(retrieveUserName);
                    userStatus.setText(retrieveStatus);
                }
                else {
                    userName.setVisibility(View.VISIBLE);
                    Toast.makeText(getApplicationContext(),"Please set & update your profile information...",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });*/
    }

    private void UpdateSettings() {
        String setUserName = userName.getText().toString();
        String setStatus = userStatus.getText().toString();
        if (TextUtils.isEmpty(setUserName)) {
            Toast.makeText(this,"Please write your user name first....",Toast.LENGTH_SHORT).show();
        }
        if (TextUtils.isEmpty(setStatus)) {
            Toast.makeText(this,"Please write your status....",Toast.LENGTH_SHORT).show();
        }
        else {
            HashMap<String, Object> profileMap = new HashMap<>();
            profileMap.put("uid", currentUserId);
            profileMap.put("name", setUserName);
            profileMap.put("status", setStatus);
            RootRef.child("Users").child(currentUserId).updateChildren(profileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if(task.isSuccessful()){
                        Intent mainIntent = new Intent(getApplicationContext(),MainActivity.class);
                        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(mainIntent);
                        finish();
                        Toast.makeText(getApplicationContext(),"Profile Updated Successfully...",Toast.LENGTH_SHORT).show();
                    }
                    else {
                        String message = task.getException().toString();
                        Toast.makeText(getApplicationContext(),"Error : "+message,Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    private void InitializeFields() {
        UpdateAccountSetting = findViewById(R.id.update_settings_button);
        userName = findViewById(R.id.set_user_name);
        userStatus =findViewById(R.id.set_profile_status);
        userProfileImage = findViewById(R.id.set_profile_image);
        loadingBar = new ProgressDialog(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            Uri ImageUri = data.getData();
            loadingBar.setTitle("Set Profile Image");
            loadingBar.setMessage("Please wait, your profile image is updating...");
            loadingBar.setCanceledOnTouchOutside(false);
            loadingBar.show();
            StorageReference filePath = UserProfileImagesRef.child(currentUserId+".jpg");
            filePath.putFile(ImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Toast.makeText(getApplicationContext(),"Profile Image uploaded Successfully...",Toast.LENGTH_SHORT).show();
                        final String downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
                        RootRef.child("Users").child(currentUserId).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if(task.isSuccessful()){
                                    Toast.makeText(getApplicationContext(),"Image save in Database Successfully...",Toast.LENGTH_SHORT).show();
                                    loadingBar.dismiss();
                                }
                                else{
                                    String message = task.getException().toString();
                                    Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
                                    loadingBar.dismiss();
                                }
                            }
                        });

                }
            });
            //String downloadUrl = filePath.getDownloadUrl().toString();
            /*filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if(task.isSuccessful()){
                        Toast.makeText(getApplicationContext(),"Profile Image uploaded Successfully...",Toast.LENGTH_SHORT).show();
                        final String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
                        RootRef.child("Users").child(currentUserId).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if(task.isSuccessful()){
                                    Toast.makeText(getApplicationContext(),"Image save in Database Successfully...",Toast.LENGTH_SHORT).show();
                                    loadingBar.dismiss();
                                }
                                else{
                                    String message = task.getException().toString();
                                    Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
                                    loadingBar.dismiss();
                                }
                            }
                        });
                    }
                    else{
                        String message = task.getException().toString();
                        Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }
            });*/
        }
    }
}

My XML file code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/settingsbackground"
    tools:context=".SettingsActivity">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/set_profile_image"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="90dp"
        android:src="@drawable/profile_image"
        />

    <EditText
        android:id="@+id/set_user_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/set_profile_image"
        android:inputType="textMultiLine"
        android:hint="Username"
        android:textSize="24sp"
        android:textStyle="bold"
        android:layout_marginLeft="55dp"
        android:layout_marginRight="60dp"
        android:padding="15dp"
        android:layout_marginTop="10dp"/>

    <EditText
        android:id="@+id/set_profile_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/set_user_name"
        android:inputType="textMultiLine"
        android:hint="Hey, I am available now"
        android:textSize="24sp"
        android:textStyle="bold"
        android:layout_marginLeft="55dp"
        android:layout_marginRight="60dp"
        android:padding="15dp"
        android:layout_marginTop="10dp"/>

    <Button
        android:id="@+id/update_settings_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/set_profile_status"
        android:inputType="textMultiLine"
        android:text="Update"
        android:background="@drawable/update_btn_style"
        android:textStyle="bold"
        android:padding="6dp"
        android:layout_marginTop="135dp"
        android:layout_marginLeft="200dp"
        android:layout_marginRight="75dp"
        android:textAllCaps="false"
        android:textSize="28sp"/>

</RelativeLayout>

My gradle file code:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
        classpath 'com.google.gms:google-services:4.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenCentral()
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

my build.gradle file

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.ichat"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-auth:16.0.3'
    implementation 'com.google.firebase:firebase-database:16.0.1'
    implementation 'com.google.firebase:firebase-storage:16.0.1'
    implementation 'com.google.firebase:firebase-messaging:17.3.2'
    implementation 'com.android.support:support-v4:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'de.hdodenhof:circleimageview:3.0.0'
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
}

My Firebase Data Structure: My Firebase Data Structure

Ashvin Solanki

With this line you final String downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();can't get the correct image download url, so usefilePath.getDownloadUrl()

Example

filePath.putFile(ImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                final String downloadUrl = uri;
                        RootRef.child("Users").child(currentUserId).child("image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if(task.isSuccessful()){
                                    Toast.makeText(getApplicationContext(),"Image save in Database Successfully...",Toast.LENGTH_SHORT).show();
                                    loadingBar.dismiss();
                                }
                                else{
                                    String message = task.getException().toString();
                                    Toast.makeText(getApplicationContext(),"Error:"+message,Toast.LENGTH_SHORT).show();
                                    loadingBar.dismiss();
                                }
                            }
                        });
            }
        });
    }
});

or use continueWithTask

//add file on Firebase and got Download Link
filePath.putFile(imageUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
    @Override
    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
        if (!task.isSuccessful()){
            throw task.getException();
        }
        return filePath.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()){
            Uri downUri = task.getResult();
            Log.d(TAG, "onComplete: Url: "+ downUri.toString());
        }
    }
});

Related


Unable to retrieve image from Firebase

Samsul Islam | I'm trying to build a messenger type app. For this, I have uploaded the image from my phone to Firebase. The image is successfully stored in Firebase Storage. I am trying to display an image on my phone. I'm using both Picasso and Glide to retri

Unable to retrieve image from Firebase

Samsul Islam | I'm trying to build a messenger type app. For this, I have uploaded the image from my phone to Firebase. The image is successfully stored in Firebase Storage. I am trying to display an image on my phone. I'm using both Picasso and Glide to retri

Unable to retrieve image from Firebase

Samsul Islam | I'm trying to build a messenger type app. For this, I have uploaded the image from my phone to Firebase. The image is successfully stored in Firebase Storage. I am trying to display an image on my phone. I'm using both Picasso and Glide to retri

Unable to retrieve image from Firebase

Samsul Islam | I'm trying to build a messenger type app. For this, I have uploaded the image from my phone to Firebase. The image is successfully stored in Firebase Storage. I am trying to display an image on my phone. I'm using both Picasso and Glide to retri

Unable to retrieve image from firebase storage

Ruchit Patel So far, I have successfully uploaded the image to Firebase, but when retrieving it to the recycler view, I'm having trouble retrieving the image at all. Take a look at my source code: Here is the Recycler View adapter: public class MyAdapter exten

Unable to retrieve image from firebase storage

Ruchit Patel So far, I have successfully uploaded the image to Firebase, but when retrieving it to the recycler view, I'm having trouble retrieving the image at all. Take a look at my source code: Here is the Recycler View adapter: public class MyAdapter exten

Unable to retrieve Int from Firebase

Batuhan I'm trying to retrieve an Int from Firestore, but I can't say "The result of a call to 'append' is unused" Here is my code: class pointsM: ObservableObject { @Published var point = 0 init() { let db = Firestore.firestore() let user = Auth.auth(

Unable to retrieve image from dropbox

Samuel Mathews Hi! I have an image slider. When I try to retrieve the image from the server, the image is displayed correctly. ( http://stthomasmountmtc.org/index.html ) However, when I try to retrieve the same image from Dropbox, the image is not displayed/re

Unable to retrieve image from dropbox

Samuel Mathews Hi! I have an image slider. When I try to retrieve the image from the server, the image is displayed correctly. ( http://stthomasmountmtc.org/index.html ) However, when I try to retrieve the same image from Dropbox, the image is not displayed/re

Unable to retrieve image using Picasso FRM Firebase

Ahmet Keles: My problem is that when I try to manually fetch the image from firebase storage, nothing shows up on the imageview, no error, no sign of the wrong code, so I'm confused as to where I'm going wrong, I want to put all the lines of code with for deta

Unable to retrieve image using Picasso FRM Firebase

Ahmet Keles: My problem is that when I try to manually fetch the image from firebase storage, nothing shows up on the imageview, no error, no sign of the wrong code, so I'm confused as to where I'm going wrong, I want to put all the lines of code with for deta

Unable to retrieve image using Picasso FRM Firebase

Ahmet Keles: My problem is that when I try to manually fetch the image from firebase storage, nothing shows up on the imageview, no error, no sign of the wrong code, so I'm confused as to where I'm going wrong, I want to put all the lines of code with for deta

Unable to retrieve image using Picasso FRM Firebase

Ahmet Keles: My problem is that when I try to manually fetch the image from firebase storage, nothing shows up on the imageview, no error, no sign of the wrong code, so I'm confused as to where I'm going wrong, I want to put all the lines of code with for deta

Unable to retrieve data from Firebase in Django

Ansel D'souza: I've been trying to get data from Firebase into my Django app and the problem I'm facing is that some documents are being retrieved and some are not. One very strange thing I've noticed is that on the admin page, the documents that are accessibl

Unable to retrieve data from Firebase database

Vishal I have a Firebase database as shown. I'm trying to retrieve data based on some criteria but it's not showing any results. DbRef2 =FirebaseDatabase.getInstance().getReference().child("Notification"); DbRef2.child("45961").orderByChild("FromId").

Unable to retrieve data from Firebase in Django

Ansel D'souza: I've been trying to get data from Firebase into my Django app and the problem I'm facing is that some documents are being retrieved and some are not. One very strange thing I've noticed is that on the admin page, the documents that are accessibl

Unable to retrieve data from Firebase database

Naga Hermans Here is my component. I don't know why the data cannot be retrieved from Firebase. Can anyone tell me what's wrong in this code? import { Component, OnInit, Input, ViewChild } from '@angular/core'; import { AngularFireDatabase, FirebaseListObserva

Unable to retrieve list of documents from Firebase

Yuval I'm trying to retrieve a list of documents using the admin SDK and firestore api on my firebase functions. I try to use the following method: import * as admin from 'firebase-admin'; const adminFirestore = admin.firestore(); adminFirestore.collection

Unable to retrieve data from Firebase database

Vishal I have a Firebase database as shown. I'm trying to retrieve data based on some criteria but it's not showing any results. DbRef2 =FirebaseDatabase.getInstance().getReference().child("Notification"); DbRef2.child("45961").orderByChild("FromId").

Unable to retrieve data from Firebase using dataSnapshot

Kartik Singh | My Firebase database looks like above I'm trying to retrieve the 'a' value of 'alind' and similarly I'm using Android Studio to retrieve another child node 'kartik'. but I am getting this error - java.lang.NullPointerException: Attempt to invoke

Unable to retrieve data from Firebase by retrieving 'number'

build new I am new to learning how to create an app using android studio and firebase realtime storage. I'm trying to make an app that can easily retrieve details from firebase, the apps stop by themselves when trying to retrieve details from firebase. As laid

Unable to retrieve data from Firebase in Angular 7

atheesh27 I want to retrieve dataset from firebase database and populate my dropdown list. But nothing came up. I've done a lot of research but still can't figure it out. I am using Angular 7 . ERROR Error: "Cannot find a differ supporting object 'function (ev

Unable to retrieve data from Firebase Realtime Database

Manjujohn I am a beginner in angular. When I try to retrieve the data using the AngularFireDatabase object, I don't get the data in the required format interface: export interface AppUser { name: string; email: string; isAdmin: boolean; } function call: get

Unable to retrieve data from Firebase using dataSnapshot

Kartik Singh | My Firebase database looks like above I'm trying to retrieve the 'a' value of 'alind' and similarly I'm using Android Studio to retrieve another child node 'kartik'. but I am getting this error - java.lang.NullPointerException: Attempt to invoke

Unable to retrieve data from Firebase by retrieving 'number'

build new I am new to learning how to create an app using android studio and firebase realtime storage. I'm trying to make an app that can easily retrieve details from firebase, the apps stop by themselves when trying to retrieve details from firebase. As laid

Unable to retrieve data from Firebase database

Naga Hermans Here is my component. I don't know why the data cannot be retrieved from Firebase. Can anyone tell me what's wrong in this code? import { Component, OnInit, Input, ViewChild } from '@angular/core'; import { AngularFireDatabase, FirebaseListObserva