how to check if the random number exists in array - java

I'm trying to check my random number exists in my array; this is my array
int [] img = {R.drawable.im1,R.drawable.im2}
My function to update data and show it random
private void updateQuestion() {
int ranom_number = random.nextInt(img.length);
image.setImageResource(img[ranom_number]);
ton= MediaPlayer.create(BallActivity.this,Questions.audinb[ranom_number]);
ton.start();
}
this is my class. In my view I have a button I want when the random number is displaying if the user clicks right the other buttons disappear. If he clicks next then all buttons should be displayed. If the last number of array is displaying the activity finish
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
if (ranom_number == img.length) {
bravo = MediaPlayer.create(getApplicationContext(), R.raw.bravo);
bravo.start();
bt2.setVisibility(v.GONE);
}else{
bt1.setVisibility(v.VISIBLE);
bt2.setVisibility(v.VISIBLE);
}
break;
case R.id.btn2:
if(ranom_number <= img.length-1){
}
break;
case R.id.suiv:
if(ranom_number <= imgnb.length-1) {
updateQuestion();
}else{
Intent i = new Intent(BallActivity.this, NewActivity.class);
BallActivity.this.finish();
startActivity(i);
}
}
But doesn't work thank you for helping

Related

Why is the text in TextViews changing two times when I am calling it only once at a time?

