首页 > 解决方案 > 我必须单击两次才能对其进行更新(调试时效果很好)

问题描述

我正在尝试制作一个教授 C 语言的应用程序。我的应用程序有 4 个片段,“学习”“测验”“排名”和“个人资料”。我的课程卡在“学习”片段中,当您第一次登录应用程序时,课程 1 可用,其他课程被锁定。我想要做的是当你完成第 1 课时,移除第 2 课上的锁定。我的代码在调试时有效,但在运行时,我必须再单击一次以在我的BottomNavigation. 我的意思是底部导航上的“学习”项目,您可以在屏幕截图中看到它。

这是一开始的样子

这是在完成第 1 课之后

我没有收到任何错误,因为我说我的代码运行良好,但我只需要单击两次。

我试过的

我找不到太多可做的事情,所以我没有尝试,因为我对 android 编程也有点陌生,所以请具体说明。

我正在填写学习片段的班级

public class Learning extends Fragment {

RecyclerView recyclerView;
FirebaseRecyclerAdapter<LearningHelperClass, LearningViewHolder> recyclerAdapter;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference databaseReference;
DatabaseReference lessons,user;

public int index;
public UserHelperClass current;

public static Learning newInstance(){
    Learning learning = new Learning();
    return learning;
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_learning, container, false);
    recyclerView = (RecyclerView)view.findViewById(R.id.recyclerViewLearning);
    recyclerView.setHasFixedSize(true);
    layoutManager = new GridLayoutManager(container.getContext(),1);
    recyclerView.setLayoutManager(layoutManager);

    user.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            current = dataSnapshot.child(Common.currentUser.getUsername()).getValue(UserHelperClass.class);
            Common.currentUser = current;
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    }); //currentUser update
    loadData();

    return view;
}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    database = FirebaseDatabase.getInstance();
    databaseReference = database.getReference("Lessons");
    lessons = database.getReference("LessonInside");
    user = database.getReference("users");

}

private void loadData() {

    FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<LearningHelperClass>()
            .setQuery(databaseReference, LearningHelperClass.class)
            .build();
    recyclerAdapter = new FirebaseRecyclerAdapter<LearningHelperClass, LearningViewHolder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull LearningViewHolder learningViewHolder, int i, @NonNull LearningHelperClass learningHelperClass) {
            index = i;
            learningViewHolder.Name.setText(learningHelperClass.getName());
            learningViewHolder.Number.setText(learningHelperClass.getNumber());
            if(Common.currentUser.getCmpLesson().equals("") && index == 0) {
                learningViewHolder.itemView.setEnabled(true);
                learningViewHolder.Lock.setVisibility(View.INVISIBLE);
                learningViewHolder.Tick.setVisibility(View.INVISIBLE);
            } else if (Common.currentUser.getCmpLesson().equals("") && index != 0){
                learningViewHolder.Lock.setVisibility(View.VISIBLE);
                learningViewHolder.Tick.setVisibility(View.INVISIBLE);
                learningViewHolder.itemView.setEnabled(false);
            }else if (Common.currentUser.getCmpLesson().contains(controlTick())) {
                learningViewHolder.Tick.setVisibility(View.VISIBLE);
                learningViewHolder.Lock.setVisibility(View.INVISIBLE);
                learningViewHolder.itemView.setEnabled(true);
            }else if (Common.currentUser.getCmpLesson().contains(controlLock())){
                learningViewHolder.Tick.setVisibility(View.INVISIBLE);
                learningViewHolder.Lock.setVisibility(View.INVISIBLE);
                learningViewHolder.itemView.setEnabled(true);
            } else {
                learningViewHolder.Lock.setVisibility(View.VISIBLE);
                learningViewHolder.Tick.setVisibility(View.INVISIBLE);
                learningViewHolder.itemView.setEnabled(false);
            }
            learningViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity().getApplicationContext(), StartLesson.class);
                    intent.putExtra("Name", learningHelperClass.getName());
                    Common.lessonId = recyclerAdapter.getRef(i).getKey();
                    startActivity(intent);
                }
            });

        }

        @NonNull
        @Override
        public LearningViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_view,parent,false);
            return new LearningViewHolder(view);
        }
    };
    recyclerAdapter.notifyDataSetChanged();
    recyclerAdapter.startListening();
    recyclerView.setAdapter(recyclerAdapter);
}

public String controlTick(){
    if (index >= 9){
        return " "+(index+1)+" ";
    }else
        return " 0"+(index+1)+" ";
}

public String controlLock(){
    if (index >= 9){
        return " "+(index)+" ";
    }else
        return " 0"+(index)+" ";
}}

我的测试活动类在您完成课程时自动启动,它还会更新 Firebase 关于用户完成课程的信息

