Статус администратора обновляется, когда я сворачиваю и возобновляю приложение - PullRequest
0 голосов
/ 29 марта 2020

Сначала внутри метода onCreate () , getAdminInfo () метод возвращает значение false, где он должен возвращать значение true. Но при сворачивании и возобновлении данные приложения обновляются и работают так, как и предполагалось.

getAdminInfo () метод извлекает данные из firebase и сохраняет их в объекте Volunteer. Когда я вхожу в систему, он открывает MainActivity , где он должен открыться Main2Activity . Я создал определенные условия внутри onCreate () , используя if-else, чтобы проверить, является ли пользователь, вошедший в систему в данный момент, администратором или нет.

MainActivity. java

public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private DatabaseReference dbRef;
private FirebaseUser currentUser;
private String uid;
private Volunteer newVolunteer = new Volunteer();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //checking if current user is logged in
    mAuth = FirebaseAuth.getInstance();
    currentUser = mAuth.getCurrentUser();
    //setting path to node Volunteer
    dbRef = FirebaseDatabase.getInstance().getReference("Volunteer");
    if(currentUser == null){
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
    //checking if current user is admin
    else if(getAdminInfo()){
            Toast.makeText(this,"Welcome! " + newVolunteer.getFullName() , Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, Main2Activity.class);
            startActivity(intent);
            finish();
    }
    //if not admin set default user layout
    else{
        setContentView(R.layout.activity_main);
        Log.d("bug", "I am the bug");
        Toast.makeText(this,"Welcome! " + newVolunteer.getFullName() , Toast.LENGTH_SHORT).show();
    }
}

public boolean getAdminInfo(){
    uid= mAuth.getCurrentUser().getUid();
    Log.d("crash", uid);
    dbRef.child(uid).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String fullName = (String) dataSnapshot.child("fullName").getValue();
            String email = (String) dataSnapshot.child("email").getValue();
            String gender = (String) dataSnapshot.child("gender").getValue();
            final Boolean admin = (Boolean) dataSnapshot.child("admin").getValue();
            try {
                newVolunteer.setAdmin(admin);
                newVolunteer.setEmail(email);
                newVolunteer.setGender(gender);
                newVolunteer.setFullName(fullName);
            }catch (Exception e){
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.d("db", databaseError.getDetails());
        }
    });
    Log.d("dbcheck", "admin status inside getAdminInfo 2 " + newVolunteer.isAdmin());
    Log.d("dbcheck", "name inside getAdminInfo " + newVolunteer.getFullName());
    return newVolunteer.isAdmin();
}

@Override
protected void onStart() {
    super.onStart();
    //Check if user is already signed in
    currentUser = mAuth.getCurrentUser();
    if(getAdminInfo()){
        Log.d("dbcheck", "Admin Activity Launched from onStart");
        Intent intent = new Intent(this, Main2Activity.class);
        startActivity(intent);
        finish();
        Log.d("dbcheck", "admin status onStart " + getAdminInfo());
        uid= mAuth.getCurrentUser().getUid();
        Toast.makeText(this,"Welcome Back! " + newVolunteer.getFullName() , Toast.LENGTH_SHORT).show();
    }

}

}

Волонтер. java

public class Volunteer {
private String fullName;
private String email;
private String gender;
private boolean admin;

boolean isAdmin() {
    return admin;
}

void setAdmin(boolean admin) {
    this.admin = admin;
}

String getFullName() {
    return fullName;
}

void setFullName(String fullName) {
    this.fullName = fullName;
}

public String getEmail() {
    return email;
}

void setEmail(String email) {
    this.email = email;
}

public String getGender() {
    return gender;
}

void setGender(String gender) {
    this.gender = gender;
}

Volunteer(){
    FirebaseAuth mAuth = FirebaseAuth.getInstance();
    FirebaseUser currentUser = mAuth.getCurrentUser();
    DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Volunteer");
}

Volunteer(String fullName, String email, String gender, Boolean admin) {
    this.fullName = fullName;
    this.email = email;
    this.gender = gender;
    this.admin = false;
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...