Array is getting Wiped - java

So I am in the middle of a Challenge from a book I am reading. The challenge says that I do some questions at the users of the app and they should answer True or False. Also they have the option to cheat but when they gone back to the question answer must not be acceptable.
So I created a Boolean Array where I save the status of the "cheater". True if he cheats and False if he doesn't cheat. But after one full rotation of the Questions the Array is Wiped. Why is this happening? What I am doing wrong?
Here is my main code for the Quiz Activity:
public class QuizActivity extends Activity {
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mCheatButton;
private TextView mQuestionTextView;
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private static final String CHEATER_BOOLEAN = "cheat";
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true),
};
private boolean[] mCheatBank = new boolean[mQuestionBank.length];
private int mCurrentIndex = 0;
private boolean mIsCheater;
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if(mIsCheater) {
messageResId = R.string.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT)
.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
mQuestionTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
mIsCheater = mCheatBank[mCurrentIndex];
updateQuestion();
}
});
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this,CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivityForResult(i,0);
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
mIsCheater = savedInstanceState.getBoolean(CHEATER_BOOLEAN, false);
}
updateQuestion();
} // End of onCreate(Bundle) method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG,"onActivityResult called");
if (data == null) {
return;
}
mIsCheater = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN, false);
mCheatBank[mCurrentIndex] = mIsCheater;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
savedInstanceState.putBoolean(CHEATER_BOOLEAN, mIsCheater);
}
Edit 1: Here is the code from the other classes because someone asked.
CheatActivity Code:
public class CheatActivity extends Activity {
public static final String EXTRA_ANSWER_IS_TRUE = "com.bignerrandch.android.geoquiz.answer_is_true";
public static final String EXTRA_ANSWER_SHOWN = "com.bignerdranch.android.geoquiz.answer_shown";
private boolean mAnswerIsTrue;
private boolean mCheater;
private TextView mAnswerTextView;
private Button mShowAnswer;
private void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView)findViewById(R.id.answerTextView);
mCheater = false;
if (savedInstanceState != null) {
mCheater = savedInstanceState.getBoolean(EXTRA_ANSWER_SHOWN, false);
setAnswerShownResult(mCheater);
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
}
else {
mAnswerTextView.setText(R.string.false_button);
}
} else {
setAnswerShownResult(false);
}
mShowAnswer = (Button)findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
}
else {
mAnswerTextView.setText(R.string.false_button);
}
setAnswerShownResult(true);
mCheater = true;
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(EXTRA_ANSWER_SHOWN, mCheater);
}
}
TrueFalse Code:
public class TrueFalse{
private int mQuestion;
private boolean mTrueQuestion;
public TrueFalse(int question, boolean trueQuestion) {
mQuestion = question;
mTrueQuestion = trueQuestion;
}
public int getQuestion() {
return mQuestion;
}
public void setQuestion(int question) {
mQuestion = question;
}
public boolean isTrueQuestion() {
return mTrueQuestion;
}
public void setTrueQuestion(boolean trueQuestion) {
mTrueQuestion = trueQuestion;
}
}

It's not entirely clear what you mean by wiped. But I think your problem is that you are using a member variable to set your array values. So you are setting each element of your array to that value. So essentially the entire array will be set to what ever the final state of mIsCheater is.

Related

Data is not Retrieving from Firebase Firestore into Arraylist in Android Studio?

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.

preventing a user from entering multiple answer