public class Tests extends AppCompatActivity implements View.OnClickListener {

ImageView question_image;
Button btnA,btnB,btnC,btnD,btnNext;
TextView txtQuestionNum,question_text;
public String addComplete;
FirebaseDatabase database;
DatabaseReference user;

int index=0,thisQuestion=0,totalQuestion,correctAnswer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_tests);

    txtQuestionNum = (TextView)findViewById(R.id.txtTotalQuestionTest);
    question_text = (TextView)findViewById(R.id.quest_textTest);
    question_image = (ImageView)findViewById(R.id.quest_imageTest);
    btnA = (Button)findViewById(R.id.btnAnswerATest);
    btnB = (Button)findViewById(R.id.btnAnswerBTest);
    btnC = (Button)findViewById(R.id.btnAnswerCTest);
    btnD = (Button)findViewById(R.id.btnAnswerDTest);
    btnNext = (Button)findViewById(R.id.nextButtonTest);
    addComplete = Common.lessonId;
    database = FirebaseDatabase.getInstance();
    user = database.getReference("users");

    btnA.setOnClickListener(this);
    btnB.setOnClickListener(this);
    btnC.setOnClickListener(this);
    btnD.setOnClickListener(this);
    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btnA.setClickable(true);
            btnB.setClickable(true);
            btnC.setClickable(true);
            btnD.setClickable(true);
            btnA.setBackgroundColor(Color.WHITE);
            btnB.setBackgroundColor(Color.WHITE);
            btnC.setBackgroundColor(Color.WHITE);
            btnD.setBackgroundColor(Color.WHITE);
            showQuestion(++index);
            if (index+1 == totalQuestion) {
                btnNext.setText("Finish Course");
                user.child(Common.currentUser.getUsername()).child("cmpLesson").setValue(Common.currentUser.getCmpLesson()+" "+addComplete+" ");
            }
        }
    });
}

@Override
public void onClick(View v) {
    if (index < totalQuestion) {
        Button clickedButton = (Button)v;
        btnA.setClickable(false);
        btnB.setClickable(false);
        btnC.setClickable(false);
        btnD.setClickable(false);
        if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer()))
        {
            clickedButton.setBackgroundColor(Color.GREEN);
            correctAnswer++;
        } else {
            clickedButton.setBackgroundColor(Color.RED);
            if (btnA.getText().equals(Common.questionList.get(index).getCorrectAnswer()))
                btnA.setBackgroundColor(Color.GREEN);
            if (btnB.getText().equals(Common.questionList.get(index).getCorrectAnswer()))
                btnB.setBackgroundColor(Color.GREEN);
            if (btnC.getText().equals(Common.questionList.get(index).getCorrectAnswer()))
                btnC.setBackgroundColor(Color.GREEN);
            if (btnD.getText().equals(Common.questionList.get(index).getCorrectAnswer()))
                btnD.setBackgroundColor(Color.GREEN);
        }
    }
}
private void showQuestion(int index) {
    if (index < totalQuestion) {
        thisQuestion++;
        txtQuestionNum.setText(String.format("%d / %d", thisQuestion, totalQuestion));
            if(Common.questionList.get(index).getIsImageQuestion().equals("true"))
            {
                Picasso.get().load(Common.questionList.get(index).getQuestion())
                        .into(question_image);
                question_image.setVisibility(View.VISIBLE);
                question_text.setVisibility(View.INVISIBLE);
            }
            else
            {
                question_text.setText(Common.questionList.get(index).getQuestion());
                question_image.setVisibility(View.INVISIBLE);
                question_text.setVisibility(View.VISIBLE);
            }
            btnA.setText(Common.questionList.get(index).getAnswerA());
            btnB.setText(Common.questionList.get(index).getAnswerB());
            btnC.setText(Common.questionList.get(index).getAnswerC());
            btnD.setText(Common.questionList.get(index).getAnswerD());
        } else
        {
            //Son Soru
            Intent intent = new Intent(this, HomeNavigationBottom.class);
            startActivity(intent);
            finish();
        }
    }

@Override
protected void onResume() {
    super.onResume();
    totalQuestion = Common.questionList.size();
    showQuestion(index);
}}

我的 UserHelperClass

public class UserHelperClass {

String username,email,password,cmpQuiz,cmpLesson;

public UserHelperClass() {
}

public UserHelperClass(String username, String email, String password, String cmpQuiz, String cmpLesson) {
    this.username = username;
    this.email = email;
    this.password = password;
    this.cmpQuiz = cmpQuiz;
    this.cmpLesson = cmpLesson;
}

public String getCmpQuiz() {
    return cmpQuiz;
}

public void setCmpQuiz(String cmpQuiz) {
    this.cmpQuiz = cmpQuiz;
}

public String getCmpLesson() {
    return cmpLesson;
}

public void setCmpLesson(String cmpLesson) {
    this.cmpLesson = cmpLesson;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getEmail() {
    return email;
}

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

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}}

HomeNavigation底层类。BottomNavigationView 的代码

public class HomeNavigationBottom extends AppCompatActivity {

BottomNavigationView bottomNavigationView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_home_navigation_bottom);

    bottomNavigationView = (BottomNavigationView)findViewById(R.id.navigation);

    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            Fragment selectedFragment = null;

            switch (item.getItemId()){
                case R.id.action_dashboard:
                    selectedFragment = Dashboard.newInstance();
                    break;
                case R.id.action_learning:
                    selectedFragment = Learning.newInstance();
                    break;
                case R.id.action_profile:
                    selectedFragment = Profile.newInstance();
                    break;
                case R.id.action_ranking:
                    selectedFragment = Ranking.newInstance();
                    break;
            }
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.frame_layout,selectedFragment);
            transaction.commit();
            return false;
        }
    });
    setDefaultFragment();
}

private void setDefaultFragment() {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_layout,Profile.newInstance());
    transaction.commit();
}}

我想这就是我需要说的,谢谢你的时间!

标签: javaandroidfirebasefirebase-realtime-databaseandroid-recyclerview

解决方案


所以你需要recyclerAdapter.startListening();onCreateonStartonResume,因为BottomNavigationView第一次点击后可以创建和缓存的选项卡;如果您转到其他选项卡并返回,则将启动/恢复缓存版本而不再次创建它,因此recyclerAdapter.startListening();除非您第二次单击它以重新创建它,否则不会触发它。

也为了提高效率,在相反的生命周期方法中停止侦听器onPauseonStop使用recyclerAdapter.stopListening();


推荐阅读