skip to Main Content

Having issues uploading the name and URL into the Firebase Realtime Database. I am able to upload the images into Firebase Storage and everything else is working as intended. Really need the URL and metadata to move to the next phase of my project. Can someone please help me?

Attached are my codes below:

package com.example.x_raydetect;

import static android.content.ContentValues.TAG;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AlertDialogLayout;

import com.google.android.gms.tasks.OnCanceledListener;
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.android.gms.tasks.Tasks;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;

public class InsDB extends AppCompatActivity {

    private Button mainPage, btnView, btnMed, btnGallery, btnInsert, btnCamera;
    private EditText name;
    private ImageView insertImageView;
    private ProgressBar progressBar;
    public Uri imageUri;
    Bitmap bitmap;

    private StorageReference StorageRef;
    private DatabaseReference DatabaseRef;

    private StorageTask UploadTask;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ins_database);

        //menu tabs
        mainPage = findViewById(R.id.mainPage);
        btnView = findViewById(R.id.btnView);
        btnMed = findViewById(R.id.btnMed);
        //interface buttons/GUY
        btnCamera = findViewById(R.id.btnCamera);
        btnGallery = findViewById(R.id.btnGallery);
        btnInsert = findViewById(R.id.btnInsert);
        insertImageView = findViewById(R.id.insert_ImageView);
        name = findViewById(R.id.name);
        progressBar = findViewById(R.id.progressBar);

        StorageRef = FirebaseStorage.getInstance().getReference("uploads");
        DatabaseRef = FirebaseDatabase.getInstance("https://x-ray-detect-default-rtdb.asia-southeast1.firebasedatabase.app/").getReference("uploads");


        mainPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openMainPage();
            }
        });

        btnView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openViewDB();
            }
        });

        btnMed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        btnGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGalleryChooser();
            }
        });

        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, 12);
            }
        });

        btnInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UploadTask != null && UploadTask.isInProgress()) {
                    Toast.makeText(InsDB.this, "Upload in progress", Toast.LENGTH_SHORT).show();
                } else {
                    insertFile();
                }

            }
        });
    }

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

    private String getFileExtension(Uri uri) {
        ContentResolver cR = getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return mime.getExtensionFromMimeType(cR.getType(uri));
    }

    private void insertFile() {
        if (imageUri != null) {
            StorageReference fileReference = StorageRef.child(System.currentTimeMillis()
                    + "." + getFileExtension(imageUri));

            UploadTask = fileReference.putFile(imageUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    progressBar.setProgress(0);
                                }
                            }, 500);

                            Toast.makeText(InsDB.this, "Upload successful", Toast.LENGTH_LONG).show();
                            /*
                            Upload upload = new Upload(name.getText().toString().trim(),
                                    taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
                            String uploadId = DatabaseRef.push().getKey();
                            DatabaseRef.child(uploadId).setValue(upload);
                            */

                            Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
                            while (!urlTask.isSuccessful());
                            Uri downloadUrl = urlTask.getResult();

                            //Log.d(TAG, "onSuccess: firebase download url: " + downloadUrl.toString()); //use if testing...don't need this line.
                            Upload upload = new Upload(name.getText().toString().trim(),downloadUrl.toString());

                            String uploadId = DatabaseRef.push().getKey();
                            DatabaseRef.child(uploadId).setValue(upload)
                                    //ADDED NEW LISTENERS//
                                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void unused) {
                                            new AlertDialog.Builder(InsDB.this).setTitle("Success")
                                                    .setMessage(uploadId + name.getText().toString().trim() + downloadUrl.toString())
                                                    .setCancelable(true)
                                                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            finish();
                                                        }
                                                    })
                                                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.cancel();
                                                        }
                                                    })
                                                    .show();
                                        }
                                    })
                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            new AlertDialog.Builder(InsDB.this).setTitle("Failed")
                                                    .setMessage(uploadId + name.getText().toString().trim() + downloadUrl.toString())
                                                    .setCancelable(true)
                                                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            finish();
                                                        }
                                                    })
                                                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.cancel();
                                                        }
                                                    })
                                                    .show();
                                        }
                                    })
                                    .addOnCanceledListener(new OnCanceledListener() {
                                        @Override
                                        public void onCanceled() {
                                            new AlertDialog.Builder(InsDB.this)
                                                    .setTitle("Cancelled")
                                                    .setMessage(uploadId + name.getText().toString().trim() + downloadUrl.toString())
                                                    .setCancelable(true)
                                                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            finish();
                                                        }
                                                    })
                                                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.cancel();
                                                        }
                                                    })
                                                    .show();
                                        }
                                    })
                                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            new AlertDialog.Builder(InsDB.this)
                                                    .setTitle("Complete")
                                                    .setMessage(uploadId + name.getText().toString().trim() + downloadUrl.toString())
                                                    .setCancelable(true)
                                                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            finish();
                                                        }
                                                    })
                                                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.cancel();
                                                        }
                                                    })
                                                    .show();
                                        }
                                    });
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(InsDB.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot snapshot) {
                            double progress = (100.0 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
                            progressBar.setProgress((int) progress);
                        }
                    });
        } else {
            Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
        }

    }

    public void openMainPage() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    public void openViewDB() {
        Intent intent = new Intent(this, ViewDB.class);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10 && data != null) {
            imageUri = data.getData();
            Picasso.with(this).load(imageUri).into(insertImageView);
        } else if (requestCode == 12) {
            if (data != null) {
                bitmap = (Bitmap) data.getExtras().get("data");
                insertImageView.setImageBitmap(bitmap);
            }

        }
    }
}

I have read other posts on similar issue and follow their methods but it is still not working. Dependencies are correct and SHA-1/SHA-256 inserted into Firebase console. updated json report pasted in.

Thanks in advance for helping me!

2

Answers


  1. Chosen as BEST ANSWER
    btnMed.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v) {
                    String uploadId = DatabaseRef.push().getKey();
                    DatabaseRef.child(uploadId).setValue("test3").addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void unused) {
                            Toast.makeText(InsDB.this, "Success", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(InsDB.this, "Failure", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            Toast.makeText(InsDB.this, "Complete", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnCanceledListener(new OnCanceledListener() {
                        @Override
                        public void onCanceled() {
                            Toast.makeText(InsDB.this, "Cancelled", Toast.LENGTH_SHORT).show();
                        }
                    });
                    new AlertDialog.Builder(InsDB.this).setMessage("Clicked").show();
                }
            });
    

    I used this to test for response, however only the AlertDialog came out.


  2. The problem seems to be when using the following line of code:

    while (!urlTask.isSuccessful());
    

    If you add a semicolon at the end of the line, the while loop isn’t executed. Besides that, a while loop without a body isn’t helpful at all. So to solve this, you either use a while like this:

    while (!urlTask.isSuccessful()) {
        //Your logic
    }
    

    But in my opinion it makes more sense to use an if statement:

    if(!urlTask.isSuccessful()) {
        //Your logic
    } else {
        //Your logic
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search