1

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();
            }
        }
    }
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Fratsie
  • 11
  • 2
  • 1
    When an app crashes, it writes an error message and stack trace to its logcat. Please find those, and add them to your question by clicking the `edit` link under it. Also see https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this and https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – Frank van Puffelen Aug 26 '23 at 14:08
  • oke i've done it – Fratsie Aug 26 '23 at 14:44
  • Okay i've fixed it so that the image uploads to firebase but i still get this error any ideas? – Fratsie Aug 27 '23 at 09:15
  • I've located the problem. Everything works fine but if i upload more than 1 image the email gives the error – Fratsie Aug 27 '23 at 09:35

1 Answers1

0

Dear User First you check Internet permission in manifests

Try this way to adding images to firebase storage

private void SelectImage() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, 100);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 100 && resultCode == RESULT_OK && 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 imageName = UUID.randomUUID().toString();
        StorageReference imageRef = storageReference.child("images/").child(imageName);

        // You can use getInstance() without specifying the database URL if it's already configured in your project.
        FirebaseDatabase database = FirebaseDatabase.getInstance();

        DatabaseReference myRef = database.getReference();

        EditText descriptionEditText = findViewById(R.id.EtDescription);
        String description = descriptionEditText.getText().toString().trim();

        if (!description.isEmpty()) {
            String email = Profile.GetEmail.Email;
            myRef.child(imageName).child("Description").setValue(description);
            myRef.child(imageName).child("Email").setValue(email.replace(".", ";"));

            // Upload the image
            imageRef.putFile(filePath)
                .addOnSuccessListener(taskSnapshot -> {
                    Toast.makeText(getApplicationContext(), "Image uploaded successfully", Toast.LENGTH_SHORT).show();
                    // Proceed to the home screen or another appropriate action
                    Intent goHome = new Intent(AddPosts.this, Home.class);
                    startActivity(goHome);
                })
                .addOnFailureListener(e -> {
                    Toast.makeText(getApplicationContext(), "Failed to upload image", Toast.LENGTH_SHORT).show();
                });
        } else {
            Toast.makeText(getApplicationContext(), "Please fill in the description", Toast.LENGTH_SHORT).show();
        }
    }
}