So i have a problem with uploading images to the firebase storage through android studio java. I can upload 1 image but as soon as i want to upload a second image the app crashes and it didn't work.I've looked into the code myself but i can't find the problem so i'm hoping one of you can.
So beneath you will find the code where in the "selectImage" void i select an image from the gallery of the phone and with that piece of code is nothing wrong. But as soon as i press the upload image button it crahses so the problem finds itself in the "uploadImage" void i think.
This is the error that appears after is crashes:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Here is the code:
private void SelectImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 100);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100 && data != null && data.getData() != null){
filePath = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
ImageView postImage = findViewById(R.id.IvPostImage);
postImage.setImageBitmap(bitmap);
}
catch (IOException e){
e.printStackTrace();
}
}
}
private void uploadImage() {
if(filePath != null){
String name = UUID.randomUUID().toString();
StorageReference ref = storageReference.child("images/").child(String.valueOf(name));
FirebaseDatabase database = FirebaseDatabase.getInstance("https://elevate-92324-default-rtdb.europe-west1.firebasedatabase.app/");
DatabaseReference myRef = database.getReference();
EditText Description = findViewById(R.id.EtDescription);
String description = Description.getText().toString();
ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "Image uploaded with success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to upload image", Toast.LENGTH_SHORT).show();
}
});
if(description != null){
String email = Profile.GetEmail.Email;
myRef.child(name).child("Description").setValue(description);
myRef.child(name).child("Email").setValue(email.replace(".", ";"));
Intent goHome = new Intent(AddPosts.this, Home.class);
startActivity(goHome);
}else{
Toast.makeText(getApplicationContext(), "Fill in the description", Toast.LENGTH_SHORT).show();
}
}
}