and-nd-firebase icon indicating copy to clipboard operation
and-nd-firebase copied to clipboard

Store photo in Firebase Storage.

Open swdevdave opened this issue 6 years ago • 19 comments

The following should be updated as there was a recent change to Firebase.

implementation 'com.firebaseui:firebase-ui-auth:4.0.0'

        // Upload file to Firebase Storage
        photoRef.putFile(selectedImageUri);
        mChatPhotosStorageReference.putFile(selectedImageUri).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 mChatPhotosStorageReference.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri downloadUri = task.getResult();
                        FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
                        mMessagesDatabaseReference.push().setValue(friendlyMessage);
                    }                         
                 }
            });
    }

swdevdave avatar Jun 15 '18 03:06 swdevdave

@swdevdave As others partners here, I tried your code but, the photo doesn't upload at all and doesn't show up on screen either.

E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb40fc300 Not supplying enough data to HAL, expected position 68787138 , only wrote 68650799

RRGT19 avatar Jul 07 '18 20:07 RRGT19

@swdevdave I have also tried your code snippet and it is not working. Do you have any tips? @RRGT19 Were you able to upload the photos? Mine is still not uploading.

ibnahmadbello avatar Jul 18 '18 12:07 ibnahmadbello

@swdevdave and @RRGT19 Never mind about my above comment because I have fixed the bug. One of my if statement was blocking the code from running. Thanks.

ibnahmadbello avatar Jul 18 '18 13:07 ibnahmadbello

Hey guys, I take a look at Firebase documentation and I was able to upload the picture with this code:

} else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();

            // Get a reference to store file at chat_photos/<FILENAME>
            StorageReference photoRef =
                    mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

            UploadTask uploadTask = photoRef.putFile(selectedImageUri);

            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d(TAG,"Unsuccessful upload");
                }
            }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Uri downloadUrl = taskSnapshot.getDownloadUrl();
                    assert downloadUrl != null;
                    FriendlyMessage friendlyMessage =
                            new FriendlyMessage(null, mUsername, downloadUrl.toString());
                    mMessagesDatabaseReference.push().setValue(friendlyMessage);
                }
            });
        }

carlosughini avatar Oct 16 '18 19:10 carlosughini

its not working... My whole day went with this problem

faisalmushtaq007 avatar Jan 20 '19 19:01 faisalmushtaq007

The following should be updated as there was a recent change to Firebase.

implementation 'com.firebaseui:firebase-ui-auth:4.0.0'

        // Upload file to Firebase Storage
        photoRef.putFile(selectedImageUri);
        mChatPhotosStorageReference.putFile(selectedImageUri).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 mChatPhotosStorageReference.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri downloadUri = task.getResult();
                        FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
                        mMessagesDatabaseReference.push().setValue(friendlyMessage);
                    }                         
                 }
            });
    }

its not working for me as well for others and still there is no problem looking in code at all ??

prashantk01 avatar Apr 15 '19 14:04 prashantk01

not working !!

harisvm avatar Dec 16 '19 01:12 harisvm

Ey, this code works

StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
                            photoRef.putFile(selectedImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                    photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                        @Override
                                        public void onSuccess(Uri uri) {
                                            FriendlyMessage friendlyMessage = new FriendlyMessage(mUsername, uri.toString());
                                            mMessageDatabaseReference.push().setValue(friendlyMessage);
                                            Toast.makeText(MainActivity.this, "Photo Uploaded and URL is : " + uri.toString(), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            });

5AbhishekSaxena avatar Jan 17 '20 21:01 5AbhishekSaxena

The following should be updated as there was a recent change to Firebase.

implementation 'com.firebaseui:firebase-ui-auth:4.0.0'

        // Upload file to Firebase Storage
        photoRef.putFile(selectedImageUri);
        mChatPhotosStorageReference.putFile(selectedImageUri).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 mChatPhotosStorageReference.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri downloadUri = task.getResult();
                        FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
                        mMessagesDatabaseReference.push().setValue(friendlyMessage);
                    }                         
                 }
            });
    }

This code will work but it will create a two images in the Firebase Storage, because when you call the

    photoRef.putFile(selectedImageUri);
    mChatPhotosStorageReference.putFile(selectedImageUri)......

You once uploaded the file in the chat_photos folder and 2nd one outside the chat_photos folder i.e. the root folder.

