Firebase Storage image upload - android

I am using the following method to save information.
private void saveUserData() {
progressDialog.setTitle("Account Settings");
progressDialog.setMessage("Please wait while settings are being changed...");
progressDialog.show();
final StorageReference imageRef = storageReference
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
imageRef.putFile(imageUri);
}
I have removed some lines of code for accessing the database.
This the log cat description.
E/StorageException: StorageException has occurred.
An unknown error occurred, please check the HTTP result code and inner exception for server response.
Code: -13000 HttpResult: 0
E/AndroidRuntime: FATAL EXCEPTION: FirebaseStorage-Upload-1
I seached this error code and found
case unknown = -13000
The app doesn't crash when I comment this line.
imageRef.putFile(imageUri);
On a side note, I am able to save text info successfully and even retrieve it from the database.
EDIT
Here is the code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
storageReference = FirebaseStorage.getInstance()
.getReference().child("Profile Pictures");
profileImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, galleryPick);
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveUserData();
}
});
retrieveUserInformation();
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == galleryPick && resultCode == RESULT_OK && data != null) {
imageUri = data.getData();
profileImageView.setImageURI(imageUri);
}
}

Given the variable name imageUri, you're trying to upload to Storage from a URL, which is not supported. You'll first have to download the data from the URL, and then upload it to Storage.

Related

How to upload image on firebase without button android studio

How to upload the image without "upload" button and to use that new image automatically as default user picture? How can I implement this in my code.
mAuth = FirebaseAuth.getInstance();
circlePic = findViewById(R.id.circleImageView);
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
Glide.with(this)
.load(user.getPhotoUrl())
.into(circlePic);
public void Profile(View view) {
Intent cpicview = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(cpicview, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageRIntent) {
super.onActivityResult(requestCode, resultCode, imageRIntent);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK)
mProfileUri = imageRIntent.getData();
Uri selectedImage = imageRIntent.getData();
this.circlePic.setImageURI(selectedImage);
first add click listener to your imageview that will open activity to choose an image
profileImage.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Profile Image"), REQUEST_CODE);
}
});
then implement onActivityResult that will be executed when image is selected
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE) {
InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
uploadImage(bitmap);
}
}
this is the method to upload Bitmap
private void uploadImage(Bitmap bitmap)
{
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("Your url for storage");
StorageReference mountainImagesRef = storageRef.child("images/" + chat_id + Utils.getCurrentTimeStamp() + ".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainImagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Log.d(downloadUrl);
}
});
}
and don't forget to declare REQUEST_CODE in your class
public static final int REQUEST_CODE = 1;
and maybe you will need to add this line in your xml for your profile image view
android:clickable="true"

Upload profile image for a user Firebase

I am trying to add an image to the user information in the real time database(firebase) for android. I have uploaded the image on the firebase storage but how will I be able to add the image in the database for that user?
Code Below:
//inside onCreate() method
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i,request_code);
}
});
Here I am clicking on the imageview, so I will be able to change it and get an image from the gallery.
Here I authenticate the user and send data to the database:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(StudentSignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(getApplicationContext(), "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(StudentSignUpActivity.this, HomeActivity.class));
finish();
}
}
});
mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference newStudent=mDatabase.push();
newStudent.child("email").setValue(email);
newStudent.child("password").setValue(password);
newStudent.child("name").setValue(name);
newStudent.child("date").setValue(dates);
newStudent.child("phone").setValue(number);
newStudent.child("uid").setValue(mCurrentUser.getUid());
//outside of onCreate()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request_code&&resultCode==RESULT_OK){
Uri uri=data.getData();
StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
}
In the above code I have uploaded the image to the firebase storage. Now how will i be able to add that image as a child for a specific user.
I think I need to do something like this:
newStudent.child("image").setValue(uri_here);
But I am unable to figure how to get the uri of the image and how to add that uri in the setValue() since its in another method.
You can use the method getDownloadUrl() in the success listener to access the download URL:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request_code&&resultCode==RESULT_OK){
Uri uri=data.getData();
StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
newStudent.child("image").setValue(downloadUrl);
}
});
}
}
As an aside, instead of using push(), I recommend storing the user's data with the uid as the key. This will make your data easier to find.
private DatabaseReference newStudent;
mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
newStudent=mDatabase.child(mCurrentUser.getUid());
newStudent.child("email").setValue(email);
// etc
Just to update because I spent sometime to find this answer, getDownloadUrl() is NOT a function of taskSnapshot anymore. So in order to get the image URL from Firebase Storage you need to add a listener to
taskSnapshot.getMetadata().getReference().getDownloadUrl()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==request_code&&resultCode==RESULT_OK){
Uri uri=data.getData();
StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getMetadata().getReference().getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
newStudent.child("image").setValue(uri);
}
});
}
});
}
}
Now it's safe to use uri to whatever you want

What causes my resultCode to return -1

