Buttons in a tic tac toe app are only recognizing certain columns - java

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?

Related

Is there any other option rather that switch case statement?

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

Why is It happining this error when I run the app?

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();
}
}
});
}
}

Issue With Button setOnClickListener Function Call

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());
}
});
}

Application keeps Crashing

My application keeps on crashing, and I cannot figure out why. I am suspecting that there is something wrong with the getReactants() method because the button is working just fine and can display any other text I put in the beq.setText().
There are no errors in the logcat, the threads are simply suspended and my device says that the application is not responding, and says I can either wait or kill the app.
Here is my code.
Java
package me.finalproject.com.apchemchemolyapp;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.io.Serializable;
/**
* Created by Shishir on 6/9/2016.
*/
public class stoich_fragment extends Fragment implements View.OnClickListener, Serializable
{
View rootview;
int i = 0;
ArrayList<Integer> arr = new ArrayList<>();
ArrayList<String> elements = new ArrayList<>();
boolean getElements = true;
String s1;
String element = "";
EditText reactants;
TextView beq;
Button go;
int temp;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
rootview = inflater.inflate(R.layout.stoich_layout, container, false);
reactants = (EditText) rootview.findViewById(R.id.reactants);
go = (Button) rootview.findViewById(R.id.button);
go.setOnClickListener(this);
return rootview;
}
public void onClick(View v)
{
getReactants(s1);
beq = (TextView) rootview.findViewById(R.id.balanced_equation);
beq.setText(s1);
}
public void getReactants(String s)
{
String reactant = reactants.getText().toString();
//saying that reactants is null even after it went through the onCreateView method
String re = reactant.replaceAll("\\s+","");
while(getElements)
{
String let = re.substring(i, i+1);
if(let.compareTo(let.toLowerCase()) > 0)
{
element += let;
if(i == re.length()-1 || i == re.length())
{
elements.add(element);
if(re.substring(re.length()-1).equals("2")||re.substring(re.length()-1).equals("3")||re.substring(re.length()-1).equals("4")||re.substring(re.length()-1).equals("5")||re.substring(re.length()-1).equals("6")||re.substring(re.length()-1).equals("7")||re.substring(re.length()-1).equals("8")||re.substring(re.length()-1).equals("9"))
{
arr.add(Integer.parseInt(re.substring(re.length()-1)));
}
else
{
arr.add(1);
elements.add(re.substring(re.length()-1));
arr.add(1);
}
getElements = false;
}
else if(re.substring(i+1, i+2).compareTo(re.substring(i+1, i+2).toLowerCase()) != 0)
{
if(!re.substring(i+1,i+2).equals("2")||!re.substring(i+1,i+2).equals("3")||!re.substring(i+1,i+2).equals("4")||!re.substring(i+1,i+2).equals("5")||!re.substring(i+1,i+2).equals("6")||!re.substring(i+1,i+2).equals("7")||!re.substring(i+1,i+2).equals("8")||!re.substring(i+1,i+2).equals("9"))
{
temp = 1;
arr.add(temp);
}
}
}
else if(let.compareTo(let.toLowerCase()) == 0)
{
element += let;
if(i == re.length()-1 || i == re.length())
{
elements.add(element);
if(re.substring(re.length()-1).equals("2")||re.substring(re.length()-1).equals("3")||re.substring(re.length()-1).equals("4")||re.substring(re.length()-1).equals("5")||re.substring(re.length()-1).equals("6")||re.substring(re.length()-1).equals("7")||re.substring(re.length()-1).equals("8")||re.substring(re.length()-1).equals("9"))
{
arr.add(Integer.parseInt(re.substring(re.length()-1)));
}
else
{
arr.add(1);
elements.add(re.substring(re.length()-1));
arr.add(1);
}
getElements = false;
}
else if(!re.substring(i+1,i+2).equals("2")||re.substring(i+1,i+2).equals("3")||re.substring(i+1,i+2).equals("4")||re.substring(i+1,i+2).equals("5")||re.substring(i+1,i+2).equals("6")||re.substring(i+1,i+2).equals("7")||re.substring(i+1,i+2).equals("8")||re.substring(i+1,i+2).equals("9"))
{
temp = 1;
arr.add(temp);
}
}
else if (let.equals("2")||let.equals("3")||let.equals("4")||let.equals("5")||let.equals("6")||let.equals("7")||let.equals("8")||let.equals("9"))
{
temp = Integer.parseInt(let);
arr.add(temp);
elements.add(element);
element = "";
}
i++;
if(i == re.length()+1)
{
getElements = false;
}
}
// displays the elements isolated on the reactant side
// to test to make sure my logic works
for(int a = 0; a<elements.size(); a++)
{
s += (elements.get(a) + " : " + arr.get(a) + "\n");
}
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/reactants"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="95dp"
android:textSize="20sp"
android:inputType="text" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/products"
android:layout_alignBottom="#+id/reactants"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textSize="20sp"
android:inputType="text" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/balanced_equation"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="30sp" />
<!--should make text bold and black-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/beq"
android:id="#+id/title"
android:textSize="35sp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textStyle = "bold"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="45dp" />
</RelativeLayout>
This messages means your application is doing too much work on it's main thread (UI Tread).
I suggest to put getReactants() in an AsyncTask and show the result when all proccesses finished without blocking the main thread.
Looking at your code, it seems that you probably have an infinite loop. Try to set your getElements flag to false at the end of your while loop to make sure it will be executed. Must be something like:
while(getElements)
{
String let = re.substring(i, i+1);
if(let.compareTo(let.toLowerCase()) > 0)
{
element += let;
if(re.substring(i+1, i+2).compareTo(re.substring(i+1, i+2).toLowerCase()) != 0)
{
if(!re.substring(i+1,i+2).equals("2")||re.substring(i+1,i+2).equals("3")||re.substring(i+1,i+2).equals("4")||re.substring(i+1,i+2).equals("5")||re.substring(i+1,i+2).equals("6")||re.substring(i+1,i+2).equals("7")||re.substring(i+1,i+2).equals("8")||re.substring(i+1,i+2).equals("9"))
{
temp = 1;
arr.add(temp);
}
}
i++;
}
else if(let.compareTo(let.toLowerCase()) == 0)
{
element += let;
if(!re.substring(i+1,i+2).equals("2")||re.substring(i+1,i+2).equals("3")||re.substring(i+1,i+2).equals("4")||re.substring(i+1,i+2).equals("5")||re.substring(i+1,i+2).equals("6")||re.substring(i+1,i+2).equals("7")||re.substring(i+1,i+2).equals("8")||re.substring(i+1,i+2).equals("9"))
{
temp = 1;
arr.add(temp);
}
i++;
}
else if (let.equals("2")||let.equals("3")||let.equals("4")||let.equals("5")||let.equals("6")||let.equals("7")||let.equals("8")||let.equals("9"))
{
temp = Integer.parseInt(let);
arr.add(temp);
elements.add(element);
element = "";
}
if(i == re.length())
{
getElements = false;
}
// must have an else statement here or else you will have an infinite loop if your condition is always false.
}
You are not incrementing i in some cases, you should have to move i++ to the end of your while to avoid an infinite loop
i has to be incremented in all cases, consider something like this:
if () {
`enter code here`
}
else if () {
`enter code here`
}
else if () {
`enter code here`
}
i++;
if(i == re.length()) {
getElements = false;
}

[Android-Java]Learning android, layout work only once

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!!!");
}
}
}

Categories