I know setText just changes the text only once but I can't seem to find the reason why the text in it changes before I move on to the next question in the quizActivity
What I have made is an app with one activity in it which has a quiz in it, a question is displayed along with 4 options. When the user selects an option, if that option is correct then it becomes green and red otherwise and additionally, I then open a dialog box showing whether the answer was right or wrong and then the question is changed when the user clicks Next on the dialog box.
But what is happening that when the user selects an option, in between the process of clicking the option and then clicking next on the dialog box, the text in the questions and the options changes and I can't seem to figure out why is that happening. In total, the question and options change two times when they should change only once, the unexpected change is when the user clicks on an option and the dialog box opens.
Here's the code:
#Override
public void onClick(View view) {
int selectedOption = 0;
switch (view.getId()) {
case R.id.option_1_tile:
selectedOption = 1;
break;
case R.id.option_2_tile:
selectedOption = 2;
break;
case R.id.option_3_tile:
selectedOption = 3;
break;
case R.id.option_4_tile:
selectedOption = 4;
break;
default:
}
checkAnswer(selectedOption, view);
}
Here's the function which checks the answer:
private void checkAnswer(int selectedOption, View view) {
if (selectedOption == selected_questions.get(quesNum).getAnswer()) {
//Right Answer
(view).setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
quizReference.child(selected_questions.get(quesNum).getId()).child("correct_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getCorrect_attempts()) + 1));
quizReference.child(selected_questions.get(quesNum).getId()).child("total_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getTotal_attempts()) + 1));
score++;
correctDialog();
} else {
//Wrong Answer
(view).setBackgroundTintList(ColorStateList.valueOf(Color.RED));
quizReference.child(selected_questions.get(quesNum).getId()).child("total_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getTotal_attempts()) + 1));
switch (selected_questions.get(quesNum).getAnswer()) {
case 1:
options[0].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 2:
options[1].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 3:
options[2].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 4:
options[3].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
}
wrongDialog ();
}
}
Here's the function which changes the question:
private void changeQuestion() {
resetColor ();
if (quesNum < selected_questions.size() - 1) {
quesNum++;
playAnim(question, 0, 0);
playAnim(option1_text, 0, 1);
playAnim(option2_text, 0, 2);
playAnim(option3_text, 0, 3);
playAnim(option4_text, 0, 4);
qCount.setText(String.valueOf(quesNum + 1) + "/" + String.valueOf(selected_questions.size()));
} else {
// Go to Score Activity
Intent intent = new Intent(quizActivity.this, scoreActivity.class);
intent.putExtra("SCORE", String.valueOf(score) + "/" + String.valueOf(selected_questions.size()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Here's the function which sets the text and animation:
private void playAnim(final View view, final int value, final int viewNum) {
view.animate().alpha(value).scaleX(value).scaleY(value).setDuration(500)
.setStartDelay(100).setInterpolator(new DecelerateInterpolator())
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
if (value == 0) {
switch (viewNum) {
case 0:
((TextView) view).setText(selected_questions.get(quesNum).getQuestion());
break;
case 1:
((TextView) view).setText(selected_questions.get(quesNum).getOption1());
break;
case 2:
((TextView) view).setText(selected_questions.get(quesNum).getOption2());
break;
case 3:
((TextView) view).setText(selected_questions.get(quesNum).getOption3());
break;
case 4:
((TextView) view).setText(selected_questions.get(quesNum).getOption4());
break;
}
if (viewNum != 0)
(view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#E99C03")));
playAnim(view, 1, viewNum);
}
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
Here's the code for the dialog boxes:
public void wrongDialog() {
final Dialog dialogWrong = new Dialog(quizActivity.this);
dialogWrong.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogWrong.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogWrong.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogWrong.setContentView(R.layout.dialog_wrong);
dialogWrong.setCancelable(false);
dialogWrong.show();
TextView wrongText = (TextView) dialogWrong.findViewById(R.id.wrongText);
Button buttonNext = (Button) dialogWrong.findViewById(R.id.dialogNext);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogWrong.dismiss();
//reset the color of buttons back to white
resetColor();
//Change question
changeQuestion();
}
});
}
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(quizActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog_correct);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
Button buttonNext = (Button) dialogCorrect.findViewById(R.id.dialogNext);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//reset the color of buttons back to white
resetColor();
//it will increment the question number
changeQuestion();
}
});
}
I have tried to explain it to my best ability though I would be glad to answer any additional information/code you may want. Also, this is the link for the project if you have the time to run it and understand the problem better.
I have checked your code. you have placed an addValueEventListener in setUpdates method. When you select an option, you update the firestore database by setting fields like total attempts. As a result, eventListener gets triggered and "selectQuestionSet" function is called.
Hence, every time you select an option, selectQuestionSet function is called. You should make sure that its called only once at the start.

Android RecyclerView Adapter ImageButton Problem

I have my adapters with image buttons and so. When pressing the sixth one it does as suppose to do. This is the last time it was updated correctly.
But then it keeps moving up the list doing the same thing. Now this
#Override
public void onClick(View view) {
TimeCard card = MyAdapter.cards.get(position);
switch (view.getId()) {
case R.id.playButton:
startTimer(card);
///new Logger(TimeCardButton.class).debug("Play button was pressed");
break;
case R.id.editButton:
Intent intent = new Intent(context, TimeCardAdd.class);
intent.putExtra("cardPosition", position);
context.startActivity(intent);
//TODO: Finish the editing so we can modify the timer card
Toast.makeText(context, "Edit button has been pressed.", Toast.LENGTH_SHORT).show();
break;
case R.id.stopButton:
stopTimer(card);
break;
case R.id.pauseButton:
pauseTimer(card);
break;
}
}
Is called only once. Which is correct. But this is called every second from the UI update call
private void sendPlayTimeButtons() {
cardButtons.get(TimeCardButtonId.PLAY_BUTTON.getId()).setVisibility(View.INVISIBLE);
cardButtons.get(TimeCardButtonId.EDIT_BUTTON.getId()).setVisibility(View.INVISIBLE);
cardButtons.get(TimeCardButtonId.PAUSE_BUTTON.getId()).setVisibility(View.VISIBLE);
cardButtons.get(TimeCardButtonId.STOP_BUTTON.getId()).setVisibility(View.VISIBLE);
// logger.debug("Sending Play Buttons");
}
Here's the code for my BindViewHolder on the Adapter
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
//TODO: add everything back
holder.playButton.setOnClickListener(new TimeCardButton(context, holder.getAdapterPosition(), holder.buttons).checkStatus());
holder.editButton.setOnClickListener(new TimeCardButton(context, holder.getAdapterPosition(), holder.buttons).checkStatus());
holder.pauseButton.setOnClickListener(new TimeCardButton(context, holder.getAdapterPosition(), holder.buttons).checkStatus());
holder.stopButton.setOnClickListener(new TimeCardButton(context, holder.getAdapterPosition(), holder.buttons).checkStatus());
}
And last but finally the code for my ViewHolder inside the adapter
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView timerTitle;
public TextView timeRemaining;
ImageButton playButton;
ImageButton editButton;
ImageButton pauseButton;
ImageButton stopButton;
LinkedList<ImageButton> buttons = new LinkedList<>();
public MyViewHolder(final View view) {
super(view);
timerTitle = view.findViewById(R.id.titleCardName);
timeRemaining = view.findViewById(R.id.timeLeftTextCard);
playButton = view.findViewById(R.id.playButton);
editButton = view.findViewById(R.id.editButton);
pauseButton = view.findViewById(R.id.pauseButton);
stopButton = view.findViewById(R.id.stopButton);
buttons.add(playButton);
buttons.add(editButton);
buttons.add(pauseButton);
buttons.add(stopButton);
}
}
Here's the startTimer function which I have tested and it's called only once.
private void startTimer(TimeCard card) {
new Logger(TimeCardButton.class).debug("Play button was pressed");
if (!card.isTimeStarted()) {
card.setTimeStarted(true);
sendPlayTimeButtons();
logger.info("Starting Timer!");
} else if(card.isTimerPaused() && card.isTimeStarted()) {
TimerTask.notifyUpdate();
card.setTimerPaused(false);
sendPlayTimeButtons();
logger.info("Resuming from being paused!");
}
}
By all of them one at a time by my task system. My Task system only sends updates to the recycler from the activity handling the UI calls...
Again On those images, the buttons will move up the list every second having no reason. I tried replacing the button ids with tags. But that still failed.
You need to have a separate array in your adapter having the track of the list playing/paused/stopped. Let us consider the following.
0 -> Stopped
1 -> Playing
2 -> Paused
Now take an array in your adapter like the following.
// This initializes the array with the number of elements of your list
// and all initialized by 0 to indicate primarily all tracks were not playing.
int[] trackPlayer = new int[cards.size];
Now when you are clicking the buttons to do some action you need to update the array with the action as well.
#Override
public void onClick(View view) {
TimeCard card = MyAdapter.cards.get(position);
switch (view.getId()) {
case R.id.playButton:
startTimer(card);
trackPlayer[position] = 1; // Playing
break;
case R.id.editButton:
Intent intent = new Intent(context, TimeCardAdd.class);
intent.putExtra("cardPosition", position);
context.startActivity(intent);
//TODO: Finish the editing so we can modify the timer card
Toast.makeText(context, "Edit button has been pressed.", Toast.LENGTH_SHORT).show();
break;
case R.id.stopButton:
stopTimer(card);
trackPlayer[position] = 0; // Stopped
break;
case R.id.pauseButton:
pauseTimer(card);
trackPlayer[position] = 2; // Paused
break;
}
}
Now inside your onBindViewHolder, you need to change the button's visibility based on the trackPlayer values.
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.playButton.setOnClickListener(new TimeCardButton(context, holder.getAdapterPosition(), holder.buttons).checkStatus());
holder.editButton.setOnClickListener(new TimeCardButton(context, holder.getAdapterPosition(), holder.buttons).checkStatus());
holder.pauseButton.setOnClickListener(new TimeCardButton(context, holder.getAdapterPosition(), holder.buttons).checkStatus());
holder.stopButton.setOnClickListener(new TimeCardButton(context, holder.getAdapterPosition(), holder.buttons).checkStatus());
// Set the buttons visibility changes here.
if(playTrack[position] == 1) {
// Item in this position is being played
playButton.setVisibility(View.INVISIBLE);
editButton.setVisibility(View.INVISIBLE);
pauseButton.setVisibility(View.VISIBLE);
stopButton.setVisibility(View.VISIBLE);
} else if(playTrack[position] == 0) {
// Item in this position is not being played/stopped
playButton.setVisibility(View.VISIBLE);
editButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
stopButton.setVisibility(View.INVISIBLE);
} else if(playTrack[position] == 2) {
// Item in this position is paused
playButton.setVisibility(View.VISIBLE);
editButton.setVisibility(View.INVISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
stopButton.setVisibility(View.VISIBLE);
}
}
And remove the sendPlayTimeButtons function call from your startTimer function. I think you might consider removing the sendPlayTimeButtons function as well.
private void startTimer(TimeCard card) {
new Logger(TimeCardButton.class).debug("Play button was pressed");
if (!card.isTimeStarted()) {
card.setTimeStarted(true);
notifyDataSetChanged(); // Call notifyDataSetChanged instead here.
} else if(card.isTimerPaused() && card.isTimeStarted()) {
TimerTask.notifyUpdate();
card.setTimerPaused(false);
notifyDataSetChanged(); // Call notifyDataSetChanged instead here.
}
}
Hope you get the idea.