i create a true/false quiz app. in that app i have 4 buttons i.e True,False,previous(to get back to previous question),next(to get the next question). i want to add a functionality when a user click on true or false button its get disable for that question so the user can click only once for one question.
i tried to disable the button by using button.setEnabled(false) but when i click on previous button or next button the true/false buttons enabled.i want that the user can click the answer only once it does not matter how much the user traverse the question.
i try to call the setEnabledButton() in previous on click button but it disable the button but it also disable whether the user click on answer or not.
Button btrue,bfalse,bnext,bprevious;
TextView tquestion;
int mCurrentIndex=0;
Questions[] questionbank;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btrue=findViewById(R.id.true_button);
bfalse=findViewById(R.id.false_button);
bnext=findViewById(R.id.next_button);
tquestion=findViewById(R.id.question_text);
bprevious=findViewById(R.id.previous_button);
questionbank = new Questions[]
{
new Questions(R.string.greater,false),
new Questions(R.string.Pm,true),
new Questions(R.string.capital,true),
new Questions(R.string.china,false),
new Questions(R.string.Richer,false),
new Questions(R.string.company,true),
new Questions(R.string.company1,false),
};
update();
bnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int s=questionbank.length;
if( mCurrentIndex<=s )
{
if (mCurrentIndex + 1 < questionbank.length) {
mCurrentIndex++;
}
else
{ Toast.makeText(getApplicationContext(),"not more question",Toast.LENGTH_SHORT).show();
}
update();
}
}
});
btrue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(true);
}
});
bfalse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(false);
}
});
bprevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrentIndex > 0) {
mCurrentIndex = (mCurrentIndex - 1);
update();
}
else
{ Toast.makeText(getApplicationContext(), "cant go back", Toast.LENGTH_SHORT).show(); }
}
});
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
setButtonEnabled(true);
}
private void checkAnswer(boolean userPressedTrue)
{
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
private void setButtonEnabled(boolean enabled) {
btrue.setEnabled(enabled);
bfalse.setEnabled(enabled);
}
}
In Questions class you can create a method,
public class Questions {
boolean isQuestionAnswered;
public boolean isQuestionAnswered() {
return isQuestionAnswered;
}
public void setQuestionAnswered(boolean questionAnswered) {
isQuestionAnswered = questionAnswered;
}
}
private void checkAnswer(boolean userPressedTrue)
{
questionbank[mCurrentIndex].setQuestionAnswered(true);
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
if(questionbank[mCurrentIndex].isQuestionAnswered())
setButtonEnabled(false);
else
setButtonEnabled(true);
}
Try this out and check whether this solves your problem

App is not responding after running this activity