I have this code to upload an image from the gallery or user can use their camera to take the picture, but the result code for the camera returns -1 and crashes, I honestly don't know why. Here is the code:
private Button mSelectImage;
private Button upload;
private ImageView mImage;
private StorageReference mStorage;
private static final int GALLERY_INTENT = 2;
private static final int CAMERA_REQUEST_CODE = 7;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mSelectImage = (Button) findViewById(R.id.selectImage);
upload = (Button) findViewById(R.id.captureUpload);
progressDialog = new ProgressDialog(this);
mImage = (ImageView) findViewById(R.id.image);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(i, GALLERY_INTENT);
}
});
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK)
{
progressDialog.setMessage("uploading...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filePath =
mStorage.child("Photos").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(MainActivity.this, "Image upload
successful",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
else if(requestCode == CAMERA_REQUEST_CODE && resultCode ==
RESULT_OK)
{
progressDialog.setMessage("uploading...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filePath =
mStorage.child("Photos").child(uri.getLastPathSegment());
filePath.putFile(uri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(MainActivity.this, "Image upload
successful",Toast.LENGTH_LONG).show();
progressDialog.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this)
.load(downloadUri).fit().centerCrop().into(mImage);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
}
It works when I upload from the gallery but returns a -1 request result on the camera, just after I take the camera. It doesn't even go to the download part, (with Picasso)
Your help would be appreciated very much!!!!
Best regards
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=7, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.user.uploadingimages/com.example.user.uploadingimages.MainActivity}: java.lang.IllegalArgumentException: uri cannot be null
Without a logcat i'd say it could be a permission issue:
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
If you post the logcat i can be more precise
EDIT:
The logcat clearly states the problem
java.lang.IllegalArgumentException: uri cannot be null
Did you properly check that this statements returns a not null value?
Uri uri = data.getData();
As per logs, data.getData() is returning null.
Supply EXTRA_OUTPUT in your ACTION_IMAGE_CAPTURE Intent, in which case you know where the image should be stored, and do not need to rely upon getData()
On click of camera button, use this code:
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(f));
startActivityForResult(intent,
CAMERA_REQUEST_CODE);
Refer: Android data.getData() returns null from CameraActivity for some phones

Not able to upload an Image in Firebase Storage

This is the my code ( check this file full code on GitHub) for Uploading an image to Firebase Storage.
// ImagePickerButton shows an image picker to upload a image for a message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(i, "Complete action using"), RC_PHOTO_PICKER);
}
});
This is the OnActivityResult Method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
//get the reference to stored file at database
StorageReference selectedImageFilePath = mStorageReference.child(selectedImageUri.getLastPathSegment());
//upload file to firebase
selectedImageFilePath.putFile(selectedImageUri).addOnSuccessListener(MainActivity.this, new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests")
String downloadUrl = taskSnapshot.getDownloadUrl().toString();
Message message = new Message(null, userName, downloadUrl);
messagesDatabaseReference.push().setValue(message);
}
});
}
}
}
Picking an Image from the Gallery works fine but I'm not able to upload the selected Image on Firebase Storage. Correct my code If I'm wrong at any site. However, I manually entered these lines in my manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I'm currently running the app in my own mobile device connected via USB( Moto G4 - Nougat)
data.getData() could return an URI that does not point to a File.
You should use
InputStream is = getContentResolver().openInputStream(data.getData())
and than use
selectedImageFilePath.putStream(is)
Also you could add an onFailureListener to the upload task and debug what is going wrong.
In addition, if I recall correctly, I do not think you need the storage permissions when you directly read the data in onActivityResult.
Try this for button click :
//Select Image functionality
btnselectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 2);
}
});
For saving image to fire base :
//Storing and getting image from firebase
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
final Uri uri = data.getData();
StorageReference filepath = mStorageRef.child("Photos").child(name);
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
//Getting url where image is stored
saveImage(downloadUri);
Picasso.with(getActivity()).load(downloadUri).fit().centerCrop().into(profileImage);
}
});
}
This works fine for me, Hope this will help.
Instead of else if statement, I modified it by writing a seperate if statement.
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
}else if (resultCode == RESULT_CANCELED) {
}
// This was the change I made
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
}
}
If ( //sign in)
{
If (//result ok)
{}
else if (//result cancel)
{}
}
else if (//rc photot picker && result ok)
{ //your storage code here.....}
tats works perfectly.....check out the braces carefully....

App crashes when trying to upload to Firebase

When I try to upload to Firebase my app is crashing with the following error.
I have an 'upload' button that is being used to invoke the camera. Upon clicking it, the image is not uploaded to Firebase.
My code:
private Button mUploadBtn;
private ImageView mImageView;
private static final int CAMERA_REQUEST_CODE = 1;
private StorageReference mStorage;
Uri photoURI;
private ProgressDialog mProgressDialog;
private static final int GALLERY_INTENT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mUploadBtn = (Button) findViewById(R.id.upload);
mImageView = (ImageView) findViewById(R.id.imageView);
mProgressDialog = new ProgressDialog(this);
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
mProgressDialog.setMessage("Uplaoding");
mProgressDialog.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child("file");
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this,"Done",Toast.LENGTH_LONG).show();
}
});
}
}
It looks like you're not working with the camera intent correctly. The code you show is expecting that the intent returned by the camera app contains a Uri to the captured image via its getData() method. That's not the way it works.
I recommend you follow this tutorial instead to work with the camera.
override this method
and do the following steps
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK)
{
Uri uri = data.getData();
StorageReference image_path = storageReference.child("Camera Photos").child(uri.getLastPathSegment());
image_path.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
}
});
}
}

Categories

Resources