How can I store ArrayList<Class> in SharedPreferences to store game progress?

I'm new to android development and I am creating an android application that works like "4 Pics 1 Word" for my project. I'm having difficulties in storing ArrayList in SharedPreferences or in the internal storage of the android phone. The reason why is because I am randomizing the next activity using random generator and ArrayList. Any suggestions or ideas that my help my case? Thank you in advance! I've been stuck here for hours now.
This is my MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button btnStart;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// We are creating a list, which will store the activities that haven't been opened yet
ArrayList<Class> activityList = new ArrayList<>();
activityList.add(first.class);
activityList.add(second.class);
activityList.add(third.class);
activityList.add(fourth.class);
activityList.add(fifth.class);
Random generator = new Random();
int number = generator.nextInt(5) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
activity = first.class;
// We are adding the number of the activity to the list
activityList.remove(first.class);
break;
case 2:
activity = second.class;
activityList.remove(second.class);
break;
case 3:
activity = third.class;
activityList.remove(third.class);
break;
case 4:
activity = fourth.class;
activityList.remove(fourth.class);
break;
default:
activity = fifth.class;
activityList.remove(fifth.class);
break;
}
// We use intents to start activities
Intent intent = new Intent(getBaseContext(), activity);
// `intent.putExtra(...)` is used to pass on extra information to the next activity
intent.putExtra("ACTIVITY_LIST", activityList);
startActivity(intent);
}
}
And here's my first activity:
public class first extends AppCompatActivity implements View.OnClickListener{
EditText etAnswer;
Button btnGo;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
etAnswer = (EditText) findViewById(R.id.etAnswer);
btnGo = (Button) findViewById(R.id.btnGo);
btnGo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnGo:
String answer = etAnswer.getText().toString();
if(answer.equals("Jose Rizal") || answer.equals("jose rizal") || answer.equals("Rizal") || answer.equals("rizal") ){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("The famous Rizal monument in Luneta was not the work of a Filipino but a Swiss sculptor named Richard Kissling?" +
"Source: http://www.joserizal.ph/ta01.html");
dlgAlert.setTitle("Did you know that ...");
dlgAlert.setPositiveButton("Next",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ArrayList<Class> activityList = new ArrayList<>();
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("ACTIVITY_LIST");
if(activityList.size() == 0) {
Context context = getApplicationContext();
CharSequence last = "Congratulations! You just finished the game! Please wait for the next update!";
int durationFinal = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, last, durationFinal);
toast.show();
} else {
// Now, the random number is generated between 1 and however many
// activities we have remaining
Random generator = new Random();
int number = generator.nextInt(activityList.size()) + 1;
Class activity = null;
// Here, we are checking to see what the output of the random was
switch(number) {
case 1:
// We will open the first remaining activity of the list
activity = activityList.get(0);
// We will now remove that activity from the list
activityList.remove(0);
break;
case 2:
// We will open the second remaining activity of the list
activity = activityList.get(1);
activityList.remove(1);
break;
case 3:
// We will open the third remaining activity of the list
activity = activityList.get(2);
activityList.remove(2);
break;
case 4:
// We will open the fourth remaining activity of the list
activity = activityList.get(3);
activityList.remove(3);
break;
default:
// We will open the fifth remaining activity of the list
activity = activityList.get(4);
activityList.remove(4);
break;
}
// Note: in the above, we might not have 3 remaining activities, for example,
// but it doesn't matter because that case wouldn't be called anyway,
// as we have already decided that the number would be between 1 and the number of
// activities left.
// Starting the activity, and passing on the remaining number of activities
// to the next one that is opened
Intent intent = new Intent(getBaseContext(), activity);
intent.putExtra("ACTIVITY_LIST", activityList);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}else{
Context context = getApplicationContext();
CharSequence text = "Wrong! Try Again.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
break;
}
}
}
Okay, this is a horrible hack and I don't endorse it in any way, but since you are so close to finishing your app, I propose a workaround:
Instead of storing an ArrayList<Class> in your SharedPreferences (which is impossible), store a HashSet<String> containing the fully qualified names of your classes via putStringSet().
In order to get the String representations of the fully qualified names of your classes you need to call getName(), e.g. first.class.getName().
Then, you can get your Set<String> from SharedPreferences using getStringSet() and create a Class instance for each String in that set via Class.forName().

