Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Store photo in Firebase Storage. #42

Open
wants to merge 1 commit into
base: 2.01-firebase-storage-photo-picker-intent
Choose a base branch
from

Conversation

swdevdave
Copy link

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);
                    }                         
                 }
            });
    }

@RRGT19
Copy link

RRGT19 commented Jul 7, 2018

@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

@ibnahmadbello
Copy link

@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
Copy link

@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.

@carlosughini
Copy link

carlosughini commented Oct 16, 2018

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);
                }
            });
        }

@faisalmushtaq007
Copy link

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

@prashantk01
Copy link

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 ??

@harisvm
Copy link

harisvm commented Dec 16, 2019

not working !!

@5AbhishekSaxena
Copy link

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();
                                        }
                                    });
                                }
                            });

@sagittarius-saq
Copy link

sagittarius-saq commented May 30, 2020

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
                    // ...
                }
            }
        });

@nikhilsutar123
Copy link

photo uploaded in firebase storage but not visible in app UI

@wissam-MA
Copy link

شباب هذة الكود الصحيح والكامل
سبب الخطأ هو
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
Copy link

لا تنسو بوضع صلاحيات
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" />

@gibranportillo
Copy link

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);
                }
            }
        });

@shakoorsherani
Copy link

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
Copy link

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

@ghost
Copy link

ghost commented Dec 17, 2020

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

@rohan09-raj
Copy link

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
Copy link

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
Copy link

rohan09-raj commented May 30, 2021

this is my code
please help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.