New Activity UI load but does not respond, After running onStop() which trigger submit()
List View with the checkbox is bound by a custom adapter. On touch of the Submit button, an intent is triggered which takes me to HomeActivity and onStop() method is triggered which in return call submit method. All submit method is created under a new thread which interfere with UI.
package com.example.cadur.teacher;
public class Attendace extends AppCompatActivity {
DatabaseReference dref;
ArrayList<String> list=new ArrayList<>();
ArrayList<DeatailAttandance> deatailAttandances;
private MyListAdapter myListAdapter;
private ProgressDialog pb;
String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
int pre_int,abs_int;
ListView listview;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
final String s=sp.getString("Password","");
final String s1=sp.getString("username","");
year=sp.getString("Year","");
branch=sp.getString("Branch","");
subject=sp.getString("Subject","");
final String attend="Attandence";
emailId=sp.getString("emailId","");
if (s!=null&&s!="" && s1!=null&&s1!="") {
setContentView(R.layout.activity_attendace);
deatailAttandances=new ArrayList<>();
listview = findViewById(R.id.list);
TextView detail=findViewById(R.id.lay);
detail.setText(year+" "+branch+" "+" "+subject);
pb =new ProgressDialog(Attendace.this);
pb.setTitle("Connecting Database");
pb.setMessage("Please Wait....");
pb.setCancelable(false);
pb.show();
database=FirebaseDatabase.getInstance();
myRef=database.getReference(year+"/"+branch);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()) {
try {
abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
rollno = ds.getKey().toString();
deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
listview.setAdapter(myListAdapter);
pb.dismiss();
}catch (NullPointerException e){
pb.dismiss();
Intent intent=new Intent(Attendace.this, Login.class);
startActivity(intent);
finish();
}
}
count();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
Button selectAll=findViewById(R.id.selectall);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myListAdapter.setCheck();
count();
}
});
Button submit_attan=findViewById(R.id.submit_attan);
submit_attan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(Attendace.this,HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
Button count=findViewById(R.id.count);
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
});
}else{
SharedPreferences.Editor e = sp.edit();
e.putString("Password", "");
e.putString("username", "");
e.commit();
Intent i=new Intent(Attendace.this,MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected void onStop() {
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
finish();
super.onStop();
}
public void submit(){
View parentView = null;
final Calendar calendar = Calendar.getInstance();
dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
file_name=year+"_"+branch+"_"+dat;
rollno_present=rollno_present+""+year+" "+branch+" "+subject+"\n "+dat+"\n\nList of present Students\n";
rollno_absent=rollno_absent+"\n List of absent Students\n";
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
pre_int=Integer.parseInt(pre_str);
abs_int=Integer.parseInt(abs_str);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
pre_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
rollno_present=rollno_present+"\n"+roll_str+"\n";
}else{
abs_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
rollno_absent=rollno_absent+"\n"+roll_str+"\n";
}
}
// Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
}
});
}
public void count(){
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
private View getViewByPosition(int pos, ListView listview1) {
final int firstListItemPosition = listview1.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listview1.getAdapter().getView(pos, null, listview1);
} else {
final int childIndex = pos - firstListItemPosition;
return listview1.getChildAt(childIndex);
}
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try
{
File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, file_name+".doc");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n");
writer.flush();
writer.close();
// Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Just use
submit();
instead of using
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
and remove finish()

Unable to display String from Intent

At the moment when running I get only one text displayed Wrong_answer.
public class AnswerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
TextView textViewDisplayResult = (TextView) findViewById(R.id.text_view_display_result);
textViewDisplayResult.setText(getIntent().getExtras().getString("KEY_ALL_CHECKED"));
textViewDisplayResult.setText(getIntent().getBooleanExtra("KEY_ANSWER", false)?R.string.Good_answer:R.string.Wrong_answer);
}
POST UPDATE
public class MainActivity extends AppCompatActivity {
private static int NUMBER_OF_QUESTIONS = 3;
static boolean[] answer = new boolean[NUMBER_OF_QUESTIONS];
static boolean[] checked = new boolean[NUMBER_OF_QUESTIONS];
static boolean[] isAnswered = new boolean[NUMBER_OF_QUESTIONS];
final Intent intent = new Intent(MainActivity.this, AnswerActivity.class);
buttonCheckAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!allAnswersChecked())
intent.putExtra("KEY_ALL_CHECKED", R.string.text_not_checked);
else if (checkAnswers())
intent.putExtra("KEY_ANSWER", R.string.Good_answer);
else
intent.putExtra("KEY_ANSWER", R.string.Wrong_answer);
startActivity(intent);
}
});
public static void checkSelected() {
for (boolean radioChecked : checked) {
if (radioChecked) {
buttonCheckAnswer.setVisibility(View.VISIBLE);
break;
}
}
}
private boolean checkAnswers() {
for (boolean radioAnswer : answer) {
if (!radioAnswer) {
return false;
}
}
return true;
}
private boolean allAnswersChecked() {
for (boolean radioAnswer : isAnswered) {
if (!radioAnswer) {
return false;
}
}
return true;
}
and AnswerActivity
public class AnswerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
TextView textViewDisplayResult = (TextView) findViewById(R.id.text_view_display_result);
textViewDisplayResult.setText(getIntent().getExtras().getString("KEY_ALL_CHECKED"));
textViewDisplayResult.setText(getIntent().getBooleanExtra("KEY_ANSWER", false)?getString(R.string.Good_answer):getString(R.string.Wrong_answer));
}
}
Second setText will overwrite your first setText value.
....
String x = getIntent().getExtras().getString("KEY_ALL_CHECKED");
textViewDisplayResult.setText(getIntent().getBooleanExtra("KEY_ANSWER", false) ? x +" "+ R.string.Good_answer: x +" "+ R.string.Wrong_answer);
textViewDisplayResult will always overwrite.
If you want both to display in same textView you just need to append the text like below:
textViewDisplayResult.setText(getIntent().getExtras().getString("KEY_ALL_CHECKED"));
textViewDisplayResult.append(getIntent().getBooleanExtra("KEY_ANSWER", false)?getString(R.string.Good_answer):getString(R.string.Wrong_answer));
This will display your both result in same textView.

