I am learning how to make an android app, as my first project I'm trying to build a stupid game haha.
when I get to my second activity, The game runs as it has to (picture down)
http://i.imgur.com/BBllAJU.png?1
Than nothing changes, the score, the numbers, but all the toasts still coming.
package com.example.moshik.whatisbigger;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.DynamicLayout;
import android.text.Layout;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class NormalModeActivity1 extends AppCompatActivity {
int Score = 0;
boolean AnswerBig = false;
boolean AnswerEqual = false;
boolean AnswerSmall = false;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_normal_mode1);
Random rnd = new Random();
while (counter < 5) {
int Number1 = rnd.nextInt(99) + 1;
TextView X = (TextView) findViewById(R.id.XNumber);
String Xstring = String.valueOf(Number1);
X.setText(Xstring);
int Number2 = rnd.nextInt(99) + 1;
TextView Y = (TextView) findViewById(R.id.YNumber);
String Ystring = String.valueOf(Number2);
Y.setText(Ystring);
if (Number1 > Number2) {
AnswerBig = true;
}
if (Number1 == Number2) {
AnswerEqual = true;
}
if (Number1 < Number2) {
AnswerSmall = true;
}
findViewById(R.id.Bigger).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerBig) {
Toast.makeText(NormalModeActivity1.this, "(BIG)You are RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerBig = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(BIG)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
findViewById(R.id.Equal).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerEqual) {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerEqual = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
findViewById(R.id.Smaller).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerSmall)
{
Toast.makeText(NormalModeActivity1.this, "(Small)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerSmall = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Small)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
TextView score = (TextView) findViewById(R.id.ScoreDisplay);
String ScoreShow;
ScoreShow = String.valueOf(Score);
score.setText("Your Score Is: " + ScoreShow);
counter++;
if (counter > 5)
{
score.setText("ItsOver!!!");
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.moshik.whatisbigger.NormalModeActivity1">
<include layout="#layout/content_normal_mode1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:id="#+id/ScoreDisplay"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/XNumber"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/ScoreDisplay"
android:layout_toStartOf="#+id/ScoreDisplay"
android:textSize="20sp">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/YNumber"
android:layout_alignTop="#+id/XNumber"
android:layout_toRightOf="#+id/ScoreDisplay"
android:layout_toEndOf="#+id/ScoreDisplay"
android:textSize="20sp">
</TextView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Bigger"
android:layout_marginTop="121dp"
android:hint="#string/BIG"
android:layout_below="#+id/XNumber"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Equal"
android:layout_alignTop="#+id/Bigger"
android:layout_centerHorizontal="true"
android:hint="#string/EQUAL">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Smaller"
android:hint="#string/SMALL"
android:layout_alignTop="#+id/Equal"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
</Button>
Here is the layout and the activity itself.
Can you find what the problem here or what I miss?, thank you very much :)
You are never updating your score TextView. Change it to a class field first so it is easier to access in your callbacks.
private TextView score;
and then in your onCreate method:
score = (TextView) findViewById(R.id.ScoreDisplay);
Then update the text in each callback click listener after incrementing Score:
Score++;
score.setText("Your Score Is: " + Score);
Also, I would update your variable names to be more different as using Score for an int and score for a TextView is confusing.
Update Showing class field:
public class NormalModeActivity1 extends AppCompatActivity {
int Score = 0;
boolean AnswerBig = false;
boolean AnswerEqual = false;
boolean AnswerSmall = false;
int counter = 0;
TextView X;
TextView Y;
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_normal_mode1);
// set class fields
X = (TextView) findViewById(R.id.XNumber);
Y = (TextView) findViewById(R.id.YNumber);
score = (TextView) findViewById(R.id.ScoreDisplay);
Random rnd = new Random();
int Number1 = rnd.nextInt(99) + 1;
String Xstring = String.valueOf(Number1);
X.setText(Xstring);
int Number2 = rnd.nextInt(99) + 1;
String Ystring = String.valueOf(Number2);
Y.setText(Ystring);
if (Number1 > Number2) {
AnswerBig = true;
}
if (Number1 == Number2) {
AnswerEqual = true;
}
if (Number1 < Number2) {
AnswerSmall = true;
}
findViewById(R.id.Bigger).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerBig) {
Toast.makeText(NormalModeActivity1.this, "(BIG)You are RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerBig = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(BIG)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
findViewById(R.id.Equal).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerEqual) {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerEqual = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
findViewById(R.id.Smaller).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerSmall)
{
Toast.makeText(NormalModeActivity1.this, "(Small)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerSmall = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Small)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
String ScoreShow;
ScoreShow = String.valueOf(Score);
score.setText("Your Score Is: " + ScoreShow);
}
private void incrementAndCheckCounter() {
counter++;
if (counter > 5)
{
score.setText("ItsOver!!!");
}
}
}
Related
I am making one simple bank transfer Android application with Google voice input. So, basically, in my app I have created one method layoutclicked() for number of clicks on the layout. I have initialized numberOfclicks as 0 initially, so when user taps on the screen it increments. It will start voice input as well.
public void layoutClicked(View view)
{
if(IsInitialVoiceFinshed) {
numberOfClicks++;
listen();
}
}
I have created switch case statement for filling the input field, so like when case is 1, i.e user tap on the screen one time, then it will start voice input and user tell the details. It will set that text to that input field. And, again, in case 2 it will do another task.
If the user does not say anything in the first case, the field will be empty. And in case 2, they will go to another field. I want to fill that first input field. Can we achieve this by using for loop?
Here is my complete Java code
package org.tensorflow.lite.examples.detection;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
public class Banktransfer extends AppCompatActivity {
private TextToSpeech tts;
private TextView status;
private TextView To;
private TextView Subject;
private TextView To1;
private int numberOfClicks;
static String to;
float x1,x2;
private boolean IsInitialVoiceFinshed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bank_transfer);
IsInitialVoiceFinshed = false ;
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
tts.speak("Welcome to Bank transfer. tap on the screen , Tell me the IFSC code of bank",TextToSpeech.QUEUE_FLUSH,null);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
IsInitialVoiceFinshed=true;
}
}, 8500);
} else {
Log.e("TTS", "Initilization Failed!");
}
}
});
status = (TextView)findViewById(R.id.status);
To = (TextView) findViewById(R.id.to);
Subject = findViewById(R.id.subject);
To1 = (TextView) findViewById(R.id.to1);
numberOfClicks = 0;
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void layoutClicked(View view)
{
if(IsInitialVoiceFinshed) {
numberOfClicks++;
listen();
}
}
private void listen(){
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say something");
try {
startActivityForResult(i, 100);
} catch (ActivityNotFoundException a) {
Toast.makeText(Banktransfer.this, "Your device doesn't support Speech Recognition", Toast.LENGTH_SHORT).show();
}
}
#SuppressLint("SetTextI18n")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100&& IsInitialVoiceFinshed){
IsInitialVoiceFinshed = false;
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(result.get(0).contains("cancel"))
{
tts.speak("Transaction Cancelled!",TextToSpeech.QUEUE_FLUSH,null);
}
else {
switch (numberOfClicks) {
case 1:
To1.setText("");
String ifsc;
ifsc = result.get(0).replace(" ","");
char[] str=ifsc.toCharArray();
for(int i=0;i< str.length;i++){
To1.append(str[i]+"");
Toast.makeText(getApplicationContext(), To1.getText().toString(), Toast.LENGTH_SHORT).show();
}
if(!To1.getText().toString().isEmpty()) {
tts.speak("tap on the screen & say, account number to whom you want to transfer money? ",TextToSpeech.QUEUE_FLUSH,null);
}
break;
case 2:
to = result.get(0).replaceAll("[^\\d.]", "");
To.setText(to);
if(!to.isEmpty()) {
tts.speak("tap on the screen & say, how much money you want to transfer",TextToSpeech.QUEUE_FLUSH,null);
}
break;
case 3:
String amount;
amount = result.get(0).replaceAll("[^\\d.]", "");
Subject.setText(amount);
status.setText("confirm");
if(!amount.isEmpty()) {
tts.speak("Please Confirm the details , IFSC code is "+To1.getText().toString()+",Account number is: " + Arrays.toString(To.getText().toString().split("(?!^)")) + ". And Money that you want to transfer is ,: " + Subject.getText().toString() +"rupees"+ ",Tap on the screen and Speak Yes to confirm",TextToSpeech.QUEUE_FLUSH,null);
tts.speak(",swipe left to listen again, or say Yes to confirm or no to cancel the transaction",TextToSpeech.QUEUE_ADD,null);
}
break;
default:
if(result.get(0).equals("yes")) {
if (To.getText().toString().equals("")) {
if (Subject.getText().toString().equals("")) {
tts.speak("Details may be incorrect or incomplete, canceling the transaction",TextToSpeech.QUEUE_FLUSH,null);
final Handler h = new Handler(Looper.getMainLooper());
h.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(Banktransfer.this,MainActivity.class);
startActivity(i);
}
},8000);
}
} else {
status.setText("transferring money ");
tts.speak("transferring money please wait",TextToSpeech.QUEUE_FLUSH,null);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
status.setText("Amount transferred successfully.");
tts.speak("Amount transferred successfully.",TextToSpeech.QUEUE_FLUSH,null);
}
}, 6000);
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
finish();
Intent intent = new Intent(Banktransfer.this, MainActivity.class);
startActivity(intent);
tts.speak("you are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
}, 9000);
}
}
else if(result.get(0).contains("no")){
tts.speak("transaction cancelled",TextToSpeech.QUEUE_FLUSH,null);
To.setText("");
Subject.setText("");
IsInitialVoiceFinshed=true;
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
finish();
Intent intent = new Intent(Banktransfer.this,MainActivity.class);
startActivity(intent);
}
},3000);
}
}
}
}
else {
switch (numberOfClicks) {
case 1:
break;
case 2:
break;
default:
tts.speak("say yes to proceed the transaction or no to cancel the transaction",TextToSpeech.QUEUE_FLUSH,null);
break;
}
numberOfClicks--;
}
}
IsInitialVoiceFinshed=true;
}
public boolean onTouchEvent(MotionEvent touchEvent) {
switch (touchEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = touchEvent.getX();
break;
case MotionEvent.ACTION_UP:
x2 = touchEvent.getX();
if (x1 < x2) {
tts.speak("Please Confirm the details , IFSC code is "+To1.getText().toString()+"Account number is: " + Arrays.toString(To.getText().toString().split("(?!^)")) + ". And Money that you want to transfer is ,: " + Subject.getText().toString() +"rupees"+ ",Tap on the screen and Speak Yes to confirm",TextToSpeech.QUEUE_FLUSH,null);
tts.speak("swipe left to listen again, and say Yes to confirm or no to cancel the transaction",TextToSpeech.QUEUE_ADD,null);
break;
}
if (x1 > x2) {
break;
}
break;
}
return false;
}
public void onPause() {
if (tts != null) {
tts.stop();
}
super.onPause();
}
}
bank_transfer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#faa519"
android:orientation="vertical"
android:onClick = "layoutClicked"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="48dp"
android:background="#e8e8e7"
android:orientation="horizontal">
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_marginLeft="25dp"
android:text="Bank transfer"
android:textColor="#2582C5"
android:textSize="18sp"
android:textStyle="bold" />
</RelativeLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="30dp"
android:orientation="vertical">
<ImageView
android:layout_width="161dp"
android:layout_height="77dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:src="#drawable/bank" />
<TextView
android:id="#+id/to1"
android:layout_width="fill_parent"
android:layout_height="85dp"
android:layout_marginTop="70dp"
android:background="#f3f3f3"
android:paddingLeft="7dp"
android:paddingTop="7dp"
android:text="IFSC Code"
android:textColor="#4C4D4F" />
<TextView
android:id="#+id/to"
android:layout_width="fill_parent"
android:layout_height="85dp"
android:layout_marginTop="80dp"
android:background="#f3f3f3"
android:paddingLeft="7dp"
android:paddingTop="7dp"
android:text="Acc. no"
android:textColor="#4C4D4F" />
<TextView
android:id="#+id/subject"
android:layout_width="fill_parent"
android:layout_height="95dp"
android:layout_marginTop="95dp"
android:background="#f3f3f3"
android:text="Transfer money:- "
android:textColor="#4C4D4F" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
Instead of using switch statement You can use the codes below:
if(//){
}else if(//){
}else if(//){
}else if(//){
}else{
//
}
but switch statement, it's simpler and readable than the if and else if
This question already has answers here:
Java generating non-repeating random numbers
(12 answers)
Closed 1 year ago.
I'm currently working on this simple application to create a quiz of ten questions and make it random. This is my progress so far, the questions are random which is what I need, but the problem is the questions are repeating and I only need them to show once. Please help me to fix this bug.
activity_quiz.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:layout_marginBottom="40dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score"
android:textSize="20sp"
android:layout_alignParentLeft="true"
android:id="#+id/score_text"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/score"
android:layout_alignParentRight="true"
android:text="0"
android:textSize="20sp"/>
</RelativeLayout>
<TextView
android:id="#+id/question"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp"
android:padding="80dp"
android:text="Question"
android:textSize="15sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choice 1"
android:padding="8dp"
android:layout_marginBottom="24dp"
android:id="#+id/choice1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choice 2"
android:padding="8dp"
android:layout_marginBottom="24dp"
android:id="#+id/choice2" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choice 3"
android:padding="8dp"
android:layout_marginBottom="24dp"
android:id="#+id/choice3" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choice 4"
android:padding="8dp"
android:layout_marginBottom="24dp"
android:id="#+id/choice4" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/backQuiz"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="100dp"
android:text="Back to Table of Content"
/>
</RelativeLayout>
</LinearLayout>```
QuestionsLibrary.java:
public class QuestionsLibrary {
public String mQuestions [] = {
"Moses remains on the peak of Mt. Sinai for 40 days and 40 nights, then returns to the Israelites carrying what?",
"From the burning bush, how does God reply to Moses when Moses asks for his name?",
"Who was appointed as the first hereditary high priest of the Israelites??",
"God and Moses make two new tablets. The third Commandment states that one should remember what?",
"With the help of God and his staff, Moses leads the escape of the Israelites and parts which body of water?",
"What river was Moses sent down by his mother?",
"Where did Moses receive the Ten Commandments from God?",
"How many plagues did God send to Egypt?",
"Who is the Father of the Israelites?",
"Which of the following was NOT one of the 10 plagues on Egypt?"
};
private String mChoices [] [] = {
{"Donkey", "The Ten Commandments", "Food", "Laptop"},
{"Time is Gold", "I think; therefore I am", "I Am that I Am", "Revive me Jett"},
{"Matthew", "Aaron", "Joshua", "Polo"},
{"The Sabbath day", "Valentine Day", "Holy Day", "Judgement Day"},
{"Red Sea", "Pacific Ocean", "Nile lake", "Caribbean Sea"},
{"The Nile", "The Jordan", "The Euphrates", "The Tigris"},
{"Mt. Olympus", "Mt. Diablo", "Mt. Nebo", "Mt. Sinai"},
{"12", "13", "8", "10"},
{"Joshua", "Moses", "Abraham", "Jesus"},
{"Frogs", "Flies", "Darkness", "Floods"}
};
private String mCorrectAnswers [] = {"The Ten Commandments", "I Am that I Am", "Aaron", "The Sabbath day", "Red Sea","The Nile","Mt. Sinai","10","Abraham","Floods"};
public String getQuestion(int a) {
String question = mQuestions[a];
return question;
}
public String getChoice1(int a) {
String choice0 = mChoices[a] [0];
return choice0;
}
public String getChoice2(int a) {
String choice1 = mChoices[a] [1];
return choice1;
}
public String getChoice3(int a) {
String choice2 = mChoices[a] [2];
return choice2;
}
public String getChoice4(int a) {
String choice3 = mChoices[a] [3];
return choice3;
}
public String getCorrectAnswer(int a) {
String answer = mCorrectAnswers[a];
return answer;
}
}
QuizActivity.java:
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class QuizActivity extends AppCompatActivity {
TextView mScoreView,mQuestionView;
Button mButtonChoice1,mButtonChoice2,mButtonChoice3,mButtonChoice4,backQuiz;
private QuestionsLibrary mQuestions = new QuestionsLibrary();
private String mAnswer;
private int mScore = 0;
private int num = 0;
private int mQuestionsLenght = mQuestions.mQuestions.length;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_quiz);
r = new Random ();
mScoreView = (TextView) findViewById (R.id.score);
mQuestionView = (TextView) findViewById (R.id.question);
mButtonChoice1 = (Button) findViewById (R.id.choice1);
mButtonChoice2 = (Button) findViewById (R.id.choice2);
mButtonChoice3 = (Button) findViewById (R.id.choice3);
mButtonChoice4 = (Button) findViewById (R.id.choice4);
backQuiz = (Button) findViewById (R.id.backQuiz);
mScoreView.setText ("Score:" + mScore);
updateQuestion (1+r.nextInt(mQuestionsLenght));
mButtonChoice1.setOnClickListener (new View.OnClickListener (){
#Override
public void onClick(View v) {
if (mButtonChoice1.getText () == mAnswer){
mScore = mScore + 1;
mScoreView.setText ("Score:" + mScore);
updateScore(mScore);
updateQuestion (r.nextInt (mQuestionsLenght));
Toast.makeText (QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show ();
}else {
Toast.makeText (QuizActivity.this, "Wrong", Toast.LENGTH_SHORT).show ();
updateQuestion (r.nextInt (mQuestionsLenght));
}
}
});
mButtonChoice2.setOnClickListener (new View.OnClickListener (){
#Override
public void onClick(View v) {
if (mButtonChoice2.getText () == mAnswer){
mScore = mScore + 1;
mScoreView.setText ("Score:" + mScore);
updateScore(mScore);
updateQuestion (r.nextInt (mQuestionsLenght));
Toast.makeText (QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show ();
}else {
Toast.makeText (QuizActivity.this, "Wrong", Toast.LENGTH_SHORT).show ();
updateQuestion (r.nextInt (mQuestionsLenght));
}
}
});
mButtonChoice3.setOnClickListener (new View.OnClickListener (){
#Override
public void onClick(View v) {
if (mButtonChoice3.getText () == mAnswer){
mScore = mScore + 1;
mScoreView.setText ("Score:" + mScore);
updateScore(mScore);
updateQuestion (r.nextInt (mQuestionsLenght));
Toast.makeText (QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show ();
}else {
Toast.makeText (QuizActivity.this, "Wrong", Toast.LENGTH_SHORT).show ();
updateQuestion (r.nextInt (mQuestionsLenght));
}
}
});
mButtonChoice4.setOnClickListener (new View.OnClickListener (){
#Override
public void onClick(View v) {
if (mButtonChoice4.getText () == mAnswer){
mScore = mScore + 1;
mScoreView.setText ("Score:" + mScore);
updateScore(mScore);
updateQuestion (r.nextInt (mQuestionsLenght));
Toast.makeText (QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show ();
}else {
Toast.makeText (QuizActivity.this, "Wrong", Toast.LENGTH_SHORT).show ();
updateQuestion (r.nextInt (mQuestionsLenght));
}
}
});
backQuiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, tableofcontentActivity2.class);
startActivity(i);
}
});
}
private void updateQuestion(int num){
mQuestionView.setText (mQuestions.getQuestion (num));
mButtonChoice1.setText (mQuestions.getChoice1 (num));
mButtonChoice2.setText (mQuestions.getChoice2 (num));
mButtonChoice3.setText (mQuestions.getChoice3 (num));
mButtonChoice4.setText (mQuestions.getChoice4 (num));
mAnswer = mQuestions.getCorrectAnswer (num);
}
private void updateScore(int point) {
mScoreView.setText ("" + mScore);
}
Eager initialization
Create a shuffled list of questions
Iteratively use the questions based on the shuffled order
Shuffle
List<Integer> shuffledQuestions = IntStream.range(0, mQuestionsLenght)
.boxed().collect(Collectors.toList());
Collections.shuffle(shuffledQuestions);
Replace random.nextInt with iterative index
Instead of Random r, use currentIndex = 0
Instead of r.nextInt(mQuestionsLenght), use mQuestions.getQuestion(currentIndex++)
Lazy invalidation
Maintain a set of seen questions
Repeatedly generate r.nextInt if it is already in seen
use the generated question and mark as seen(add to set)
I want to create an app on that the idea is click on the button and changing an image. every time I click on the button an imageview change (dynamic imageview). I'm trying to do that but when I run the code below the first imageview is loaded and when I press the button, the first imageview jump to last imageview, ignoring two imageviews among them. What's wrong?
This is my code:
SEGUNDATELA. JAVA:
public class SegundaTela extends AppCompatActivity {
private Integer [] imagens = new Integer[]{R.drawable.tabeladia2, R.drawable.tabeladia3, R.drawable.tabeladia4, R.drawable.tabeladia5};
private RadioGroup radioGroup;
private RadioButton sim;
private RadioButton nao;
private Button proxima;
private ImageView img;
private int i=0;
private Integer [] dados= new Integer[4];
private int soma =0;
private int j;
private int inicio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_segunda_tela);
img = findViewById(R.id.imageView);
proxima = findViewById(R.id.proximaId);
radioGroup = findViewById(R.id.RadioGroupId);
sim = findViewById(R.id.simId);
nao = findViewById(R.id.naoId);
if (sim.isChecked()) {
inicio = 1;
} else if (nao.isChecked()) {
inicio = 0;
}
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i < 4) {
++i;
j = (i - 1);
switch (j) {
case 0:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 2;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
case 1:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 4;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
case 2:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 8;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
case 3:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 16;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
}
radioGroup.clearCheck();
} else {
soma = dados[0] + dados[1] + dados[2] + dados[3] + inicio;
Intent i = new Intent(SegundaTela.this, MainActivity.class);
i.putExtra("soma", soma);
startActivity(i);
}
}
});
}
}
SEGUNDATELA.MML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/proximaId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="proxima"
app:layout_constraintBottom_toTopOf="#+id/imageView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:scaleType="fitXY"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/tabeladia1" />
<RadioGroup
android:id="#+id/RadioGroupId"
android:layout_width="98dp"
android:layout_height="86dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/imageView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="#+id/simId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Sim" />
<RadioButton
android:id="#+id/naoId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Não" />
</RadioGroup>
Ever time you execute onClick() the entire for loop will execute. That is why. If you only want it to proceed one image at the time you need to find a different solution that allows you to keep state (knowing current image) between the "clicks".
You need to remove the for loop and increment everytime the button is clicked.
Use this if you want the images to be shown in a loop.
public class MainActivity extends AppCompatActivity {
private int [] imagens = {R.drawable.tabeladia2, R.drawable.tabeladia3,
R.drawable.tabeladia4, R.drawable.tabeladia5};
private Button proxima;
private ImageView img;
private Integer currentImg;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
proxima = findViewById(R.id.proximaId);
img = findViewById(R.id.imageView);
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentImg != null && currentImg < 3) {
currentImg++;
} else {
currentImg = 0;
}
img.setImageResource(imagens[currentImg]);
}
});
}
}
Use this if you don't want the images to be looped
public class MainActivity extends AppCompatActivity {
private int [] imagens = {R.drawable.tabeladia2, R.drawable.tabeladia3,
R.drawable.tabeladia4, R.drawable.tabeladia5};
private Button proxima;
private ImageView img;
private Integer currentImg;
private int[] intArray = new int[4];
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
proxima = findViewById(R.id.proximaId);
img = findViewById(R.id.imageView);
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentImg != null) {
if (currentImg < 3) {
currentImg++;
if(currentImg == 1){
intArray[1] = 2;
}else if(currentImg == 2){
intArray[2] = 4;
}else if(currentImg == 3){
intArray[3] = 8;}
img.setImageResource(imagens[currentImg]);
}else{
//handle last image reached condition
Toast.makeText(MainActivity.this, "Last image reached", Toast.LENGTH_SHORT).show();
}
} else {
currentImg = 0;
intArray[0] = 1;
img.setImageResource(imagens[currentImg]);
}
}
});
}
}
Using Case Statement and RadioButtons.
public class SegundaTela extends AppCompatActivity {
private Integer[] imagens = new Integer[]{R.drawable.tabeladia2, R.drawable.tabeladia3, R.drawable.tabeladia4, R.drawable.tabeladia5};
private RadioGroup radioGroup;
private RadioButton sim;
private RadioButton nao;
private Button proxima;
private ImageView img;
private Integer i;
private int soma = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_segunda_tela);
img = findViewById(R.id.imageView);
proxima = findViewById(R.id.proximaId);
radioGroup = findViewById(R.id.RadioGroupId);
sim = findViewById(R.id.simId);
nao = findViewById(R.id.naoId);
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!sim.isChecked() && !nao.isChecked()) {
Toast.makeText(SegundaTela.this, "Select an option", Toast.LENGTH_SHORT).show();
return;
}
if (i != null) {
if (i < 5) {
switch (i) {
case 0:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 2;
soma = soma + 2;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 1:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 4;
soma = soma + 4;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 2:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 8;
soma = soma + 8;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 3:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 16;
soma = soma + 16;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 4:
/*if (sim.isChecked()) {
//dados[j] = 16;
soma = soma + 32;
} else if (nao.isChecked()) {
//dados[j] = 0;
soma = soma + 0;
}*/
Intent i = new Intent(SegundaTela.this, MainActivity.class);
i.putExtra("soma", soma);
startActivity(i);
break;
}
++i;
Toast.makeText(SegundaTela.this, "soma: " + soma, Toast.LENGTH_SHORT).show();
radioGroup.clearCheck();
} /*else {
//soma = dados[0] + dados[1] + dados[2] + dados[3] + inicio;
Intent i = new Intent(SegundaTela.this, MainActivity.class);
i.putExtra("soma", soma);
startActivity(i);
}*/
}else {
if (sim.isChecked()) {
//inicio = 1;
soma = soma + 1;
} else if (nao.isChecked()) {
//inicio = 0;
soma = soma + 0;
}
i = 0;
radioGroup.clearCheck();
}
}
});
}
}
I have a problem with my setOnClickListener method for one of the buttons in my code. What basically happens is that I call a typeFinder inside the setOnClickListener method, but the first time I press the button the values do not get updated. I have used the debugger and from my understanding what happens is that even though the function is called, the program does not actually go through the function until after setOnClickListener, which means when I press the button the second time it has the right values to show from the previous button press. I have tried using TypesTask as well (as seen in commented part at the bottom of the page), but doing so resulted in the same outcome.
Here is the code for the class:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private DatabaseReference myRef;
private ArrayList<String> recipesList = new ArrayList<String>();
private String[] types = {"pizza", "ice cream", "sandwich", "salad", "steak"};
private void typeFinder(String type) {
myRef.orderByChild("type").equalTo(type).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String word = "";
boolean wordAdded = false;
String value = dataSnapshot.getValue().toString();
for (int i = 0; i < value.length(); i++) {
if (wordAdded == false) {
if (value.charAt(i) == '=') {
recipesList.add(word);
wordAdded = true;
word = "";
} else if (value.charAt(i) != '{' && value.charAt(i) != ',') {
if (word.length() == 0 && value.charAt(i) == ' ') {
} else {
word = word + value.charAt(i);
}
}
}
if (value.charAt(i) == '}')
if (i + 2 == value.length()) {
wordAdded = false;
break;
} else
wordAdded = false;
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
myRef = FirebaseDatabase.getInstance().getReference();
Button saladsB = (Button) findViewById(R.id.saladButton);
Button pizzaB = (Button) findViewById(R.id.pizzaButton);
Button iceCreamB = (Button) findViewById(R.id.iceCreamButton);
Button steakB = (Button) findViewById(R.id.steakButton);
Button sandwichB = (Button) findViewById(R.id.sandwichButton);
final TextView testTextView = (TextView) findViewById(R.id.test_text_view);
testTextView.setText(Integer.toString(recipesList.size()));
super.onCreate(savedInstanceState);
saladsB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// recipesList.clear();
// t.typeFinder("salad")
typeFinder("salad");
// new TypesTask().execute("salad");
String recipes = "";
for (int i = 0; i < recipesList.size(); i++) {
recipes = recipes + recipesList.get(i) + "\n";
}
testTextView.setText(recipes);
// Intent intent = new Intent(MainActivity.this, ListviewActivity.class);
// intent.putStringArrayListExtra("FOOD_LIST", recipesList);
// startActivity(intent);
}
});
}
/*
public class TypesTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
myRef = FirebaseDatabase.getInstance().getReference();
}
#Override
protected Void doInBackground(String... params) {
typeFinder(params[0]);
return null;
}
}
*/
}
Here is the xml for the page
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.thevash.recipes.MainActivity">
<LinearLayout
android:layout_width="0dp"
android:layout_height="810dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="458dp"
android:orientation="horizontal"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1">
<TextView
android:id="#+id/test_text_view"
android:layout_width="585dp"
android:layout_height="248dp"
android:layout_weight="1"
android:text="TextView"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="-377dp" />
</LinearLayout>
<Button
android:id="#+id/saladButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="Salads"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="5dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/pizzaButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="Pizzas"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="52dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/iceCreamButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="ice cream"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/pizzaButton"
app:layout_constraintTop_toBottomOf="#+id/pizzaButton"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/pizzaButton" />
<Button
android:id="#+id/steakButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="steaks"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/iceCreamButton"
app:layout_constraintTop_toBottomOf="#+id/iceCreamButton"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/iceCreamButton" />
<Button
android:id="#+id/sandwichButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="sandwiches"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/steakButton"
app:layout_constraintTop_toBottomOf="#+id/steakButton"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/steakButton" />
</android.support.constraint.ConstraintLayout>
you can do this using TypesTask but you need to modify TypesTask class like below
public class TypesTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
myRef = FirebaseDatabase.getInstance().getReference();
}
#Override
protected Void doInBackground(String... params) {
typeFinder(params[0]);
return null;
}
#Override
onPostExecute(Void result){
String recipes = "";
for (int i = 0; i < recipesList.size(); i++) {
recipes = recipes + recipesList.get(i) + "\n";
}
testTextView.setText(recipes);
}
}
and your onClick should be like this
saladsB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TypesTask().execute("salad");
}
});
As mentioned in the comments both of the answers provided work. I either had to add the UI update to the typeFinder function itself, or use AsyncTask to update the UI inside onPostExecute method. For the latter I had to put the program to sleep for one second after the line typeFinder(params[0]) to give it enough time to update the variables.
Your method in which you are building the reciepeList is an asynchronous call. You need to update the changes to Ui after the OnSuccess() call of EventListener. Relocate the Ui updation code to OnDataChange See the code below :
private void typeFinder(String type) {
myRef.orderByChild("type").equalTo(type).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String word = "";
boolean wordAdded = false;
String value = dataSnapshot.getValue().toString();
for (int i = 0; i < value.length(); i++) {
if (wordAdded == false) {
if (value.charAt(i) == '=') {
recipesList.add(word);
wordAdded = true;
word = "";
} else if (value.charAt(i) != '{' && value.charAt(i) != ',') {
if (word.length() == 0 && value.charAt(i) == ' ') {
} else {
word = word + value.charAt(i);
}
}
}
if (value.charAt(i) == '}')
if (i + 2 == value.length()) {
wordAdded = false;
break;
} else
wordAdded = false;
}
// Update the Ui Here
String recipes = "";
for (int i = 0; i < recipesList.size(); i++) {
recipes = recipes + recipesList.get(i) + "\n";
}
this.testTextView.setText(recipes);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
I have 9 buttons in an array and when I click a Button, the turn variable is set to the opposite boolean value to maintain turns.
When I run the app and click 3 X's or O's in all three rows it works and displays a toast message with the winner.
The problem is the columns: it only recognizes when I click 3 X's or O's in the 3rd column and displays a toast, but when I do the same with the first and second column, no toast/message is displayed.
The showWinner() method uses the determineWinner() method in order to display the message.
I need to find how to display the winner when they are in the 1st and 2nd columns.
my MainActivity:
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
//declaring instance variables to keep track of the button views and user turns
private Button[] btns;
private boolean turn = false;
private Button[][] btnsWin;
//creating an array of buttons in order to easily reference them
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create a toolbar and set it as the action bar
Toolbar myToolBar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolBar);
btns = new Button[9];
btnsWin = new Button[3][3];
int id = R.id.button1;
for(int i = 0; i < btns.length; i++)
{
btns[i] = (Button)findViewById(id);
id++;
}
id = R.id.button1;
for(int col = 0; col < btnsWin.length; col++)
for(int row = 0; row < btnsWin[0].length; row++)
{
btnsWin[col][row] = (Button)findViewById(id);
id++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem spinnerItem = menu.findItem(R.id.color_spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(spinnerItem);
spinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.colors_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
return true;
}
#Override
public void onClick(View v) {
//get a handle on the textview in the xml
switch (v.getId()) {
case R.id.button1:
//checks what turn the user is on and sets the text in the button to either an X or an O
//depending on the turn. Then it sets the turn to the opposite boolean value.
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button2:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button3:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button4:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button5:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button6:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button7:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button8:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button9:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
}
}
public void showWinner()
{
Toast toast1 = null;
if(determineWinner().equals("X is the winner"))
{
toast1 = Toast.makeText(getApplicationContext(), "X is the winner", Toast.LENGTH_SHORT);
toast1.show();
}
else if(determineWinner().equals("O is the winner"))
{
toast1 = Toast.makeText(getApplicationContext(), "O is the winner", Toast.LENGTH_SHORT);
toast1.show();
}
}
public void resetBtns()
{
for(int i = 0; i < btns.length; i++)
{
btns[i].setEnabled(true);
btns[i].setText(R.string.space);
}
}
public void disableBtns()
{
for(int j = 0; j < btns.length; j++)
{
btns[j].setText("");
btns[j].setEnabled(false);
}
}
public String determineWinner()
{
String winner = " ";
int xHorizontal = 0;
int oHorizontal = 0;
int xVertical = 0;
int oVertical = 0;
// checking for x's and o's vertically
for(int x = 0; x < 3; x++)
{
if ((btns[x]).getText().equals("X") && (btns[x+3]).getText().equals("X") && (btns[x+6]).getText().equals("X")) {
xVertical = 3;
break;
}
else if ((btns[x]).getText().equals("O") && (btns[x+3]).getText().equals("O") && (btns[x+6]).getText().equals("O")) {
oVertical = 3;
break;
}
}
// checking for x's and o's horizontally
for(int i = 0; i < 9; i++)
{
if ((btns[i]).getText().equals("X") && (btns[i+1]).getText().equals("X") && (btns[i+2]).getText().equals("X")) {
xHorizontal = 3;
break;
}
else if ((btns[i]).getText().equals("O") && (btns[i+1]).getText().equals("O") && (btns[i+2]).getText().equals("O")) {
oHorizontal = 3;
break;
}
else
i = i + 2;
}
if(oHorizontal == 3 || oVertical == 3)
{
winner = "O is the winner";
}
if(xHorizontal == 3 || xVertical == 3)
{
winner = "X is the winner";
}
return winner;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Toast toast;
switch(item.getItemId())
{
case R.id.color_spinner:
toast = Toast.makeText(getApplicationContext(), "Select which color for X's or O's", Toast.LENGTH_SHORT);
toast.show();
break;
case R.id.action_favorite:
resetBtns();
toast = Toast.makeText(getApplicationContext(), "Buttons have been reset", Toast.LENGTH_LONG);
toast.show();
break;
}
return true;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
switch(i)
{
case 0:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("X"))
btns[j].setTextColor(Color.BLACK);
break;
case 1:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("O"))
btns[j].setTextColor(Color.BLACK);
break;
case 2:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("X"))
btns[j].setTextColor(Color.MAGENTA);
break;
case 3:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("O"))
btns[j].setTextColor(Color.MAGENTA);
break;
case 4:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("X"))
btns[j].setTextColor(Color.CYAN);
break;
case 5:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("O"))
btns[j].setTextColor(Color.CYAN);
break;
}
}
}
my layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="edu.ncc.tictactoe.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
android:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<Button
android:id="#+id/button1"
android:layout_width="116sp"
android:layout_height="110sp"
android:layout_toLeftOf="#+id/button2"
android:layout_below="#id/my_toolbar"
android:textSize="35sp"
android:text="#string/space"
android:onClick="onClick" />
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:id="#+id/button2"
android:textSize="35sp"
android:text=""
android:layout_below="#+id/my_toolbar"
android:layout_centerHorizontal="true"
android:onClick="onClick"/>
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:layout_below="#id/my_toolbar"
android:id="#+id/button3"
android:textSize="35sp"
android:text="#string/space"
android:layout_toRightOf="#id/button2"
android:onClick="onClick"/>
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:layout_below="#id/button1"
android:layout_toLeftOf="#+id/button5"
android:id="#+id/button4"
android:textSize="35sp"
android:text="#string/space"
android:onClick="onClick"/>
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:id="#+id/button5"
android:textSize="35sp"
android:text="#string/space"
android:onClick="onClick"
android:layout_below="#+id/button2"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:id="#+id/button6"
android:textSize="35sp"
android:text="#string/space"
android:layout_below="#id/button3"
android:layout_toRightOf="#id/button5"
android:onClick="onClick"/>
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:layout_below="#id/button4"
android:layout_toLeftOf="#+id/button8"
android:id="#+id/button7"
android:textSize="35sp"
android:text="#string/space"
android:onClick="onClick"/>
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:id="#+id/button8"
android:textSize="35sp"
android:text="#string/space"
android:onClick="onClick"
android:layout_below="#+id/button5"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:id="#+id/button9"
android:textSize="35sp"
android:text="#string/space"
android:layout_toRightOf="#id/button8"
android:layout_below="#id/button6"
android:onClick="onClick"/>
</RelativeLayout>
You need to access your views differently. id++ cannot be guaranteed to go from button1 to button2.
So, try something like this
btns = new Button[9];
btnsWin = new Button[3][3];
for(int i = 0; i < btns.length; i++)
{
int resID = getResources().getIdentifier("button"+(i+1), "id", getPackageName());
Button b = (Button) findViewById(resId);
btns[i] = b;
// I think this math is right...
btnsWin[i / 3][i % 3] = b;
}
For more information see Android, getting resource ID from string?