Instead You should do this...

        photoRef.putFile(selectedImageUri).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();
                }

                // Continue with the task to get the download URL
                return photoRef.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    FriendlyMessage friendlyMessage = new FriendlyMessage(null,
                            mUsername, downloadUri.toString());
                    mMessageDatabaseReference.push().setValue(friendlyMessage);
                } else {
                    // Handle failures
                    // ...
                }
            }
        });

sagittarius-saq avatar May 30 '20 10:05 sagittarius-saq

photo uploaded in firebase storage but not visible in app UI

nikhilsutar123 avatar Jul 14 '20 04:07 nikhilsutar123

شباب هذة الكود الصحيح والكامل سبب الخطأ هو 1- تم تحديث الاكواد لأن اكواد هذة الدرس قديمة 2- يجب ان تكون الاقواس منفصلة عن اقواس الدرس السابق لمصادقة تسجيل الدخول اتمنى ان يعمل معكم الكود

@Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { if (resultCode == RESULT_OK) { Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "Sign in cancelled", Toast.LENGTH_SHORT).show(); finish(); } } if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) { Uri selectedImageUri = data.getData();

        // Get a reference to store file at chat_photos/<FILENAME>
        final StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
        photoRef.putFile(selectedImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(MainActivity.this, "Upload Image", Toast.LENGTH_SHORT).show();
                photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, uri.toString());
                        mMessagesDatabaseReference.push().setValue(friendlyMessage);
                        Toast.makeText(MainActivity.this, "Photo Uploaded and URL is : " + uri.toString(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}

wissam-MA avatar Sep 05 '20 21:09 wissam-MA

لا تنسو بوضع صلاحيات 1- الوصول الى الانترنت 2- القراءة من Firebase Storage 3-الكتابة في Firebase Storage

توضع في ملف ال manifest
بين ال package وال application

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

wissam-MA avatar Sep 05 '20 22:09 wissam-MA

Hey guys, according with the documentation:

else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {

        Uri selectImageUri = data.getData();
        final StorageReference photoReference = mChatPhotoStorageReference.
                child(selectImageUri.getLastPathSegment());

        UploadTask uploadTask = photoReference.putFile(selectImageUri);
        Task<Uri> uriTask = uploadTask.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();
                }

                // Continue with the task to get the download URL
                return photoReference.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
                    mMessageDatabaseReference.push().setValue(friendlyMessage);
                }
            }
        });

gibranportillo avatar Nov 02 '20 01:11 gibranportillo

i have found the solution my code was also not working because the main issue is that all of our logic was surrounded by the if(requestCode == RC_SIGN_IN) block in the start of the onActivityResult method

shakoorsherani avatar Nov 21 '20 18:11 shakoorsherani

and if u want to ur ui to get updated instantly and if your image get uploaded to the firebase storage and the ui does not get update comment out the code in the onpause and you will be good to go

shakoorsherani avatar Nov 21 '20 19:11 shakoorsherani

and if u want to ur ui to get updated instantly and if your image get uploaded to the firebase storage and the ui does not get update comment out the code in the onpause and you will be good to go

i tried it but it not upload in my firebase nor show in app

ghost avatar Dec 17 '20 10:12 ghost

I tried all the code up here but none of them is working and I am unable to upload the image to storage and display it in chat as well.

rohan09-raj avatar May 30 '21 07:05 rohan09-raj

package com.google.firebase.udacity.friendlychat;

import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast;

import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity;

import com.firebase.ui.auth.AuthUI; import com.google.android.gms.tasks.Continuation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; 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.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask;

import java.util.ArrayList; import java.util.Arrays; import java.util.List;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

public static final String ANONYMOUS = "anonymous";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;

private static final int RC_SIGN_IN = 1;
private static final int RC_PHOTO_PICKER =  2;

private ListView mMessageListView;
private MessageAdapter mMessageAdapter;
private ProgressBar mProgressBar;
private ImageButton mPhotoPickerButton;
private EditText mMessageEditText;
private Button mSendButton;

private String mUsername;