How to get data from getter setter class?

I am beginner in android development , I have some issue please help me.
I have 2 screen Login and After Login , I have set User id in login class and i want to use that user_id in after login how to get , when I use get method find Null how to resolve this problem.
here is my Login Code`public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
private LoginBean loginBean;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
setupUI(findViewById(R.id.parentEdit));
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
public void getLogin(JSONObject response) {
LoginBean loginBean = new LoginBean();
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
}
}
}
`
here is my AfterLogin class`public class AfterLoginActivity extends FragmentActivity {
private ImageView partyIcon;
private ImageView dealIcon;
private ImageView deliveryIcon;
private TextView txtParty;
private TextView txtDeals;
private TextView txtDelivery;
boolean doubleBackToExitPressedOnce = false;
int backButtonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
Utility.setStatusBarColor(this, R.color.splash_status_color);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
partyIcon = (ImageView)findViewById(R.id.party_Icon);
dealIcon = (ImageView)findViewById(R.id.deals_Icon);
deliveryIcon = (ImageView)findViewById(R.id.delivery_Icon);
partyIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BookPartyActivity.class);
startActivity(intent);
}
});
dealIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), DealsActivity.class);
startActivity(intent);
}
});
deliveryIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBean loginBean = new LoginBean();
Toast.makeText(getBaseContext(),"Auth"+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MyAuction.class);
startActivity(intent);
}
});
}
/*
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, "you have logged in ,plz enjoy the party", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable()
{
public void run()
{
doubleBackToExitPressedOnce = false;
}
}
, 2000L);
}*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}`
here is LoginBean`public class LoginBean {
private String user_id;
private String full_name;
private String display_name;
private String user_image;
private String gender;
private String authorization_key;
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_id() {
return user_id;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getFull_name() {
return full_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getDisplay_name() {
return display_name;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getUser_image() {
return user_image;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAuthorization_key(String authorization_key) {
this.authorization_key = authorization_key;
}
public String getAuthorization_key() {
return authorization_key;
}
}`
//in your both activity or create class
private SharedPreferences mSharedPreferences;
//in your login on getLogin() method ;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
//save actual drawable id in this way.
if(mSharedPreferences==null)
return;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("userId", loginBean.getUser_id());
editor.commit();
// in your after login acvtivity on deliverable method
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
return;
string userId = mSharedPreferences.getString("userId", "");
You can write and apply below mentioned steps (Please ignore any syntactical error, I am giving you simple logical steps).
step 1 - Make a global application level loginObject setter and getter like below. Make sure to define Application class in your manifest just like you do it for your LoginActivity
public class ApplicationClass extends Application{
private LoginBean loginObject;
public void setLoginBean(LoginBean object) {
this.loginObject = object;
}
public LoginBean getName() {
return this.loginObject
}
}
Step - 2 Get an instance of ApplicationClass object reference in LoginActivity to set this global loginObject
e.g. setLogin object in your current Loginactivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
appObject.setLoginBean(loginObject)
}
Step - 3 Get an instance of ApplicationClass object reference in any other Activity get this global loginObject where you need to access this login data.
e.g. getLogin object in your otherActivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
LoginBean loginObject = appObject.getLoginBean();
}

Categories

Resources