I want a central way to control my buttons

Hi I have 2 lines each with a name textfield, 2 buttons and a textfield to show the amount. There will be more lines later.
I want 1 button to add 1 to the amount and the other to decrease the amount by 1.
But I don't know how to get the ID from the button I press. I have gotten this far.
I hope someone can let me know. How I can get the indexvalue depending on which button is pressed.
public class MainActivity extends AppCompatActivity {
private ArrayList<Integer> ButtonUp;
private ArrayList<Integer> Amount;
private ArrayList<Integer> ButtonDown;
int ArrayIndex = 0;
int Value = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonUp();
Amount();
ButtonDown();
}
// ArrayList ButtonUp
public void ButtonUp(){
ButtonUp.add(R.id.Bup1);
ButtonUp.add(R.id.Bup2);
}
// ArrayList Amount
public void Amount(){
Amount.add(R.id.Aantal1);
Amount.add(R.id.Aantal2);
}
// ArrayList ButtonDown
public void ButtonDown() {
ButtonDown.add(R.id.Bdown1);
ButtonDown.add(R.id.Bdown2);
}
// Get position ArrayList on press
// Publish new Value
public void buttonPress(View v) {
switch (v.getId()) {
case R.id.Bup1:
SetAmountUp(id);
displayQuantity(Value);
break;
case R.id.Bup2:
SetAmountUp(R.id.Bup2);
displayQuantity(Value);
break;
case R.id.Bdown1:
SetAmountDown(R.id.Bdown1);
displayQuantity(Value);
break;
case R.id.Bdown2:
SetAmountDown(R.id.Bdown1);
displayQuantity(Value);
break;
}
}
public void SetAmountUp(int indexNumberUp){
Value = Amount.get(ButtonUp.indexOf(indexNumberUp));
Value++;
Amount.set(ArrayIndex,Value);
}
public void SetAmountDown(int indexNumberDown){
Value = Amount.get(ButtonDown.indexOf(indexNumberDown));
Value--;
Amount.set(ArrayIndex,Value);
}
// Publish number
private void displayQuantity(int NewAmount) {
int ID = Amount.get(ArrayIndex);
TextView quantityTextView = (TextView) findViewById(ID);
quantityTextView.setText(NewAmount);
}
}
In the layout, declare an unique id to each button, then add android:onClick="increment" to each button.
In your class, create the method
public void increment(View view) {
switch (view.getId()){
case R.id.yourbuttonid1:
// do what you whant
break;
case R.id.yourbuttonid2:
// do with second editext
break
// ....
}
}
Same approach to decrease method.
It will be much easier for you if you used a recyclerView for that

