C
C
Chesterfield252021-10-10 01:08:02
Java
Chesterfield25, 2021-10-10 01:08:02

Why couldn't get the FirebaseDatabase instance?

Why couldn't get the FirebaseDatabase instance and how to fix it?
There is a registration form after entering data when you click on the register button, the application crashes with this error

com.google.firebase.database.DatabaseException: Failed to get FirebaseDatabase instance: Specify DatabaseURL within FirebaseApp or from your getInstance() call.
        at com.google.firebase.database.FirebaseDatabase.getInstance(FirebaseDatabase.java:97)
        at com.google.firebase.database.FirebaseDatabase.getInstance(FirebaseDatabase.java:57)
        at com.buratinoapps.freelitecoinfaucet.RegisterActivity.queryAccountExistence(RegisterActivity.java:174)
        at com.buratinoapps.freelitecoinfaucet.RegisterActivity.access$400(RegisterActivity.java:36)
        at com.buratinoapps.freelitecoinfaucet.RegisterActivity$2.onClick(RegisterActivity.java:116)
        at android.view.View.performClick(View.java:8160)
        at android.widget.TextView.performClick(TextView.java:16222)
        at android.view.View.performClickInternal(View.java:8137)
        at android.view.View.access$3700(View.java:888)
        at android.view.View$PerformClick.run(View.java:30236)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8528)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)


uyfPc.png

CodeRegisterActivity

public class RegisterActivity extends AppCompatActivity {

    private Button registerBtn;
    private EditText nameEdit, emailEdit, passwordEdit, confirmPasswordEdit;
    private ProgressBar progressBar;
    private TextView loginTV;
    private FirebaseAuth auth;
    private String deviceID;

    @SuppressLint("HardwareIds")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        auth = FirebaseAuth.getInstance();

        deviceID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

        init();

        clickListener();


    }

    private void init() {

        registerBtn = findViewById(R.id.registerBtn);
        nameEdit = findViewById(R.id.nameET);
        emailEdit = findViewById(R.id.emailET);
        passwordEdit = findViewById(R.id.passwordET);
        confirmPasswordEdit = findViewById(R.id.confirmPass);
        progressBar = findViewById(R.id.progressBar);
        loginTV = findViewById(R.id.login_tv);

    }

    private void clickListener() {

        loginTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        });

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

                String name = nameEdit.getText().toString();
                String email = emailEdit.getText().toString();
                String pass = passwordEdit.getText().toString();
                String confirmPass = confirmPasswordEdit.getText().toString();

                if (name.isEmpty()) {
                    nameEdit.setError("Required");
                    return;
                }

                if (email.isEmpty()) {
                    emailEdit.setError("Required");
                    return;
                }

                if (pass.isEmpty()) {
                    passwordEdit.setError("Required");
                    return;
                }

                if (confirmPass.isEmpty() || !pass.equals(confirmPass)) {
                    confirmPasswordEdit.setError("Invalid Password");
                    return;
                }



                queryAccountExistence(email, pass);

            }
        });

    }

    private void createAccount(final String email, String password) {

        progressBar.setVisibility(View.VISIBLE);

        auth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        if (task.isSuccessful()) {

                            //Registration success:
                            final FirebaseUser user = auth.getCurrentUser();
                            assert user != null;


                            //send email verification link
                            auth.getCurrentUser().sendEmailVerification()
                                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {

                                            if (task.isSuccessful()) {

                                                updateUi(user, email);

                                            } else {
                                                Toast.makeText(RegisterActivity.this, "Error: "
                                                                + task.getException().getMessage(),
                                                        Toast.LENGTH_SHORT).show();
                                            }

                                        }
                                    });

                        } else {

                            progressBar.setVisibility(View.GONE);
                            //Registration failed:
                            Toast.makeText(RegisterActivity.this, "Error: " +
                                    task.getException().getMessage(), Toast.LENGTH_SHORT).show();

                        }

                    }
                });

    }

    private void queryAccountExistence(final String email,final String pass) {

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");

        Query query = ref.orderByChild("deviceID").equalTo(deviceID);

        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                if (snapshot.exists()) {
                    //device already registered
                    Toast.makeText(RegisterActivity.this,
                            "This device is already registered on another email, please login",
                            Toast.LENGTH_SHORT).show();

                } else {
                    //device id not found
                    createAccount(email, pass);

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

    }

    private void updateUi(FirebaseUser user, String email) {

        String refer = email.substring(0, email.lastIndexOf("@"));
        String referCode = refer.replace(".", "");

        //identify that this user already sign up

        HashMap<String, Object> map = new HashMap<>();
        map.put("name", nameEdit.getText().toString());
        map.put("email", email);
        map.put("uid", user.getUid());
        map.put("image", " ");
        map.put("coins", 0);
        map.put("referCode", referCode);
        map.put("spins", 2);
        map.put("deviceID", deviceID);
        map.put("redeemed", false);

        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1); // to get yesterday date
        Date previousDate = calendar.getTime();

        String dateString = dateFormat.format(previousDate);

        FirebaseDatabase.getInstance().getReference().child("Daily Check")
                .child(user.getUid())
                .child("date")
                .setValue(dateString);

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Users");

        reference.child(user.getUid())
                .setValue(map)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {

                        if (task.isSuccessful()) {

                            Toast.makeText(RegisterActivity.this, "Registered, Please verify email",
                                    Toast.LENGTH_SHORT).show();

                            startActivity(new Intent(RegisterActivity.this, LoginActivity.class));

                            finish();

                        } else {
                            Toast.makeText(RegisterActivity.this, "Error: " +
                                            task.getException().getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }

                        progressBar.setVisibility(View.GONE);

                    }
                });


    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-10-10
Hasanly @azerphoenix

Good afternoon.
First, the answer is easily found by a search engine.
Secondly, the reason for the error is also written there:

Failed to get FirebaseDatabase instance: Specify DatabaseURL within FirebaseApp or from your getInstance() call.

For example:
https://stackoverflow.com/questions/47730910/faile...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question