Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
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();
}
}
}
}
}
}
You're never initializing answerSheetHelperAdapter, so it's null. That's one of your problems.
It's impossible to tell why the other one is null without an actual stack trace and more code, but you're probably setting it to null in
question = Common.questionList.get(questionIndex);
See What is a NullPointerException, and how do I fix it? for more information on how to debug this.
Related
I'm using view pager for showing news and insights in same page for news i'm using simple view pager but for insights i'm using nested view pager in insights if there are more than one objects or item for horizontal scrolling the verical scrolling is stopped and when i come on last element of the insights than vertical scroll works
i'm not understanding why this happening.
here is my code...
adapter for viewpager
```
public class AllNewsAndInsightsAdapter extends PagerAdapter
{
Context context;
LayoutInflater layoutInflater;
int showingBottomLayout=1;
int showingToolbar=0;
SharedPreferences prefs;
int like=0;
int bookMark=1;
String userId,token;
boolean isDoubleTap = false;
int textSize;
Handler mHandler = new Handler(Looper.getMainLooper());
String isUserLoggedIn;
ArrayList<MixNewsInsightModel> arrayList;
public AllNewsAndInsightsAdapter(Context context, ArrayList<MixNewsInsightModel> arrayList, int textSize) {
this.context=context;
layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList=arrayList;
this.textSize=textSize;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
prefs = context.getSharedPreferences("UserData", MODE_PRIVATE);
isUserLoggedIn=prefs.getString("logged_in","");
userId=prefs.getString("userId","");
TextView textView5=view.findViewById(R.id.textView5);
view.setOnTouchListener(new View.OnTouchListener() {
private GestureDetector gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
if (showingToolbar==0){
view.findViewById(R.id.toolbar).setVisibility(View.generateViewId());
SlideDownToolbar(view.findViewById(R.id.toolbar),context);
showingToolbar=1;
}else{
SlideUpToolbar(view.findViewById(R.id.toolbar),context);
view.findViewById(R.id.toolbar).setVisibility(View.GONE);
showingToolbar=0;
}
if (showingBottomLayout==0){
SlideDownBottomLayout(view.findViewById(R.id.linearLayout7),context);
view.findViewById(R.id.linearLayout9).setEnabled(true);
view.findViewById(R.id.linearLayout7).setEnabled(false);
view.findViewById(R.id.linearLayout7).setVisibility(View.GONE);
showingBottomLayout=1;
}else{
view.findViewById(R.id.linearLayout7).setVisibility(View.VISIBLE);
view.findViewById(R.id.linearLayout9).setEnabled(false);
view.findViewById(R.id.linearLayout7).setEnabled(true);
SlideUpBottomLayout(view.findViewById(R.id.linearLayout7),context);
showingBottomLayout=0;
}
return true;
}
});
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("TEST", "Raw event: " + event.getAction() + ", (" + event.getRawX() + ", " + event.getRawY() + ")");
gestureDetector.onTouchEvent(event);
return true;
}
});
return view == (ConstraintLayout) object;
}
private void SlideDownBottomLayout(View toolbar, Context context) {
toolbar.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_down_bottomlayout));
}
private void SlideUpBottomLayout(View toolbar, Context context) {
toolbar.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_up_bottonlayout));
}
public void SlideDownToolbar(View view, Context context)
{
view.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_down_toolbar));
}
private void SlideUpToolbar(View view, Context context) {
view.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_up_toolbar));
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
try {
View view=layoutInflater.inflate(R.layout.news_details_page_layout,container,false);
prefs = context.getSharedPreferences("UserData", MODE_PRIVATE);
ImageView likeImageView=view.findViewById(R.id.likeImageView);
view.findViewById(R.id.linearLayout7).setVisibility(View.GONE);
view.findViewById(R.id.toolbar).setVisibility(View.GONE);
this.showingBottomLayout=1;
LinearLayout bookmark_ic=view.findViewById(R.id.bookmark_ic);
userId=prefs.getString("userId","");
token=prefs.getString("token","");
ImageView backArrow=view.findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
context.startActivity(new Intent(context, Main_Dashboard.class));
((Activity)context).finish();
}
});
this.showingToolbar=0;
TextView textView5=view.findViewById(R.id.textView5);
ImageView imageView2=view.findViewById(R.id.imageView2);
ImageView imageView15=view.findViewById(R.id.imageView15);
ImageView bookmarkImage=view.findViewById(R.id.bookmarkImage);
TextView textView18=view.findViewById(R.id.textView18);
TextView textView25=view.findViewById(R.id.textView25);
LinearLayout linearLayout9=view.findViewById(R.id.linearLayout9);
LinearLayout shareLayout=view.findViewById(R.id.shareLayout);
textView25.setText(arrayList.get(position).getNewss().get(0).getHeading());
textView5.setText(arrayList.get(position).getNewss().get(0).getShortDescription());
if (textSize==0){
textView5.setTextSize(18);
}else{
textView5.setTextSize(26);
}
LinearLayout fontSizeView=view.findViewById(R.id.fontSizeView);
RestClient restClient=new RestClient();
ApiService apiService=restClient.getApiService();
fontSizeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (like == 0) {
likeImageView.setImageDrawable(context.getDrawable(R.drawable.ic_heart));
like++;
} else {
if (!userId.equals("") && !isUserLoggedIn.equals("0")) {
JsonObject jsonObject = new JsonObject();
String uId = userId.replace("\"", "");
jsonObject.addProperty("user_id", uId);
String newsId = arrayList.get(position).getId().replace("\"", "");
jsonObject.addProperty("News_id", newsId);
String tokenId = token.replace("\"", "");
Call<JsonObject> call = apiService.addFeed(tokenId, jsonObject);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("TAG", "onResponse: "+response.body().get("msg").toString().replace("\"", ""));
Toast.makeText(context, "" + "News added in my feed successfully", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.d("TAG", "onFailure: " + t.getMessage());
}
});
likeImageView.setImageDrawable(context.getDrawable(R.drawable.ic_heart_red));
like--;
} else {
Toast.makeText(context, "Please Login First", Toast.LENGTH_SHORT).show();
}
}
}
});
linearLayout9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = arrayList.get(position).getLink();
Intent defaultBrowser = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_BROWSER);
try {
defaultBrowser.setData(Uri.parse(data));
context.startActivity(defaultBrowser);
} catch (Exception e) {
Toast.makeText(context, "url is not supported", Toast.LENGTH_SHORT).show();
}
}
});
shareLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, arrayList.get(position).getLink());
sendIntent.setType("text/plain");
Intent shareIntent = Intent.createChooser(sendIntent, arrayList.get(position).getNewss().get(0).getHeading());
context.startActivity(shareIntent);
}
});
String newImgUrl=("http://fpokhabar.evalue8.info/"+ arrayList.get(position).getImage().get(0).toString().trim());
String newUrl2=newImgUrl.replaceAll("\"","");
Glide.with(imageView2).load(newUrl2).into(imageView2);
Glide.with(imageView15).load(newUrl2).into(imageView15);
bookmark_ic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!userId.equals("") && !isUserLoggedIn.equals("0")){
if (bookMark==1){
bookmarkImage.setImageDrawable(context.getDrawable(R.drawable.ic_bi_bookmark_fill));
if (!token.equals("")){
Log.d("TAG", "onClick: kf"+token);
RestClient restClient=new RestClient();
ApiService apiService=restClient.getApiService();
JsonObject jsonObject=new JsonObject();
String uId=userId.replace("\"","");
jsonObject.addProperty("user_id",uId);
jsonObject.addProperty("News_id",arrayList.get(position).getId());
Log.d("TAG", "onClick: "+jsonObject);
String tokenId=token.replace("\"","");
Call<JsonObject> call=apiService.aadBookMark(tokenId,jsonObject);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (response.isSuccessful()){
Toast.makeText(context, "Bookmark added successfully", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
}
});
}else{
Toast.makeText(context, "Token is not available", Toast.LENGTH_SHORT).show();
}
bookMark++;
}else{
bookmarkImage.setImageDrawable(context.getDrawable(R.drawable.ic_bi_bookmark));
Call<JsonObject> call=apiService.deleteBookMark(arrayList.get(position).getId());
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("TAG", "onResponse: delete"+response.body());
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
}
});
bookMark--;
}
}else{
Toast.makeText(context, "please login first", Toast.LENGTH_SHORT).show();
}
}
});
textView18.setText(arrayList.get(position).getNewss().get(0).getFooterText());
Log.d("Tag", "instantiateItem: "+newUrl2);
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i=new Intent(context, ImagePriview.class);
i.putExtra("ImgLink",newUrl2);
i.putExtra("Heading",arrayList.get(position).getNewss().get(0).getHeading());
ActivityOptionsCompat optionsCompat=ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context,imageView2, ViewCompat.getTransitionName(imageView2));
context.startActivity(i,optionsCompat.toBundle());
}
});
container.addView(view);
return view;
}catch (Exception e){
View view=layoutInflater.inflate(R.layout.insight_all_item_page,container,false);
ViewPager2 viewPagerAllItems=view.findViewById(R.id.viewPagerAllItems);
TabLayout tabLayout = view.findViewById(R.id.tabDots);
InsightsPageInNewsAdapter adapter=new InsightsPageInNewsAdapter(context,arrayList.get(position));
viewPagerAllItems.setAdapter(adapter);
adapter.notifyDataSetChanged();
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPagerAllItems, true, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) { }
});
tabLayoutMediator.attach();
container.addView(view);
return view;
}
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout)object);
}
}```
vertical view pager
public class VerticalViewPager extends ViewPager {
public VerticalViewPager(Context context) {
super(context);
init();
}
public VerticalViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setPageTransformer(true, new DepthPageTransformer());
setOverScrollMode(OVER_SCROLL_NEVER);
}
/**
* Swaps the X and Y coordinates of your touch event.
*/
private MotionEvent swapXY(MotionEvent ev) {
float width = getWidth();
float height = getHeight();
float newX = (ev.getY() / height) * width;
float newY = (ev.getX() / width) * height;
ev.setLocation(newX, newY);
return ev;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
swapXY(ev); // return touch coordinates to original reference frame for any child views
return intercepted;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(swapXY(ev));
}
public class DepthPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.95f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0);
} else if (position <= 0) { // [-1,0]
// Use the default slide transition when moving to the left page
// view.setAlpha(1);
//view.setTranslationX(view.getWidth() * -position);
//set Y position to swipe in from top
float yPosition = position * view.getHeight();
view.setTranslationY(yPosition);
view.setScaleX(1);
view.setScaleY(1);
}
else if (position <= 1) { // (0,1]
// Fade the page out.
float scaleFactor = MIN_SCALE
+ (1 - MIN_SCALE) * (1 - Math.abs(position));
float vertMargin = pageHeight * (1 - scaleFactor) / 2;
float horzMargin = pageWidth * (1 - scaleFactor) / 2;
view.setAlpha(1 - position);
// Counteract the default slide transition
view.setTranslationX(pageWidth * -position);
if (position < 0) {
view.setTranslationY(vertMargin - horzMargin / 2);
} else {
view.setTranslationY(-vertMargin + horzMargin / 2);
}
// Scale the page down (between MIN_SCALE and 1)
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
}
else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
}
}`
I am developing a quiz app. So, in this app user first of all tap on play button and he has to choose category and then he has to choose no of questions and quiz will start.
In quiz activity, problem is that data is not retrieving from firebase firestore in the arraylist. If i did some problem please give the solution.
Below is my code of Main Activity.java where user tap on play button.
package com.example.capitalcamp;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,chooseCategory_Activity.class);
startActivity(intent);
}
});
binding.exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
Now user has to choose category. Below is the code of chooseCategoryActivity.java.
package com.example.capitalcamp;
public class chooseCategory_Activity extends AppCompatActivity {
ArrayList<chooseCategoryModal> chooseCategoryArrayList;
chooseCategoryAdapter chooseCategoryAdapter;
ProgressDialog progressDialog;
FirebaseFirestore db;
CollectionReference ref;
ActivityChooseCategory2Binding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityChooseCategory2Binding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
chooseCategoryArrayList = new ArrayList<>();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Categories");
progressDialog.setCancelable(false);
progressDialog.show();
StaggeredGridLayoutManager gridLayoutManager = new StaggeredGridLayoutManager(2,
StaggeredGridLayoutManager.VERTICAL);
binding.categoriesRv.setLayoutManager(gridLayoutManager);
binding.categoriesRv.setHasFixedSize(true);
chooseCategoryAdapter = new chooseCategoryAdapter(chooseCategoryArrayList, chooseCategory_Activity.this);
db = FirebaseFirestore.getInstance();
ref = db.collection("Category");
ref.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot value, FirebaseFirestoreException error) {
if (error != null) {
Log.d("ErrorCollection", error.getMessage());
return;
}
chooseCategoryArrayList.clear();
for (DocumentSnapshot snapshot: value.getDocuments()){
chooseCategoryModal modal = snapshot.toObject(chooseCategoryModal.class);
modal.setCategoryId(snapshot.getId());
chooseCategoryArrayList.add(modal);
}
chooseCategoryAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
});
binding.categoriesRv.setAdapter(chooseCategoryAdapter);
}
}
Below is the code of chooseCategoryModal.java.
package com.example.capitalcamp;
public class chooseCategoryModal {
String categoryName, categoryId;
public chooseCategoryModal() {
}
public chooseCategoryModal(String categoryName, String categoryId) {
this.categoryName = categoryName;
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
}
Below is the code of chooseCategoryAdapter.java.
package com.example.capitalcamp;
public class chooseCategoryAdapter extends RecyclerView.Adapter<chooseCategoryAdapter.ViewHolder>{
ArrayList<chooseCategoryModal> chooseCategorArrayList;
Context context;
BottomSheetDialog bottomSheetDialog;
static int noOfQuestions = 0;
Boolean cardColorCyan = false;
String categoryName, categoryId;
public chooseCategoryAdapter(ArrayList<chooseCategoryModal> chooseCategorArrayList, Context context) {
this.chooseCategorArrayList = chooseCategorArrayList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.choose_category_item,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(chooseCategoryAdapter.ViewHolder holder, int position) {
holder.categ_card.setCardBackgroundColor(getRandomColor());
categoryName = chooseCategorArrayList.get(position).getCategoryName();
categoryId = chooseCategorArrayList.get(position).getCategoryId();
holder.categoryName.setText(categoryName);
holder.categ_card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog = new BottomSheetDialog(context, R.style.BottomSheetTheme);
View bsView = LayoutInflater.from(context).
inflate(R.layout.choose_ques_bottomsheet_layout,
view.findViewById(R.id.choose_ques_bottomsheet));
bottomSheetDialog.setCancelable(false);
CardView card5 = bsView.findViewById(R.id.five_ques);
CardView card10 = bsView.findViewById(R.id.ten_ques);
CardView card15 = bsView.findViewById(R.id.fifteen_ques);
CardView card20 = bsView.findViewById(R.id.twenty_ques);
CardView card25 = bsView.findViewById(R.id.twentyfive_ques);
CardView card30 = bsView.findViewById(R.id.thirty_ques);
bsView.findViewById(R.id.five_ques).setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
if (cardColorCyan) {
card5.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = false;
noOfQuestions = 0;
} else {
card5.setCardBackgroundColor(Color.CYAN);
card10.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card15.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card20.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card25.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card30.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = true;
noOfQuestions = 5;
}
}
});
bsView.findViewById(R.id.ten_ques).setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
if (cardColorCyan) {
card10.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = false;
noOfQuestions = 0;
} else {
card10.setCardBackgroundColor(Color.CYAN);
card5.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card15.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card20.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card25.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card30.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = true;
noOfQuestions = 10;
}
}
});
bsView.findViewById(R.id.fifteen_ques).setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
if (cardColorCyan) {
card15.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = false;
noOfQuestions = 0;
} else {
card15.setCardBackgroundColor(Color.CYAN);
card5.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card10.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card20.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card25.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card30.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = true;
noOfQuestions = 15;
}
}
});
bsView.findViewById(R.id.twenty_ques).setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
if (cardColorCyan) {
card20.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = false;
noOfQuestions = 0;
} else {
card20.setCardBackgroundColor(Color.CYAN);
card5.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card10.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card15.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card25.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card30.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = true;
noOfQuestions = 20;
}
}
});
bsView.findViewById(R.id.twentyfive_ques).setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
if (cardColorCyan) {
card25.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = false;
noOfQuestions = 0;
} else {
card25.setCardBackgroundColor(Color.CYAN);
card5.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card10.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card15.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card20.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card30.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = true;
noOfQuestions = 25;
}
}
});
bsView.findViewById(R.id.thirty_ques).setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
if (cardColorCyan) {
card30.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = false;
noOfQuestions = 0;
} else {
card30.setCardBackgroundColor(Color.CYAN);
card5.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card10.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card15.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card20.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
card25.setCardBackgroundColor(context.getColorStateList(R.color.light_grey));
cardColorCyan = true;
noOfQuestions = 30;
}
}
});
bsView.findViewById(R.id.play_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (noOfQuestions != 0){
bottomSheetDialog.dismiss();
Intent intent = new Intent(context,Quiz_Activity.class);
intent.putExtra("CC_noOfQuestion",noOfQuestions);
intent.putExtra("CC_quizCategory",categoryName);
intent.putExtra("CC_categoryId",categoryId);
context.startActivity(intent);
} else {
Toast.makeText(context, "Choose No of Questions", Toast.LENGTH_SHORT).show();
}
}
});
bsView.findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
noOfQuestions = 0;
bottomSheetDialog.dismiss();
}
});
bottomSheetDialog.setContentView(bsView);
bottomSheetDialog.show();
}
});
}
#Override
public int getItemCount() {
return chooseCategorArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView categoryName;
CardView categ_card;
public ViewHolder(View itemView) {
super(itemView);
categoryName = itemView.findViewById(R.id.categoryName);
categ_card = itemView.findViewById(R.id.categ_card);
}
}
private int getRandomColor(){
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
return color;
}
}
Data is not updating in realtime. This is also happened in chooseCategoryActivity but after implementing the below dependency it solved.
implementation "io.grpc:grpc-okhttp:1.32.2"
Below is the code of quizActivity.java.
package com.example.capitalcamp;
public class Quiz_Activity extends AppCompatActivity {
int noOfQuestions;
String quizCategory, categoryId;
ArrayList<QuestionModal> questionModalArrayList;
Random random;
int currentScore = 0, incorrectScore = 0, questionNo = 1;
Handler handler = new Handler();
FirebaseFirestore firestore;
int index = 0;
QuestionModal question;
ActivityQuizBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityQuizBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
random = new Random();
questionModalArrayList = new ArrayList<>();
noOfQuestions = getIntent().getIntExtra("CC_noOfQuestion", 0);
quizCategory = getIntent().getStringExtra("CC_quizCategory");
categoryId = getIntent().getStringExtra("CC_categoryId");
addQuestions();
binding.optionA.setOnClickListener(this::onClick);
binding.optionB.setOnClickListener(this::onClick);
binding.optionC.setOnClickListener(this::onClick);
binding.optionD.setOnClickListener(this::onClick);
}
private void addQuestions() {
firestore = FirebaseFirestore.getInstance();
int rand = random.nextInt(5);
firestore.collection("Category")
.document(categoryId)
.collection("Questions")
.whereGreaterThanOrEqualTo("index", rand)
.orderBy("index")
.limit(noOfQuestions)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (queryDocumentSnapshots.getDocuments().size() < 5) {
firestore.collection("Category")
.document(categoryId)
.collection("Questions")
.whereLessThanOrEqualTo("index", rand)
.orderBy("index")
.limit(noOfQuestions)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (DocumentSnapshot snapshot : queryDocumentSnapshots) {
QuestionModal questionModal = snapshot.toObject(QuestionModal.class);
questionModalArrayList.add(questionModal);
Toast.makeText(Quiz_Activity.this, "Success 1", Toast.LENGTH_SHORT).show();
}
setNextQuestion();
}
});
Log.d("question success 1","question success 1");
} else {
for (DocumentSnapshot snapshot : queryDocumentSnapshots) {
QuestionModal questionModal = snapshot.toObject(QuestionModal.class);
questionModalArrayList.add(questionModal);
Toast.makeText(Quiz_Activity.this, "Success 1", Toast.LENGTH_SHORT).show();
}
setNextQuestion();
Log.d("question success 2","question success 2");
}
}
});
}
private void showScoreBoard() {
ProgressDialog dialog = new ProgressDialog(Quiz_Activity.this);
dialog.setCancelable(false);
dialog.setMessage("Loading Score Board");
dialog.show();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(Quiz_Activity.this, ScoreBoard_Activity.class);
intent.putExtra("quizCategory", quizCategory);
intent.putExtra("noOfQuestions", noOfQuestions);
intent.putExtra("correctAnswers", currentScore);
intent.putExtra("incorrectAnswers", incorrectScore);
startActivity(intent);
finish();
dialog.dismiss();
}
}, 2000);
}
private void setNextQuestion() {
if (index < questionModalArrayList.size()) {
question = questionModalArrayList.get(index);
binding.questionNo.setText("Question " + questionNo++);
binding.progress.setText("Progress: " + (index + 1) + "/" + noOfQuestions);
binding.question.setText(question.getQuestion());
binding.optionA.setText(question.getOptionA());
binding.optionB.setText(question.getOptionB());
binding.optionC.setText(question.getOptionC());
binding.optionD.setText(question.getOptionD());
} else {
showScoreBoard();
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void onClick(View view) {
switch (view.getId()) {
case R.id.option_A:
setCardClickable();
checkAnswer(binding.optionA, binding.opACard);
setHandler();
break;
case R.id.option_B:
setCardClickable();
checkAnswer(binding.optionB, binding.opBCard);
setHandler();
break;
case R.id.option_C:
setCardClickable();
checkAnswer(binding.optionC, binding.opCCard);
setHandler();
break;
case R.id.option_D:
setCardClickable();
checkAnswer(binding.optionD, binding.opDCard);
setHandler();
break;
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void checkAnswer(TextView option, MaterialCardView card) {
if (option.getText().toString().trim().toLowerCase()
.equals(question.getCorrectAnswer().trim().toLowerCase())) {
currentScore++;
card.setStrokeColor(getColorStateList(R.color.green));
} else {
incorrectScore++;
card.setStrokeColor(getColorStateList(R.color.red));
if (binding.optionA.getText().toString().trim().toLowerCase()
.equals(question.getCorrectAnswer().trim().toLowerCase())) {
binding.opACard.setStrokeColor(getColorStateList(R.color.green));
} else if (binding.optionB.getText().toString().trim().toLowerCase()
.equals(question.getCorrectAnswer().trim().toLowerCase())) {
binding.opBCard.setStrokeColor(getColorStateList(R.color.green));
} else if (binding.optionC.getText().toString().trim().toLowerCase()
.equals(question.getCorrectAnswer().trim().toLowerCase())) {
binding.opCCard.setStrokeColor(getColorStateList(R.color.green));
} else if (binding.optionD.getText().toString().trim().toLowerCase()
.equals(question.getCorrectAnswer().trim().toLowerCase())) {
binding.opDCard.setStrokeColor(getColorStateList(R.color.green));
}
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void resetCardStrokeColors() {
binding.opACard.setStrokeColor(getColorStateList(R.color.main_color));
binding.opBCard.setStrokeColor(getColorStateList(R.color.main_color));
binding.opCCard.setStrokeColor(getColorStateList(R.color.main_color));
binding.opDCard.setStrokeColor(getColorStateList(R.color.main_color));
}
private void setCardClickable() {
binding.opACard.setClickable(false);
binding.opBCard.setClickable(false);
binding.opCCard.setClickable(false);
binding.opDCard.setClickable(false);
}
private void setHandler() {
if (index <= questionModalArrayList.size()) {
handler.postDelayed(new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void run() {
resetCardStrokeColors();
index++;
setNextQuestion();
}
}, 2000);
} else {
showScoreBoard();
}
}
}
Below is the code of QuestionModal.java.
package com.example.capitalcamp;
public class QuestionModal {
String Question, OptionA, OptionB, OptionC, OptionD, CorrectAnswer, QuestionId;
Number index;
public QuestionModal(){
}
public QuestionModal( String question, String optionA, String optionB,
String optionC, String optionD, String correctAnswer, String questionId, Number Index) {
Question = question;
OptionA = optionA;
OptionB = optionB;
OptionC = optionC;
OptionD = optionD;
CorrectAnswer = correctAnswer;
QuestionId = questionId;
index = Index;
}
public String getQuestion() {
return Question;
}
public void setQuestion(String question) {
Question = question;
}
public String getOptionA() {
return OptionA;
}
public void setOptionA(String optionA) {
OptionA = optionA;
}
public String getOptionB() {
return OptionB;
}
public void setOptionB(String optionB) {
OptionB = optionB;
}
public String getOptionC() {
return OptionC;
}
public void setOptionC(String optionC) {
OptionC = optionC;
}
public String getOptionD() {
return OptionD;
}
public void setOptionD(String optionD) {
OptionD = optionD;
}
public String getCorrectAnswer() {
return CorrectAnswer;
}
public void setCorrectAnswer(String correctAnswer) {
CorrectAnswer = correctAnswer;
}
public String getQuestionId() {
return QuestionId;
}
public void setQuestionId(String questionId) {
QuestionId = questionId;
}
public Number getIndex() {
return index;
}
public void setIndex(Number index) {
this.index = index;
}
}
Below is the link of screenshot of firestore database.
Firestore Database Image 1
Firestore Database Image 2
In this quiz activity, problem is that data is not retrieving from firebase firestore in the arraylist. If i did some problem please give the solution.
Realm class
public class RealmManager
private static Realm mRealm;
public static Realm open() {
mRealm = Realm.getDefaultInstance();
return mRealm;
}
public static void close() {
if (mRealm != null) {
mRealm.close();
}
}
public static RecordsDao recordsDao() {
checkForOpenRealm();
return new RecordsDao(mRealm);
}
private static void checkForOpenRealm() {
if (mRealm == null || mRealm.isClosed()) {
throw new IllegalStateException("RealmManager: Realm is closed, call open() method first");
}
}
}
When I call RealmManager.open(); my app crashes with error
Unable to open a realm at path
'/data/data/com.apphoctienganhpro.firstapp/files/default.realm':
Unsupported Realm file format version. in
/Users/cm/Realm/realm-java/realm/realm-library/src/main/cpp/io_realm_internal_SharedRealm.cpp
line 92 Kind: ACCESS_ERROR
Activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
ButterKnife.bind(this);
RealmManager.open();
NestedScrollView scrollView = findViewById(R.id.nest_scrollview);
scrollView.setFillViewport(true);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(true);
}
final CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = findViewById(R.id.appbar);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = true;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
isShow = true;
} else if (isShow) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
isShow = false;
}
}
});
arrayListCategory = Utility.getAppcon().getSession().arrayListCategory;
arrayListGoal = Utility.getAppcon().getSession().arrayListGoal;
arrayList = new ArrayList<>();
arrayList = Utility.getAppcon().getSession().arrayListCategory;
if (arrayListGoal.size() > 0) {
goal_id = arrayListGoal.get(0).getSingleGoalId();
}else{
if(!arrayList.get(0).getCategory_description().equals("")) {
if(!Utility.getAppcon().getSession().screen_name.equals("lessson_complete")) {
displayDialog();
}
}
}
collapsingToolbarLayout.setTitle(arrayListCategory.get(0).getCategoryName());
layoutManager = new LinearLayoutManager(this);
recycler_view.setLayoutManager(layoutManager);
apiservice = ApiServiceCreator.createService("latest");
sessionManager = new SessionManager(this);
getCategoryLesson();
}
private void displayDialog() {
dialog = new Dialog(LessonActivity.this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_layout_lesson_detail);
dialog.setCancelable(true);
txt_close = dialog.findViewById(R.id.txt_close);
txt_title_d = dialog.findViewById(R.id.txt_title_d);
txt_description_d = dialog.findViewById(R.id.txt_description_d);
img_main_d = dialog.findViewById(R.id.img_main_d);
img_play_d = dialog.findViewById(R.id.img_play_d);
img_play_d.setVisibility(View.GONE);
Picasso.with(LessonActivity.this).load(ApiConstants.IMAGE_URL + arrayList.get(0).getCategoryImage())
.noFade()
.fit()
.placeholder(R.drawable.icon_no_image)
.into(img_main_d);
txt_title_d.setText(arrayList.get(0).getCategoryName());
txt_description_d.setText(Html.fromHtml(arrayList.get(0).getCategory_description().replaceAll("\\\\", "")));
dialog.show();
Window window = dialog.getWindow();
assert window != null;
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
txt_close.setOnClickListener(view -> dialog.dismiss());
}
private void getCategoryLesson() {
pDialog = new ProgressDialog(LessonActivity.this);
pDialog.setTitle("Checking Data");
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Observable<LessonResponse> responseObservable = apiservice.getCategoryLesson(
sessionManager.getKeyEmail(),
arrayListCategory.get(0).getCategoryId(),
goal_id,
sessionManager.getUserData().get(0).getUserId(),
sessionManager.getKeyToken());
responseObservable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(throwable -> {
if (throwable instanceof retrofit2.HttpException) {
retrofit2.HttpException ex = (retrofit2.HttpException) throwable;
Log.e("error", ex.getLocalizedMessage());
}
return Observable.empty();
})
.subscribe(new Observer<LessonResponse>() {
#Override
public void onCompleted() {
pDialog.dismiss();
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(LessonResponse lessonResponse) {
if (lessonResponse.getData().size() > 9) {
txt_total_lesson.setText(String.valueOf(lessonResponse.getData().size()));
} else {
txt_total_lesson.setText(String.valueOf("0" + lessonResponse.getData().size()));
}
if (lessonResponse.getStatusCode() == 200) {
adapter = new LessonAdapter(lessonResponse.getData(), LessonActivity.this);
recycler_view.setAdapter(adapter);
} else {
Utility.displayToast(getApplicationContext(), lessonResponse.getMessage());
}
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onClickFavButton(int position, boolean toggle) {
}
public boolean isFavourate(String LessionId,String UserId){
if (arrayList!=null){
for (int i=0;i<arrayList.size();i++)
if (favarrayList.get(1).getLessonId().equals(LessionId) && favarrayList.get(0).getUserID().equals(UserId)){
return true;
}
}
return false;
}
#Override
protected void onDestroy() {
super.onDestroy();
RealmManager.close();
}
}
Adapter Class
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_lesson, parent, false);
return new LessonAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
dialog = new Dialog(context);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_layout_lesson_audio);
txt_close = dialog.findViewById(R.id.txt_close);
txt_title_d = dialog.findViewById(R.id.txt_title_d);
txt_description_d = dialog.findViewById(R.id.txt_description_d);
img_play_d = dialog.findViewById(R.id.img_play_d);
frm_header = dialog.findViewById(R.id.frm_header);
img_back_d = dialog.findViewById(R.id.img_back_d);
holder.txt_lesson_title.setText(arrayList.get(position).getLessonName());
holder.btn_view.setOnClickListener(view -> {
txt_title_d.setText(arrayList.get(position).getLessonName());
dialog.show();
Window window = dialog.getWindow();
assert window != null;
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
txt_description_d.setText(Html.fromHtml(arrayList.get(position).getLessonDescription().replaceAll("\\\\", "")));
displayDialog(holder.getAdapterPosition());
});
holder.btn_go.setOnClickListener(view -> {
Utility.getAppcon().getSession().arrayListLesson = new ArrayList<>();
Utility.getAppcon().getSession().arrayListLesson.add(arrayList.get(position));
Intent intent = new Intent(context, LessonCompleteActivity.class);
context.startActivity(intent);
});
if (arrayList.get(position).isFavourate())
holder.favCheck.setChecked(true);
else
holder.favCheck.setChecked(false);
holder.favCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox checkBox = (CheckBox) view;
if (checkBox.isChecked()) {
RealmManager.recordsDao().saveToFavorites(arrayList.get(position));
} else {
RealmManager.recordsDao().removeFromFavorites(arrayList.get(position));
}
}
});
}
private void displayDialog(int Position) {
final MediaPlayer mediaPlayer = new MediaPlayer();
String url = ApiConstants.IMAGE_URL + arrayList.get(Position).getLesson_audio_url();
//String url = "http://208.91.198.96/~diestechnologyco/apphoctienganhpro/uploads/mp3/mp3_1.mp3"; // your URL here
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare(); // might take long! (for buffering, etc)
} catch (IOException e) {
e.printStackTrace();
}
img_play_d.setOnClickListener(view -> {
if (audio_flag == 0) {
mediaPlayer.start();
audio_flag = 1;
img_play_d.setImageResource(R.mipmap.pause_circle);
} else {
mediaPlayer.pause();
audio_flag = 0;
img_play_d.setImageResource(R.mipmap.icon_play);
}
});
//img_play_d.setOnClickListener(view -> mediaPlayer.start());
txt_close.setOnClickListener(view -> {
mediaPlayer.stop();
dialog.dismiss();
});
img_back_d.setOnClickListener(view -> {
mediaPlayer.stop();
dialog.dismiss();
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.txt_lesson_title)
TextView txt_lesson_title;
#BindView(R.id.txt_lesson_type)
TextView txt_lesson_type;
#BindView(R.id.btn_view)
Button btn_view;
#BindView(R.id.btn_go)
Button btn_go;
#BindView(R.id.image_favborder)
CheckBox favCheck;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
//RealmManager.open();
}
}
public void getdata(){
}
public void addFavourate(String LessonId,String UserId) {
if (mRealm != null) {
mRealm.beginTransaction();
favList_model = mRealm.createObject(FavList_model.class);
favList_model.setLessonId(LessonId);
favList_model.setUserID(UserId);
mRealm.commitTransaction();
mRealm.close();
}
}
}
I have pdf reader with list view and cant open all pdf because diffrent password.
source code: https://deepshikhapuri.wordpress.com/2017/04/24/open-pdf-file-from-sdcard-in-android-programmatically/
I want pdf that can not open when on click pop up error messages.
can you help me?
Main Activity.java
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"Pdf");
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra("position", i);
startActivity(intent);
Log.e("Position", i + "Pdf");
}
});
}
public static ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
getfile(listFile[i]);
} else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(".pdf")) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {
}
}
if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
PdfActivity
public static final String SAMPLE_FILE = "android_tutorial.pdf";
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG = "PdfActivity";
int position = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}
private void init() {
pdfView = (PDFView) findViewById(R.id.pdfView);
//position = Environment.getExternalStorageDirectory()+"/sdcard/Pdf"
position = getIntent().getIntExtra("position", -1);
displayFromSdcard();
//String position = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Pdf/";
}
private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();
pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)
.password("123456")
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
}
#Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), "-");
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + "-");
}
}
}
PdfAdapter
Context context;
ViewHolder viewHolder;
ArrayList<File> al_pdf;
public PDFAdapter(Context context, ArrayList<File> al_pdf) {
super(context, R.layout.adapter_pdf, al_pdf);
this.context = context;
this.al_pdf = al_pdf;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_pdf.size() > 0) {
return al_pdf.size();
} else {
return 1;
}
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
if (view == null) {
view = LayoutInflater.from(getContext()).inflate(R.layout.adapter_pdf, parent, false);
viewHolder = new ViewHolder();
viewHolder.tv_filename = (TextView) view.findViewById(R.id.tv_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.tv_filename.setText(al_pdf.get(position).getName());
return view;
}
public class ViewHolder {
TextView tv_filename;
}
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
if(isPaswordProcted()){
Toast.makeText(this, password procted, Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra("position", i);
startActivity(intent);
}
}
});
I have added a timer to my game but by doing so i keep getting the error "The method setOnTouchListener(View.OnTouchListener) in the type View is not applicable for the arguments (scene5.MyCountDownTimer)" I can not seem to fix it. This might just be me making a simple mistake but any solutions would be great. The error is about halfway down my code, I have tagged it with //THIS IS MY PROBLEM AREA!! Cheers guys
public class scene5 extends Activity implements OnClickListener {
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView text;
private final long startTime = 20 * 1000;
private final long interval = 1 * 1000;
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("FindIt")
.setMessage("Exit to main menu?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level5);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime/1000));
}
#Override
public void onClick(View v) {
startB.setVisibility(View.INVISIBLE);
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("RESTART");
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Intent intent = new Intent(scene5.this, timeUp.class);
scene5.this.startActivity(intent);
finish();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished/1000);
}
{
ImageView iv = (ImageView) findViewById (R.id.image);
if (iv != null) {
iv.setOnTouchListener (this); //THIS IS MY PROBLEM AREA!!
}
toast ("20 seconds to find IT!");}
}
public boolean onTouch (View v, MotionEvent ev)
{
boolean handledHere = false;
final int action = ev.getAction();
final int evX = (int) ev.getX();
final int evY = (int) ev.getY();
int nextImage = -1;
ImageView imageView = (ImageView) v.findViewById (R.id.image);
if (imageView == null) return false;
Integer tagNum = (Integer) imageView.getTag ();
int currentResource = (tagNum == null) ? R.drawable.levels : tagNum.intValue ();
switch (action) {
case MotionEvent.ACTION_DOWN :
if (currentResource == R.drawable.levels) {
nextImage = R.drawable.wrong5;
handledHere = true;
} else handledHere = true;
break;
case MotionEvent.ACTION_UP :
int touchColor = getHotspotColor (R.id.image_areas, evX, evY);
ColorTool ct = new ColorTool ();
int tolerance = 25;
nextImage = R.drawable.levels;
if (ct.closeMatch (Color.RED, touchColor, tolerance)){
Intent intent = new Intent(scene5.this, LevelComplete.class);
scene5.this.startActivity(intent);
}
if (currentResource == nextImage) {
nextImage = R.drawable.levels;
}
handledHere = true;
break;
default:
handledHere = false;
}
if (handledHere) {
if (nextImage > 0) {
imageView.setImageResource (nextImage);
imageView.setTag (nextImage);
}
}
return handledHere;
}
public int getHotspotColor (int hotspotId, int x, int y) {
ImageView img = (ImageView) findViewById (hotspotId);
if (img == null) {
Log.d ("ImageAreasActivity", "Hot spot image not found");
return 0;
} else {
img.setDrawingCacheEnabled(true);
Bitmap hotspots = Bitmap.createBitmap(img.getDrawingCache());
if (hotspots == null) {
Log.d ("ImageAreasActivity", "Hot spot bitmap was not created");
return 0;
} else {
img.setDrawingCacheEnabled(false);
return hotspots.getPixel(x, y);
}
}
}
public void toast (String msg)
{
Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_LONG).show ();
}
}
Your problem is here:
public class scene5 extends Activity implements OnClickListener, OnTouchListener {
...
#Override
public boolean onTouch(View v, MotionEvent event) {
...
}
}
You have to implements also OnTouchListener.
Use
scene5.this
instead of this
the problem is iv.setOnTouchListener (this);
the this context you are passing belongs to the timer task, You need to use iv.setOnTouchListener (scene5.this);
Also, I think you need to find the ImageView reference in the onCreate itself. What you are doing currently ImageView iv = (ImageView) findViewById (R.id.image); won't work.