Android - Passing more variebles via intent makes app crash

So, here is the code from the main activity(the main screen,) if you click on play a random activity( a quiz question) will show up. The problem is that, i am trying to pass an integer, default score to question #1, where the score will be 5(it's the default).
if the user clicks on the wrong button, it will navigate the user to Question #2, and for Question #2, the score will be minus2, less than 2.
int defaultScore = 51;
// start Play Intent
public void onPlay(View view){
Random r = new Random();
int XML_random = r.nextInt(5)+1; // 5 different Quiz XML files
Intent startQuiz = new Intent();
switch(XML_random){
case 1:
startQuiz.setClass(view.getContext(), Quiz_1.class);
break;
case 2:
startQuiz.setClass(view.getContext(), Quiz_2.class);
break;
case 3:
startQuiz.setClass(view.getContext(), Quiz_3.class);
break;
case 4:
startQuiz.setClass(view.getContext(), Quiz_4.class);
break;
case 5:
startQuiz.setClass(view.getContext(), Quiz_5.class);
break;
} // end of the Random switch
startQuiz.putExtra("passScore", defaultScore);
startActivity(startQuiz);
}
So, next if a random activity is chosen, then it's score will be 5, because for the first question, I want the users to start with 5 as a start. So, here is an activty(Question #1) and if the user clicks on the wrong button then Question #2 will show up. And for this activity, the score will be minus 2. Because the user chose the wrong answer.
Question 1 - user clicks on the wrong button:
public class Quiz_1 extends Activity {
TextView textviewScore;
int current_score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_1);
textviewScore = (TextView) findViewById(R.id.q_result); // declaring the TextView
Bundle extras = getIntent().getExtras();
if (extras != null)
{
current_score = extras.getInt("passScore");
}
textviewScore.setText(String.valueOf(current_score));
} // end of onCreate
public void on_quiz_1_wrong(View view){ // button clicked the wrong answer
current_score = current_score - 2;
Intent quiz1 = new Intent(this, Quiz_2.class);
startActivity(quiz1);
quiz1.putExtra("passNewScore", current_score);
}
And here is Question #2, and for this activity i want the score to be minus 2.
public class Quiz_2 extends Activity {
TextView textviewScore;
int current_score = 0;
int getScore=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_2);
textviewScore = (TextView) findViewById(R.id.q_result); // declaring the TextView
Bundle extras = getIntent().getExtras();
if (extras != null)
{
current_score = extras.getInt("passScore");
getScore = extras.getInt("passNewScore");
}
current_score = current_score - getScore;
textviewScore.setText(String.valueOf(current_score));
} // end of onCreate
you must first put extra to your intent then start it.
quiz1.putExtra("passNewScore", current_score);
startActivity(quiz1);
You are not passing the value for key "passScore" in quiz1 and calling quiz2, so how can you expect to retrieve the value on "passScore" in quiz2 ?
Pass the value for key "passScore" in quiz1.java in this method on_quiz_1_wrong(View view)

Categories

Resources