I am facing 2 nulls in my app when I try to use some buttons in it . I have checking and reviewing my codes for 3 days till now but I can not solve the null logCat shows me that the
null is at ".Question.getCorrectAnswer() / QuestionFragment.showCorrectAnswer(QuestionFragment.java:175) and QuestionActivity.onActivityResult(QuestionActivity.java:419)"
and other button shows null at "AnswerSheetHelperAdapter.notifyDataSetChanged() / at QuestionActivity.onActivityResult(QuestionActivity.java:436)"
But I'm sure that there are no nulls at all: I need help from expert people maybe they find something I cannot find cause I am a rookie for now.
This is my Question script:
public class ResultGridAdapter extends RecyclerView.Adapter<ResultGridAdapter.MyViewHolder> {
Context context;
List<CurrentQuestion> currentQuestionList;
public ResultGridAdapter(Context context, List<CurrentQuestion> currentQuestionList) {
this.context = context;
this.currentQuestionList = currentQuestionList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(context).inflate(R.layout.layout_result_item, viewGroup, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
Drawable img;
myViewHolder.btn_question.setText(new StringBuilder("Question").append(currentQuestionList.get(i)
.getQuestionIndex() + 1));
if (currentQuestionList.get(i).getType() == Common.ANSWER_TYPE.RIGHT_ANSWER) {
myViewHolder.btn_question.setBackgroundColor(Color.parseColor("#ff99cc00"));
img = context.getResources().getDrawable(R.drawable.ic_check_white_24dp);
myViewHolder.btn_question.setCompoundDrawables(null, null, null, img);
} else if (currentQuestionList.get(i).getType() == Common.ANSWER_TYPE.WRONG_ANSWER) {
myViewHolder.btn_question.setBackgroundColor(Color.parseColor("#ffcc0000"));
img = context.getResources().getDrawable(R.drawable.ic_clear_white_24dp);
myViewHolder.btn_question.setCompoundDrawables(null, null, null, img);
} else {
img = context.getResources().getDrawable(R.drawable.ic_error_outline_white_24dp);
myViewHolder.btn_question.setCompoundDrawables(null, null, null, img);
}
}
@Override
public int getItemCount() {
return currentQuestionList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
Button btn_question;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
btn_question = (Button) itemView.findViewById(R.id.btn_question);
btn_question.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LocalBroadcastManager.getInstance(context)
.sendBroadcast(new Intent(Common.KEY_BACK_FROM_RESULT).putExtra(Common.KEY_BACK_FROM_RESULT
, currentQuestionList.get(getAdapterPosition()).getQuestionIndex()));
}
});
}
}
}
This is my QuestionFragment:
public class QuestionFragment extends Fragment implements IQuestion {
TextView txt_question_text;
CheckBox ckbA, ckbB, ckbC, ckbD;
FrameLayout layout_image;
ProgressBar progressBar;
Question question;
int questionIndex = -1;
public QuestionFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View itemView = inflater.inflate(R.layout.fragment_question, container, false);
questionIndex = getArguments().getInt("index", -1);
question = Common.questionList.get(questionIndex);
if (question != null) {
layout_image = (FrameLayout) itemView.findViewById(R.id.layout_image);
progressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar);
if (question.isImageQuestion()) {
ImageView img_question = (ImageView) itemView.findViewById(R.id.img_question);
Picasso.get().load(question.getQuestionImage()).into(img_question, new Callback() {
@Override
public void onSuccess() {
progressBar.setVisibility(View.GONE);
}
@Override
public void onError(Exception e) {
Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else
layout_image.setVisibility(View.GONE);
txt_question_text = (TextView) itemView.findViewById(R.id.txt_question_text);
txt_question_text.setText(question.getQuestionText());
ckbA = (CheckBox) itemView.findViewById(R.id.ckbA);
ckbA.setText(question.getAnswerA());
ckbA.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbA.getText().toString());
else
Common.selected_values.remove(ckbA.getText().toString());
}
});
ckbB = (CheckBox) itemView.findViewById(R.id.ckbB);
ckbB.setText(question.getAnswerB());
ckbB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbB.getText().toString());
else
Common.selected_values.remove(ckbB.getText().toString());
}
});
ckbC = (CheckBox) itemView.findViewById(R.id.ckbC);
ckbC.setText(question.getAnswerC());
ckbC.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbC.getText().toString());
else
Common.selected_values.remove(ckbC.getText().toString());
}
});
ckbD = (CheckBox) itemView.findViewById(R.id.ckbD);
ckbD.setText(question.getAnswerD());
ckbD.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean b) {
if (b)
Common.selected_values.add(ckbD.getText().toString());
else
Common.selected_values.remove(ckbD.getText().toString());
}
});
}
return itemView;
}
@Override
public CurrentQuestion getSelectedAnswer() {
CurrentQuestion currentQuestion = new CurrentQuestion(questionIndex, Common.ANSWER_TYPE.NO_ANSWER);
StringBuilder result = new StringBuilder();
if (Common.selected_values.size() > 1) {
//for multi choices this will make it multi arrays for answer if it has multi value
Object[] arrayAnswer = Common.selected_values.toArray();
for (int i = 0; i < arrayAnswer.length; i++)
if (i < arrayAnswer.length - 1)
result.append(new StringBuilder(((String) arrayAnswer[i]).substring(0, 1)).append(","));
else
result.append(new StringBuilder((String) arrayAnswer[i]).substring(0, 1));
} else if (Common.selected_values.size() == 1) {
Object[] arrayAnswer = Common.selected_values.toArray();
result.append((String) arrayAnswer[0]).substring(0, 1);
}
if (question != null) {
if (!TextUtils.isEmpty(result)) {
if (result.toString().equals(question.getCorrectAnswer()))
currentQuestion.setType(Common.ANSWER_TYPE.RIGHT_ANSWER);
else
currentQuestion.setType(Common.ANSWER_TYPE.WRONG_ANSWER);
} else
currentQuestion.setType(Common.ANSWER_TYPE.NO_ANSWER);
} else {
Toast.makeText(getContext(), "Cannot get Question", Toast.LENGTH_SHORT).show();
currentQuestion.setType(Common.ANSWER_TYPE.NO_ANSWER);
}
Common.selected_values.clear();
return currentQuestion;
}
@Override
public void showCorrectAnswer() {
String[] correctAnswer = question.getCorrectAnswer().split(",");
for (String answer : correctAnswer) {
if (answer.equals("A")) {
ckbA.setTypeface(null, Typeface.BOLD);
ckbA.setTextColor(Color.RED);
} else if (answer.equals("B")) {
ckbB.setTypeface(null, Typeface.BOLD);
ckbB.setTextColor(Color.RED);
} else if (answer.equals("C")) {
ckbC.setTypeface(null, Typeface.BOLD);
ckbC.setTextColor(Color.RED);
} else if (answer.equals("D")) {
ckbD.setTypeface(null, Typeface.BOLD);
ckbD.setTextColor(Color.RED);
}
}
}
@Override
public void disapleAnswer() {
ckbA.setEnabled(false);
ckbB.setEnabled(false);
ckbC.setEnabled(false);
ckbD.setEnabled(false);
}
@Override
public void resetQuestion() {
ckbA.setEnabled(true);
ckbB.setEnabled(true);
ckbC.setEnabled(true);
ckbD.setEnabled(true);
ckbA.setChecked(false);
ckbB.setChecked(false);
ckbC.setChecked(false);
ckbD.setChecked(false);
ckbA.setTypeface(null, Typeface.NORMAL);
ckbA.setTextColor(Color.BLACK);
ckbB.setTypeface(null, Typeface.NORMAL);
ckbB.setTextColor(Color.BLACK);
ckbC.setTypeface(null, Typeface.NORMAL);
ckbC.setTextColor(Color.BLACK);
ckbD.setTypeface(null, Typeface.NORMAL);
ckbD.setTextColor(Color.BLACK);
}
}
This is my QuestionActivity:
public class QuestionActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private static final int CODE_GET_RESULT = 9999;
ActionBarDrawerToggle toggle;
int time_play = Common.TOTAL_TIME;
private static final String time_Format = "%02d:%02d:%02d";
boolean isAnswerModeView = false;
TextView txt_right_answer, txt_timer, txt_wrong_answer;
RecyclerView answer_sheet_view;
AnswerSheetAdapter answerSheetAdapter;
AnswerSheetHelperAdapter answerSheetHelperAdapter;
ViewPager viewPager;
TabLayout tabLayout;
@Override
protected void onDestroy() {
if (Common.countDownTimer != null)
Common.countDownTimer.cancel();
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(Common.selectedCategory.getName());
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//we need to import question from db
takeQuestion();
if (Common.questionList.size() > 0) {
//to show timer and answer
txt_right_answer = (TextView) findViewById(R.id.txt_question_right);
txt_timer = (TextView) findViewById(R.id.txt_timer);
txt_timer.setVisibility(View.VISIBLE);
txt_right_answer.setVisibility(View.VISIBLE);
txt_right_answer.setText(new StringBuilder(String.format("%d/%d", Common.right_answer_count, Common.questionList.size())));
countTimer();
//view
answer_sheet_view = (RecyclerView) findViewById(R.id.grid_answer);
answer_sheet_view.setHasFixedSize(true);
if (Common.questionList.size() > 5)
answer_sheet_view.setLayoutManager(new GridLayoutManager(this, Common.questionList.size() / 2));
answerSheetAdapter = new AnswerSheetAdapter(this, Common.answerSheetList);
answer_sheet_view.setAdapter(answerSheetAdapter);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
genFragmentList();
QuestionFragmentAdapter questionFragmentAdapter = new QuestionFragmentAdapter(getSupportFragmentManager(),
this,
Common.fragmentsList);
viewPager.setAdapter(questionFragmentAdapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
int SCROLLING_RIGHT = 0;
int SCROLLING_LEFT = 1;
int SCROLLING_UNDETERMINED = 2;
int currentScrollDirection = 2;
private void setScrollingDirection(float positionOffset) {
if ((1 - positionOffset) >= 0.5)
this.currentScrollDirection = SCROLLING_RIGHT;
else if ((1 - positionOffset) <= 0.5)
this.currentScrollDirection = SCROLLING_LEFT;
}
private boolean isScrolledDirectionUndetermined() {
return currentScrollDirection == SCROLLING_UNDETERMINED;
}
private boolean isScrollingRight() {
return currentScrollDirection == SCROLLING_RIGHT;
}
private boolean isScrollingLeft() {
return currentScrollDirection == SCROLLING_LEFT;
}
@Override
public void onPageScrolled(int i, float v, int i1) {
if (isScrolledDirectionUndetermined())
setScrollingDirection(v);
}
@Override
public void onPageSelected(int i) {
QuestionFragment questionFragment;
int position = 0;
if (i > 0) {
if (isScrollingRight()) {
questionFragment = Common.fragmentsList.get(i - 1);
position = i - 1;
} else if (isScrollingLeft()) {
questionFragment = Common.fragmentsList.get(i + 1);
position = i + 1;
} else {
questionFragment = Common.fragmentsList.get(position);
}
} else {
questionFragment = Common.fragmentsList.get(0);
position = 0;
}
CurrentQuestion question_state = questionFragment.getSelectedAnswer();
Common.answerSheetList.set(position, question_state);
answerSheetAdapter.notifyDataSetChanged();
countCorrectAnswer();
txt_right_answer.setText(new StringBuilder(String.format("%d", Common.right_answer_count))
.append("/")
.append(String.format("%d", Common.questionList.size())).toString());
txt_wrong_answer.setText(String.valueOf(Common.wrong_answer_count));
if (question_state.getType() != Common.ANSWER_TYPE.NO_ANSWER) {
questionFragment.showCorrectAnswer();
questionFragment.disapleAnswer();
}
}
@Override
public void onPageScrollStateChanged(int i) {
if (i == ViewPager.SCROLL_STATE_IDLE)
this.currentScrollDirection = SCROLLING_UNDETERMINED;
}
});
}
}
private void finishGame() {
int position = viewPager.getCurrentItem();
QuestionFragment questionFragment = Common.fragmentsList.get(position);
CurrentQuestion question_state = questionFragment.getSelectedAnswer();
Common.answerSheetList.set(position, question_state);
answerSheetAdapter.notifyDataSetChanged();
countCorrectAnswer();
txt_right_answer.setText(new StringBuilder(String.format("%d", Common.right_answer_count))
.append("/")
.append(String.format("%d", Common.questionList.size())).toString());
txt_wrong_answer.setText(String.valueOf(Common.wrong_answer_count));
if (question_state.getType() != Common.ANSWER_TYPE.NO_ANSWER) {
questionFragment.showCorrectAnswer();
questionFragment.disapleAnswer();
}
Intent intent = new Intent(QuestionActivity.this, ResultActivity.class);
Common.timer = Common.TOTAL_TIME - time_play;
Common.no_answer_count = Common.questionList.size() - (Common.wrong_answer_count + Common.right_answer_count);
Common.data_question = new StringBuilder(new Gson().toJson(Common.answerSheetList));
startActivityForResult(intent, CODE_GET_RESULT);
}
private void countCorrectAnswer() {
Common.right_answer_count = Common.wrong_answer_count = 0;
for (CurrentQuestion item : Common.answerSheetList)
if (item.getType() == Common.ANSWER_TYPE.RIGHT_ANSWER)
Common.right_answer_count++;
else if (item.getType() == Common.ANSWER_TYPE.WRONG_ANSWER)
Common.wrong_answer_count++;
}
private void genFragmentList() {
for (int i = 0; i < Common.questionList.size(); i++) {
Bundle bundle = new Bundle();
bundle.putInt("index", i);
QuestionFragment fragment = new QuestionFragment();
fragment.setArguments(bundle);
Common.fragmentsList.add(fragment);
}
}
private void countTimer() {
if (Common.countDownTimer == null) {
Common.countDownTimer = new CountDownTimer(Common.TOTAL_TIME, 1000) {
@Override
public void onTick(long millisUntilFinished) {
txt_timer.setText(String.format(time_Format,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
@Override
public void onFinish() {
//finish the game :]
finishGame();
}
}.start();
} else {
Common.countDownTimer.cancel();
Common.countDownTimer = new CountDownTimer(Common.TOTAL_TIME, 1000) {
@Override
public void onTick(long millisUntilFinished) {
txt_timer.setText(String.format(time_Format,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
@Override
public void onFinish() {
//finish the game :]
}
}.start();
}
}
private void takeQuestion() {
Common.questionList = DBHelper.getInstance(this).getQuestionByCategory(Common.selectedCategory.getId());
if (Common.questionList.size() == 0) {
//this one in case category is empty
new MaterialStyledDialog.Builder(this)
.setTitle("Coming Soon !")
.setIcon(R.drawable.ic_sentiment_very_dissatisfied_black_24dp)
.setDescription("The content is coming soon waite for " + Common.selectedCategory.getName() + " category ")
.setPositiveText("ok")
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
finish();
}
}).show();
} else {
if (Common.answerSheetList.size() > 0)
Common.answerSheetList.clear();
//gen answers from answersheet each question will has online 1 answer sheet content
for (int i = 0; i < Common.questionList.size(); i++) {
Common.answerSheetList.add(new CurrentQuestion(i, Common.ANSWER_TYPE.NO_ANSWER)); //no answer is default
}
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.menu_wrong_answer);
ConstraintLayout constraintLayout = (ConstraintLayout) item.getActionView();
txt_wrong_answer = (TextView) constraintLayout.findViewById(R.id.txt_wrong_answer);
txt_wrong_answer.setText(String.valueOf(0));
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.question, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_finish_game) {
if (!isAnswerModeView) {
new MaterialStyledDialog.Builder(this)
.setTitle("Finish ?")
.setIcon(R.drawable.ic_mood_black_24dp)
.setDescription("Do you really want to finish?")
.setNegativeText("NO")
.onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
}
})
.setPositiveText("YES")
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
finishGame();
}
}).show();
} else
finishGame();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE_GET_RESULT) {
if (resultCode == Activity.RESULT_OK) {
String action = data.getStringExtra("action");
if (action == null || TextUtils.isEmpty(action)) {
int questionNum = data.getIntExtra(Common.KEY_BACK_FROM_RESULT, -1);
viewPager.setCurrentItem(questionNum);
isAnswerModeView = true;
Common.countDownTimer.cancel();
txt_wrong_answer.setVisibility(View.GONE);
txt_right_answer.setVisibility(View.GONE);
txt_timer.setVisibility(View.GONE);
} else {
if (action.equals("viewquizanswer")) {
viewPager.setCurrentItem(0);
isAnswerModeView = true;
Common.countDownTimer.cancel();
txt_wrong_answer.setVisibility(View.GONE);
txt_right_answer.setVisibility(View.GONE);
txt_timer.setVisibility(View.GONE);
for (int i = 0; i < Common.fragmentsList.size(); i++) {
Common.fragmentsList.get(i).showCorrectAnswer();
Common.fragmentsList.get(i).disapleAnswer();
}
} else if (action.equals("doitagain")) {
viewPager.setCurrentItem(0);
isAnswerModeView = false;
countTimer();
txt_wrong_answer.setVisibility(View.VISIBLE);
txt_right_answer.setVisibility(View.VISIBLE);
txt_timer.setVisibility(View.VISIBLE);
for (CurrentQuestion item : Common.answerSheetList)
item.setType(Common.ANSWER_TYPE.NO_ANSWER);
answerSheetAdapter.notifyDataSetChanged();
answerSheetHelperAdapter.notifyDataSetChanged();
for (int i = 0; i < Common.fragmentsList.size(); i++)
Common.fragmentsList.get(i).resetQuestion();
}
}
}
}
}
}