菜单未出现,并且列表视图不可单击

时间:2019-10-27 03:31:10

标签: android firebase-realtime-database android-recyclerview android-menu

感谢您的帮助。菜单未出现,并且在回收站视图中的列表视图不可单击。

这是菜单部分。

public class QuizListActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private FirebaseAuth mAuth;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz_list);
        mAuth = FirebaseAuth.getInstance();

    mRecyclerView = (RecyclerView)findViewById(R.id.recyclerBView);
    new FirebaseDatabaseHelper().readQuiz(new FirebaseDatabaseHelper.DataStatus() {
        @Override
        public void DataIsLoaded(List<Quiz> quizzes, List<String> keys) {
            new RecyclerConfig().setConfig(mRecyclerView, QuizListActivity.this, quizzes, keys);
        }

        @Override
        public void DataIsInserted() {

        }

        @Override
        public void DataIsUpdated() {

        }

        @Override
        public void DataIsDeleted() {

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    FirebaseUser user = mAuth.getCurrentUser();
    getMenuInflater().inflate(R.menu.quizlistmenu, menu);
    if(user!=null) {
        menu.getItem(0).setVisible(true);
        menu.getItem(1).setVisible(true);
        menu.getItem(2).setVisible(true);
    }

    return super.onCreateOptionsMenu(menu);
}

public boolean onPrepareOptionsMenu(Menu menu)
{FirebaseUser user = mAuth.getCurrentUser();
    if(user!=null) {
        menu.getItem(0).setVisible(true);
        menu.getItem(1).setVisible(true);
        menu.getItem(2).setVisible(true);
    }

    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId())
    {
        case R.id.new_book:
            startActivity(new Intent(this, NewQuestionActivity.class));
            return true;
        case R.id.user_approval:
            startActivity(new Intent(this, Approval.class));
            return true;
        case R.id.signout:
            mAuth.signOut();
            invalidateOptionsMenu();
            RecyclerConfig.logout();
            return true;
    }
    return super.onOptionsItemSelected(item);
}
}

这是菜单。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/new_book"
        android:title="New Question" />
    <item
        android:id="@+id/user_approval"
        android:title="Registered User" />
    <item
        android:id="@+id/signout"
        android:title="Sign Out" />
</menu>

这是回收站的一部分。

public class RecyclerConfig
{
    FirebaseAuth mAuth;
    private static FirebaseUser user;
    private Context mContext;
    private QuizAdapter mQuizAdapter;
    public void setConfig(RecyclerView mRecyclerView, Context context, List<Quiz> quizzes, List<String> keys)
    {
        mAuth = FirebaseAuth.getInstance();
        user = mAuth.getCurrentUser();
        mContext = context;
        mQuizAdapter = new QuizAdapter(quizzes, keys);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        mRecyclerView.setAdapter(mQuizAdapter);
    }
    class QuizItemView extends RecyclerView.ViewHolder
    {
        private TextView mquestion,mans1,mans2,mans3,mans4,mcorrect,mcategoryid;

    private String key;

    public QuizItemView(ViewGroup parent)
    {
        super(LayoutInflater.from(mContext)
                .inflate(R.layout.quizlistitem, parent, false));

        mquestion = (TextView) itemView.findViewById(R.id.questiontv);
        mans1 = (TextView) itemView.findViewById(R.id.ans1tv);
        mans2 = (TextView) itemView.findViewById(R.id.ans2tv);
        mans3 = (TextView) itemView.findViewById(R.id.ans3tv);
        mans4 = (TextView) itemView.findViewById(R.id.ans4tv);
        mcorrect = (TextView) itemView.findViewById(R.id.correcttv);
        mcategoryid = (TextView) itemView.findViewById(R.id.categorytv);

        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(user!=null) {
                    Intent intent = new Intent(mContext, QuizDetailActivity.class);
                    intent.putExtra("key", key);
                    intent.putExtra("question", mquestion.getText().toString());
                    intent.putExtra("answer1", mans1.getText().toString());
                    intent.putExtra("answer2", mans2.getText().toString());
                    intent.putExtra("answer3", mans3.getText().toString());
                    intent.putExtra("answer3", mans4.getText().toString());
                    intent.putExtra("answer3", mcorrect.getText().toString());
                    intent.putExtra("categoryid", mcategoryid.getText().toString());

                    mContext.startActivity(intent);
                }
                /*else
                {
                    mContext.startActivity(new Intent(mContext, SignInActivity.class));
                }*/

            }
        });
    }

    public void bind(Quiz quizzes, String key)
    {
        mquestion.setText(quizzes.getQuestion());
        mans1.setText(quizzes.getAnswer1());
        mans2.setText(quizzes.getAnswer2());
        mans3.setText(quizzes.getAnswer3());
        mans4.setText(quizzes.getAnswer4());
        mcorrect.setText(quizzes.getCorrect());
        mcategoryid.setText(quizzes.getCategoryid());
        this.key = key;
    }
}
class QuizAdapter extends RecyclerView.Adapter<QuizItemView>
{
    private List<Quiz> mQuizList;
    private List<String> mKeys;

    public QuizAdapter(List<Quiz> mQuizList, List<String> mKeys) {
        this.mQuizList = mQuizList;
        this.mKeys = mKeys;
    }

    @NonNull
    @Override
    public QuizItemView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new QuizItemView(parent);
    }

    @Override
    public void onBindViewHolder(@NonNull QuizItemView holder, int position) {
        holder.bind(mQuizList.get(position), mKeys.get(position));
    }

    @Override
    public int getItemCount() {
        return mQuizList.size();
    }
}

public static void logout()
{
    user = null;
}
}

这是登录/注册部分。