private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosStorageReference;
private ChildEventListener mChildEventListener;

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

    mUsername = ANONYMOUS;

    mFirebaseDatabase = FirebaseDatabase.getInstance();
    mFirebaseAuth = FirebaseAuth.getInstance();
    mFirebaseStorage = FirebaseStorage.getInstance();

    mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");
    mChatPhotosStorageReference = mFirebaseStorage.getReference().child("photos");

    // Initialize references to views
    mProgressBar = findViewById(R.id.progressBar);
    mMessageListView = findViewById(R.id.messageListView);
    mPhotoPickerButton = findViewById(R.id.photoPickerButton);
    mMessageEditText = findViewById(R.id.messageEditText);
    mSendButton = findViewById(R.id.sendButton);

    // Initialize message ListView and its adapter
    List<FriendlyMessage> friendlyMessages = new ArrayList<>();
    mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
    mMessageListView.setAdapter(mMessageAdapter);

    // Initialize progress bar
    mProgressBar.setVisibility(ProgressBar.INVISIBLE);

    // ImagePickerButton shows an image picker to upload a image for a message
    mPhotoPickerButton.setOnClickListener(view -> {
        // TODO: Fire an intent to show an image picker
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/jpeg");
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
        startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
    });

    // Enable Send button when there's text to send
    mMessageEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.toString().trim().length() > 0) {
                mSendButton.setEnabled(true);
            } else {
                mSendButton.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });
    mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});

    // Send button sends a message and clears the EditText
    mSendButton.setOnClickListener(view -> {
        // TODO: Send messages on click
        FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
        mMessagesDatabaseReference.push().setValue(friendlyMessage);
        // Clear input box
        mMessageEditText.setText("");
    });

    mAuthStateListener = firebaseAuth -> {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            onSignedInInitialize(user.getDisplayName());
        } else {
            onSignedOutCleanup();
            startActivityForResult(
                    AuthUI.getInstance()
                            .createSignInIntentBuilder()
                            .setIsSmartLockEnabled(false)
                            .setAvailableProviders(Arrays.asList(
                                    new AuthUI.IdpConfig.EmailBuilder().build(),
                                    new AuthUI.IdpConfig.GoogleBuilder().build()))
                            .build(),
                    RC_SIGN_IN);
        }
    };
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        if (resultCode == RESULT_OK) {
            // Sign-in succeeded, set up the UI
            Toast.makeText(this, "Signed In!", Toast.LENGTH_SHORT).show();
        } else if (resultCode == RESULT_CANCELED) {
            // Sign in was canceled by the user, finish the activity
            Toast.makeText(this, "Sign In Cancelled!", Toast.LENGTH_SHORT).show();
            finish();
        } else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();

            // Get a reference to store file at chat_photos/<FILENAME>
            StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());

            // Upload file to Firebase Storage
            photoRef.putFile(selectedImageUri);
            mChatPhotosStorageReference.putFile(selectedImageUri).continueWithTask(task -> {
                if (!task.isSuccessful()) {
                    throw task.getException();
                }
                return mChatPhotosStorageReference.getDownloadUrl();
            }).addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUri.toString());
                    mMessagesDatabaseReference.push().setValue(friendlyMessage);
                }
            });
        }
    }
}

@Override
protected void onResume() {
    super.onResume();
    mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}

@Override
protected void onPause() {
    super.onPause();
    if (mAuthStateListener != null) {
        mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
    }
    mMessageAdapter.clear();
    detachDatabaseReadListener();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    final int signOutMenu = R.id.sign_out_menu;
    if (item.getItemId() == signOutMenu) {
        AuthUI.getInstance().signOut(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void onSignedInInitialize(String username) {
    mUsername = username;
    attachDatabaseReadListener();
}

public void onSignedOutCleanup() {
    mUsername = ANONYMOUS;
    mMessageAdapter.clear();
    detachDatabaseReadListener();
}

private void attachDatabaseReadListener() {
    if (mChildEventListener == null) {
        mChildEventListener = new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, String previousChildName) {
                FriendlyMessage friendlyMessage = snapshot.getValue(FriendlyMessage.class);
                mMessageAdapter.add(friendlyMessage);
            }
            @Override
            public void onChildChanged(@NonNull DataSnapshot snapshot, String previousChildName) { }
            @Override
            public void onChildRemoved(@NonNull DataSnapshot snapshot) { }
            @Override
            public void onChildMoved(@NonNull DataSnapshot snapshot, String previousChildName) { }
            @Override
            public void onCancelled(@NonNull DatabaseError error) { }
        };
        mMessagesDatabaseReference.addChildEventListener(mChildEventListener);
    }
}

private void detachDatabaseReadListener() {
    if (mChildEventListener != null) {
        mMessagesDatabaseReference.removeEventListener(mChildEventListener);
        mChildEventListener = null;
    }
}

}

rohan09-raj avatar May 30 '21 07:05 rohan09-raj

this is my code please help.

rohan09-raj avatar May 30 '21 07:05 rohan09-raj