App crashes when trying to upload to Firebase - android

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

Related

Parsing Uri with CircleImageView

How do I Parse uri with de.hdodenhof.circleimageview.CircleImageView?
My code
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
final Uri uri = data.getData();
StorageReference path = mStoragereference.child("Photos").child(uri.getLastPathSegment());
path.putFile(uri).addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setPhotoUri(Uri.parse(userPhoto))
.build();
if (userPhoto == null) {
Toast.makeText(EditInfo.this, "Error updating image",
Toast.LENGTH_SHORT).show();
}
Thanks for your response!
Since CircleImageView is a subclass of ImageView it inherits most of its properties/methods from ImageView.
Unfortunately it seems that ImageView doesn't expose its source URI, so you'll have to keep the URI that you pass into the CircleImageView around.

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"

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

Image is failed to upload in Firebase storage

Can you please help me, I am trying to upload an image in FirebaseStorage.
But it fails.
My Button click Method
public void uploadImage(View view){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,GALLERY_INTENT);
}
And here is onActivityResult()
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
progressDialog.setMessage("Uploading");
progressDialog.show();
if(requestCode ==GALLERY_INTENT){
final Uri uri = data.getData();
StorageReference filepath = storageReference.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),"Uploaded Successfully",Toast.LENGTH_LONG).show();
// profileImage.setImageURI(uri);
progressDialog.dismiss();
}
});
}
}
What's wrong with this code?
Try this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("resultCode: ", resultCode + " RequestCode: " + requestCode);
if (resultCode == getActivity().RESULT_OK) {
sendImageToFireBase(data.getData());
}
}
private void saveImageToFireBase(Uri pathUri) {
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Photos");
StorageReference photoRef = storageReference.child(pathUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(pathUri).addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
}
});
}

Taking a Picture With Camera and Viewing in Image View

I don't know why my code which was just working and has suddenly stopped? I want to take a picture through my image button, and then display it in an Image View. Here`s my code that won't display in the Image View:
public class UserInterface extends AppCompatActivity {
private static final int REQUEST_IMAGE_CAPTURE= 1;
private ImageView imageView;
ImageButton cap;
Bundle extras;
Bitmap imageBitmap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_interface);
imageView = (ImageView)this.findViewById(R.id.imageView1);
cap = (ImageButton) this.findViewById(R.id.cap);
cap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
}
Uri imageUri;
On your button click listener:
cap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
});
On activity result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
imageView.setImageURI(imageUri);
}
}

Categories

Resources