public class SignInActivity extends AppCompatActivity {
MaterialEditText edtNewEmail,edtNewPassword,edtnewName, edtnewAge, edtnewAddress, edtStatus; // for register
MaterialEditText edtEmail,edtPassword; //for Signin

Button btnRegister,btnSignIn;
FirebaseAuth mAuth;


FirebaseDatabase database;
DatabaseReference users;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_in);
    mAuth = FirebaseAuth.getInstance();

    //Firebase
    database = FirebaseDatabase.getInstance();
    users = database.getReference("User");

    edtEmail = (MaterialEditText)findViewById(R.id.edtEmail);
    edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);

    btnSignIn = (Button)findViewById(R.id.signInBtn);
    btnRegister = (Button)findViewById(R.id.regBtn);

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showSignUpDialog();
        }
    });

    btnSignIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            signIn(edtEmail.getText().toString(),edtPassword.getText().toString());
        }
    });

}

private void signIn(final String user, final String pwd) {
    users.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if(dataSnapshot.child(user).exists())
            {
                if(!user.isEmpty())
                {
                 User login = dataSnapshot.child(user).getValue(User.class);
                 if(login.getPassword().equals(pwd))
                 {
                     Common.currentUser = login;
                         if(login.getStatus().equals("Admin"))
                         {
                             mAuth.signInWithEmailAndPassword(edtEmail.getText().toString(),
                                     edtPassword.getText().toString());
                             Toast.makeText(SignInActivity.this, "User signed in", Toast.LENGTH_LONG).show();
                             Intent intent = new Intent(SignInActivity.this,QuizListActivity.class);
                             intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                             startActivity(intent);
                             finish(); return;
                         }
                         else if(login.getStatus().equals("User") && login.getApproval().equals("Y"))
                             {
                                 Intent homeactivity = new Intent(SignInActivity.this,Home.class);
                                 startActivity(homeactivity);
                                 finish();
                             }
                         else if(login.getStatus().equals("User") && login.getApproval().equals("N"))
                         {
                             Intent adminactivity = new Intent(SignInActivity.this,Home.class);
                             startActivity(adminactivity);
                             finish();
                         }

                 }
                 else
                     Toast.makeText(SignInActivity.this,"Login Failed",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(SignInActivity.this,"Please fill in",Toast.LENGTH_SHORT).show();
                }
            }
            else
            {
                Toast.makeText(SignInActivity.this,"User doesn't exist",Toast.LENGTH_SHORT).show();
            }
        }


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

        }
    });
}

private void showSignUpDialog() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(SignInActivity.this);
    alertDialog.setTitle("Sign Up");
    //alertDialog.setMessage("Please fill full information");

    LayoutInflater inflater = this.getLayoutInflater();
    View activity_register = inflater.inflate(R.layout.activity_register,null);

    //edtNewUserName = (MaterialEditText)activity_register.findViewById(R.id.edtNewUserName);
    edtNewEmail = (MaterialEditText)activity_register.findViewById(R.id.edtNewEmail);
    edtNewPassword = (MaterialEditText)activity_register.findViewById(R.id.edtNewPassword);
    edtnewName =  (MaterialEditText)activity_register.findViewById(R.id.edtnewName);
    edtnewAge = (MaterialEditText)activity_register.findViewById(R.id.edtnewAge);
    edtnewAddress = (MaterialEditText)activity_register.findViewById(R.id.edtnewAddress);
    edtStatus = (MaterialEditText)activity_register.findViewById(R.id.edtStatus);

    alertDialog.setView(activity_register);
    //alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);

    alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    });
    alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            final User user = new User(edtNewEmail.getText().toString(),
                    edtNewPassword.getText().toString(),edtnewName.getText().toString(),
                    edtnewAge.getText().toString(),edtnewAddress.getText().toString(),edtStatus.getText().toString(),
                    "N");
            users.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.child(user.getEmail()).exists())
                        Toast.makeText(SignInActivity.this,"User already exist.",Toast.LENGTH_LONG).show();
                    else
                    {
                        if(dataSnapshot.child(user.getStatus()).exists() && user.getStatus() == "Admin")
                        {
                            mAuth.createUserWithEmailAndPassword(edtNewEmail.getText().toString(),
                                    edtNewPassword.getText().toString())
                                    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                                        @Override
                                        public void onComplete(@NonNull Task<AuthResult> task) {
                                            if(task.isSuccessful())
                                            {
                                                FirebaseDatabase.getInstance().getReference("User")
                                                        .child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user);
                                            }
                                        }
                                    });
                        }
                        else {
                            users.child(user.getEmail())
                                    .setValue(user);
                            Toast.makeText(SignInActivity.this, "User registered.", Toast.LENGTH_LONG).show();
                        }
                    }

                }

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

                }
            });
            dialogInterface.dismiss();
        }
    });
    alertDialog.show();

}

}

登录和注册的效果很好,然后登录后可以正确显示列表回收者视图,但没有出现菜单,并且无法单击回收者视图。

对于菜单,它先前声明为空引用或其他内容。

1 个答案:

答案 0 :(得分:0)

对于第一个问题,这就是为什么未初始化FirebaseUser而不显示菜单的原因。您需要通过方法onCreate对其进行初始化。

在课堂上。

private FirebaseUser user;

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_quiz_list);
   mAuth = FirebaseAuth.getInstance();
   user = mAuth.getCurrentUser();
}

接下来,在您的onCreateOptionsMenu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.quizlistmenu, menu);
    if(user!=null) {
        menu.getItem(0).setVisible(true);
        menu.getItem(1).setVisible(true);
        menu.getItem(2).setVisible(true);
    }
    return super.onCreateOptionsMenu(menu);
}