0

I am quite new to Android Studio and also Java. The app that I currently developing is crashing when the user click on the "Logout". I have edited my code several times. I have no idea now. I hope can get someone who is genius in programming to help.

This is my code for the drawer_menu:

package com.example.sample_app;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.navigation.NavigationView;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class MainActivity  extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawer;

    private FirebaseUser user;
    private DatabaseReference reference;

    private String userID;

    private TextView EmailTxtView, UIDTxtView;

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

        // Initialize Firebase
        FirebaseApp.initializeApp(this);
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawer = findViewById(R.id.drawer_layout);

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);

        drawer.addDrawerListener(toggle);
        toggle.syncState();

        // Get the header view from the NavigationView
        View headerView = navigationView.getHeaderView(0);

        //Initialised the parameter for Firebase
        user = FirebaseAuth.getInstance().getCurrentUser();
        reference = FirebaseDatabase.getInstance().getReference("Users");
        userID = user.getUid();

        // Find the TextViews by their IDs
        EmailTxtView = headerView.findViewById(R.id.email_username);
        UIDTxtView = headerView.findViewById (R.id.uid);

        reference.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                User userProfile = snapshot.getValue(User.class);

                if (userProfile != null) {

                    String email = userProfile.email;
                    String UID = userProfile.username;

                    EmailTxtView.setText(email);
                    UIDTxtView.setText(UID);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.tracking) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new FragmentTracking()).commit();
        } else if (itemId == R.id.profile) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new FragmentProfile()).commit();
        } else if (itemId == R.id.settings) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new FragmentSetting()).commit();
        } else if (itemId == R.id.logout) {
            Intent intent = new Intent(MainActivity.this,LoginUser.class);
//            intent.putExtra("LOGOUT", true);
            startActivity(intent);
            finish();
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}

The image shows drawer with logout, when user click on it. the app crash.

and this is the error message.

E  FATAL EXCEPTION: main
Process: com.example.sample_app, PID: 18145
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sample_app/com.example.sample_app.LoginUser}: com.google.firebase.database.DatabaseException: Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: com.google.firebase.database.DatabaseException: Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance.
    at com.google.firebase.database.FirebaseDatabase.assertUnfrozen(FirebaseDatabase.java:332)
    at com.google.firebase.database.FirebaseDatabase.setPersistenceEnabled(FirebaseDatabase.java:285)
    at com.example.sample_app.LoginUser.onCreate(LoginUser.java:37)
    at android.app.Activity.performCreate(Activity.java:7009)
    at android.app.Activity.performCreate(Activity.java:7000)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
    at android.app.ActivityThread.-wrap11(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
    at android.os.Handler.dispatchMessage(Handler.java:106) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6494) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

The other selection of fragment is working well only when the user starts to press on the Logout then the app crash

I have also try with the "startActivity(new Intent())" method but still the same.

Thank you, for your effort is much appreciated. If you wish to have more details about the error, just let me know

I have tried this:

public class MyApp extends Application {
    
    @Override
    public void onCreate() {
        super.onCreate();
        
        // Enable Firebase database persistence
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    }
}

//I have set this in my login screen

This is because the error message did mention about the setPersistenceEnabled() Should I remove that or any other measures?

  • In your `MainActivity`, did you try moving `FirebaseDatabase.getInstance().setPersistenceEnabled(true);` before `FirebaseApp.initializeApp(this);`? – dan1st Mar 26 '23 at 17:17
  • Thanks, but it is still the same error. I believe something wrong with the startActivity(). I have tried including and excluding the startActivity(); when including, the app crash but when excluding the startActivity, it run well as the app will go through logout only just not bringing user back to the Login activity. For example, when I place the Toast.makeText() in it and remove the startActivity(), the code has been executed well. – Voon Kok Wei Mar 27 '23 at 00:02
  • @dan1st thanks I found the way to do so. [link]https://stackoverflow.com/questions/37753991/com-google-firebase-database-databaseexception-calls-to-setpersistenceenabled. I thought it is the startActivity() as I exclude it, the entire code works well, then i to try rearrange the class see whether or not I have the application class in it, eventually found that class isn't there. – Voon Kok Wei Mar 27 '23 at 01:27

0 Answers0