Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

java - I have to click twice to fragment for it to be updated (works well when debugging)

I am trying to make an app that teaches C Language. My app has 4 fragments, "Learning" "Quizzes" "Ranking" and "Profile". My lesson cards is in "Learning" fragment, when you first sign in to app, Lesson 1 is available and the others are locked. What I'm trying to do is when you completed Lesson 1, remove the lock on Lesson 2. My code works when debugging but on run, i have to click one more time to "Learning" fragment on my BottomNavigation. I mean the "Learn" item on the Bottom Navigation, you can see it in the screenshots.

This is what it looks like in the beginning

And this is after completing Lesson 1

I'm not getting any erros, as I said my code works well but I just need to click twice.

What I've Tried

I couldn't find much to do, so i didn't try because i'm also kinda new at android programming, so please be specific.

My Class That I am Filling The Learn Fragment

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)+" ";
}}

My Test Activity Class That Automatically Starts When You Finish a Lesson, It also Updates the Firebase about a User Finished the Lesson

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);
}}

My 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

So you need to move recyclerAdapter.startListening(); from onCreate to onStart or onResume , because tabs of BottomNavigationView can be created and cached after you click it for the first time; if you go to other tabs, and return back then the cached version will be started/resumed without creating it again, and therefore the recyclerAdapter.startListening(); won't be triggered unless you click it for the second time to recreate it again.

Also for efficiency stop the listener in the opposite lifecycle method onPause or onStop using recyclerAdapter.stopListening();


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...