java.lang.ArrayIndexOutOfBoundsException: length=10; index=10 - java

I have started to work on app that has multiple choice questions, but when I try to run my app it says:
java.lang.ArrayIndexOutOfBoundsException: length=10; index=10
I know what it says but I don't understand where is the problem.
here's my code:
TextView tvq;
InputStream is;
String[] question = new String[10];
ImageButton[] buttons = new ImageButton[4];
int[] check = {-1, -1 ,-1};
int[] answersid = {R.drawable.israelflag, R.drawable.spainflag, R.drawable.franceflag, R.drawable.greeceflag, R.drawable.egyptflag, R.drawable.unitedstatesflag, R.drawable.brazilflag, R.drawable.japanflag, R.drawable.turkeyflag, R.drawable.iraqflag};
int i, randombutton, correctanswerid ,a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trivia);
buttons[0] = (ImageButton) findViewById(R.id.im1);
buttons[0].setOnClickListener(this);
buttons[1] = (ImageButton) findViewById(R.id.im2);
buttons[1].setOnClickListener(this);
buttons[2] = (ImageButton) findViewById(R.id.im3);
buttons[2].setOnClickListener(this);
buttons[3] = (ImageButton) findViewById(R.id.im4);
buttons[3].setOnClickListener(this);
tvq = (TextView) findViewById(R.id.tvq);
try {
setQuestion();
} catch (IOException e) {
e.printStackTrace();
}
game();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_trivia, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void setQuestion() throws IOException {
int z = 0;
String st = "";
is = this.getResources().openRawResource(R.raw.questions);
InputStreamReader isr1 = new InputStreamReader(is);
BufferedReader br1 = new BufferedReader(isr1);
while ((st = br1.readLine()) != null) {
question[z] = st;
z++;
}
is.close();
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.im1) {
if (R.id.im1 == correctanswerid)
Toast.makeText(this, "correct", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "incorrect", Toast.LENGTH_LONG).show();
game();
}
if (id == R.id.im2) {
if (R.id.im2 == correctanswerid)
Toast.makeText(this, "correct", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "incorrect", Toast.LENGTH_LONG).show();
game();
}
if (id == R.id.im3) {
if (R.id.im3 == correctanswerid)
Toast.makeText(this, "correct", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "incorrect", Toast.LENGTH_LONG).show();
game();
}
if (id == R.id.im4) {
if ( R.id.im4 == correctanswerid)
Toast.makeText(this, "correct", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "incorrect", Toast.LENGTH_LONG).show();
game();
}
}
public void game()
{
i = (int) (8 * Math.random());
tvq.setText(question[i]);
randombutton = (int) (3 * Math.random());
buttons[randombutton].setImageResource(answersid[i]);
correctanswerid = buttons[randombutton].getId();
ImageButton temp = buttons[randombutton];
buttons[randombutton] = buttons[buttons.length-1];
for (int s = 0; s < buttons.length - 1; s++) {
a = (int) (9 * Math.random());
for (int k = 0; k < check.length ; k++) {
if (check[k] == a || a == i ) {
a = (int) (9 * Math.random());
while (check[k] == i || a == 1)
a = (int) (9 * Math.random());
}
}
check[s] = a;
buttons[s].setImageResource(answersid[a]);
}
}
}
here's my raw's file:
Israel?
Spain?
France?
Greece?
Egypt?
United States?
Brazil?
Japan?
Turkey?
Iraq?
Thanks for help! (sorry for my bad English)

The problem is with the question array.
String[] question = new String[10];
Here your value for z is exceeding 9, the max index of your question array.
while ((st = br1.readLine()) != null) {
question[z] = st;
z++;
}
You need to stop it going past 9. Like this:
while (((st = br1.readLine()) != null) && (z < 10)) {

Related

Android studio parcel size error then java.lang.IllegalStateException: Could not execute method for android:onClick

public class MainActivity extends AppCompatActivity {
/* access modifiers changed from: private */
public int choosingUriFor;
private int playTime;
/* access modifiers changed from: private */
public Uri playerURI1;
/* access modifiers changed from: private */
public Uri playerURI2;
ActivityResultLauncher<String> startGallery = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
/* JADX WARNING: type inference failed for: r0v0, types: [android.content.Context, edu.miami.cs.geoff.tictactoc.MainActivity] */
public void onActivityResult(Uri resultUri) {
if (resultUri != null) {
Drawable convertURIToDrawable = MainActivity.convertURIToDrawable(MainActivity.this, resultUri);
Drawable image = convertURIToDrawable;
if (convertURIToDrawable == null) {
return;
}
if (MainActivity.this.choosingUriFor == 1) {
((Button) MainActivity.this.findViewById(R.id.player_image1)).setForeground(image);
Uri unused = MainActivity.this.playerURI1 = resultUri;
return;
}
((Button) MainActivity.this.findViewById(R.id.player_image2)).setForeground(image);
Uri unused2 = MainActivity.this.playerURI2 = resultUri;
}
}
});
ActivityResultLauncher<Intent> startPlaying = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
public void onActivityResult(ActivityResult result) {
int winner;
RatingBar winnerBar;
if (result.getResultCode() == -1 && (winner = result.getData().getIntExtra("edu.miami.cs.geoff.tictactoc.winner", 0)) > 0) {
if (winner == 1) {
winnerBar = (RatingBar) MainActivity.this.findViewById(R.id.player_score1);
} else {
winnerBar = (RatingBar) MainActivity.this.findViewById(R.id.player_score2);
}
winnerBar.setRating(winnerBar.getRating() + 1.0f);
if (winnerBar.getRating() == ((float) winnerBar.getNumStars())) {
MainActivity.this.findViewById(R.id.start_game_button).setVisibility(View.INVISIBLE);
}
}
}
});
private double startSplit = 0.5d;
/* access modifiers changed from: protected */
public void onCreate(Bundle savedInstanceState) {
MainActivity.super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.playTime = getResources().getInteger(R.integer.medium_ms);
}
/* JADX WARNING: type inference failed for: r7v0, types: [android.content.Context, edu.miami.cs.geoff.tictactoc.MainActivity] */
public void myClickHandler(View view) {
int starter;
switch (view.getId()) {
case R.id.playing_image1:
this.choosingUriFor = 1;
this.startGallery.launch("image/*");
return;
case R.id.playing_image2:
this.choosingUriFor = 2;
this.startGallery.launch("image/*");
return;
case R.id.start_game_button:
Intent playActivity = new Intent(this, TicTacTocPlay.class);
playActivity.putExtra("edu.miami.cs.geoff.tictactoc.player_name1", getPlayerName(R.id.player_name1));
playActivity.putExtra("edu.miami.cs.geoff.tictactoc.player_image1", this.playerURI1);
playActivity.putExtra("edu.miami.cs.geoff.tictactoc.player_name2", getPlayerName(R.id.player_name2));
playActivity.putExtra("edu.miami.cs.geoff.tictactoc.player_image2", this.playerURI2);
playActivity.putExtra("edu.miami.cs.geoff.tictactoc.play_time", this.playTime);
double random = Math.random();
double d = this.startSplit;
if (random > d) {
starter = 2;
this.startSplit = d + 0.1d;
} else {
starter = 1;
this.startSplit = d - 0.1d;
}
playActivity.putExtra("edu.miami.cs.geoff.tictactoc.go_first", starter);
this.startPlaying.launch(playActivity);
return;
default:
return;
}
}
private String getPlayerName(int playerId) {
String name = ((EditText) findViewById(playerId)).getText().toString();
if (name != null && !name.equals("")) {
return name;
}
if (playerId == R.id.player_name1) {
return getResources().getString(R.string.default_name_1);
}
return getResources().getString(R.string.default_name_2);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.score_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.play_fast_item:
this.playTime = getResources().getInteger(R.integer.fast_ms);
return true;
case R.id.play_medium_item:
this.playTime = getResources().getInteger(R.integer.medium_ms);
return true;
case R.id.play_slow_item:
this.playTime = getResources().getInteger(R.integer.slow_ms);
return true;
case R.id.play_flash_item:
this.playTime = getResources().getInteger(R.integer.flash_ms);
return true;
case R.id.reset_item:
((RatingBar) findViewById(R.id.player_score1)).setRating(0.0f);
((RatingBar) findViewById(R.id.player_score2)).setRating(0.0f);
findViewById(R.id.start_game_button).setVisibility(View.VISIBLE);
return true;
default:
return MainActivity.super.onOptionsItemSelected(item);
}
}
public static Drawable convertURIToDrawable(Context context, Uri myURI) {
try {
return Drawable.createFromStream(context.getContentResolver().openInputStream(myURI), myURI.toString());
} catch (Exception e) {
return null;
}
}
}
Above is the MainActivity in AndroidStudio. I got parcel size error first now I got On click error while trying to debug. I'm so lost. I assume the error is in the TicTacTocPLay class especially in the runnable and run method. But i still havent been able to pinpoint the error. So, in the main method there is a play button which should direct to the second activity which is the TicTacTocPlay class. In the emulator the app crashes when I press play.
public class TicTacTocPlay extends AppCompatActivity {
private int[][] board = ((int[][]) Array.newInstance(int.class, new int[]{3, 3}));
/* access modifiers changed from: private */
public Handler myHandler = new Handler();
/* access modifiers changed from: private */
public final Runnable myProgresser = new Runnable() {
private int whoseTurnLast = 0;
public void run() {
if (this.whoseTurnLast != TicTacTocPlay.this.whoseTurn) {
TicTacTocPlay.this.myHandler.removeCallbacks(TicTacTocPlay.this.myProgresser);
TicTacTocPlay.this.playTimer.setProgress(TicTacTocPlay.this.playTime);
this.whoseTurnLast = TicTacTocPlay.this.whoseTurn;
} else {
TicTacTocPlay.this.playTimer.setProgress(TicTacTocPlay.this.playTimer.getProgress() - TicTacTocPlay.this.playClickTime);
}
if (TicTacTocPlay.this.playTimer.getProgress() == 0) {
TicTacTocPlay ticTacTocPlay = TicTacTocPlay.this;
int unused = ticTacTocPlay.whoseTurn = (ticTacTocPlay.whoseTurn % 2) + 1;
TicTacTocPlay.this.startPlayer();
} else if (!TicTacTocPlay.this.myHandler.postDelayed(TicTacTocPlay.this.myProgresser, (long) TicTacTocPlay.this.playClickTime)) {
Log.e("ERROR", "Cannot postDelayed");
}
}
};
private int numberOfPlays;
/* access modifiers changed from: private */
public int playClickTime;
/* access modifiers changed from: private */
public int playTime;
/* access modifiers changed from: private */
public ProgressBar playTimer;
private Drawable[] playerImages = new Drawable[2];
private String[] playerNames = new String[2];
/* access modifiers changed from: private */
public int whoseTurn;
/* access modifiers changed from: protected */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tic_tac_toc_play);
initializeGame(getIntent());
startPlayer();
}
/* JADX WARNING: type inference failed for: r4v0, types: [android.content.Context, edu.miami.cs.geoff.tictactoc.TicTacTocPlay] */
private void initializeGame(Intent dataFromLaunch) {
this.playerNames[0] = dataFromLaunch.getStringExtra("edu.miami.cs.geoff.tictactoc.player_name1");
this.playerNames[1] = dataFromLaunch.getStringExtra("edu.miami.cs.geoff.tictactoc.player_name2");
this.playerImages[0] = MainActivity.convertURIToDrawable(this, (Uri) dataFromLaunch.getParcelableExtra("edu.miami.cs.geoff.tictactoc.player_image1"));
this.playerImages[1] = MainActivity.convertURIToDrawable(this, (Uri) dataFromLaunch.getParcelableExtra("edu.miami.cs.geoff.tictactoc.player_image2"));
setButton(R.id.playing_image1, 1);
setButton(R.id.playing_image2, 2);
this.whoseTurn = dataFromLaunch.getIntExtra("edu.miami.cs.geoff.tictactoc.go_first", 0);
int intExtra = dataFromLaunch.getIntExtra("edu.miami.cs.geoff.tictactoc.play_time", 0);
this.playTime = intExtra;
this.playClickTime = intExtra / 20;
ProgressBar progressBar = (ProgressBar) findViewById(R.id.play_time);
this.playTimer = progressBar;
progressBar.setMax(this.playTime);
this.numberOfPlays = 0;
}
/* access modifiers changed from: private */
public void startPlayer() {
Button watcherButton;
Button playerButton;
if (this.whoseTurn == 1) {
playerButton = (Button) findViewById(R.id.playing_image1);
watcherButton = (Button) findViewById(R.id.playing_image2);
} else {
playerButton = (Button) findViewById(R.id.playing_image2);
watcherButton = (Button) findViewById(R.id.playing_image1);
}
playerButton.setVisibility(View.VISIBLE);
watcherButton.setVisibility(View.INVISIBLE);
((TextView) findViewById(R.id.player_name)).setText(this.playerNames[this.whoseTurn - 1]);
this.myProgresser.run();
}
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.Button00:
setButtonAndPlay(0, 0, view.getId());
return;
case R.id.Button01:
setButtonAndPlay(0, 1, view.getId());
return;
case R.id.Button02:
setButtonAndPlay(0, 2, view.getId());
return;
case R.id.Button10:
setButtonAndPlay(1, 0, view.getId());
return;
case R.id.Button11:
setButtonAndPlay(1, 1, view.getId());
return;
case R.id.Button12:
setButtonAndPlay(1, 2, view.getId());
return;
case R.id.Button20:
setButtonAndPlay(2, 0, view.getId());
return;
case R.id.Button21:
setButtonAndPlay(2, 1, view.getId());
return;
case R.id.Button22:
setButtonAndPlay(2, 2, view.getId());
return;
default:
return;
}
}
/* access modifiers changed from: package-private */
public void setButtonAndPlay(int row, int column, int playedButtonId) {
if (this.board[row][column] == 0) {
this.numberOfPlays++;
setButton(playedButtonId, this.whoseTurn);
this.board[row][column] = this.whoseTurn;
if (!endOfGame(row, column)) {
this.whoseTurn = (this.whoseTurn % 2) + 1;
startPlayer();
}
}
}
private void setButton(int buttonId, int playerIndex) {
Log.i("DEBUG", "Setting button for player " + playerIndex);
if (this.playerImages[playerIndex - 1] != null) {
Log.i("DEBUG", "Setting button for player " + playerIndex + " to an image");
findViewById(buttonId).setForeground(this.playerImages[playerIndex + -1]);
} else if (playerIndex == 1) {
Log.i("DEBUG", "Setting button for player 1 to RED");
findViewById(buttonId).setForeground(ResourcesCompat.getDrawable(getResources(), R.drawable.red_button, (Resources.Theme) null));
} else {
Log.i("DEBUG", "Setting button for player 2 to GREEN");
findViewById(buttonId).setForeground(ResourcesCompat.getDrawable(getResources(), R.drawable.green_button, (Resources.Theme) null));
}
}
private boolean endOfGame(int row, int column) {
int winner;
int antiDiagonalWin = 0;
int diagonalWin = 0;
int columnWin = 0;
int rowWin = 0;
for (int index = 0; index < 3; index++) {
int[][] iArr = this.board;
int i = iArr[row][index];
int i2 = this.whoseTurn;
if (i == i2) {
rowWin++;
}
if (iArr[index][column] == i2) {
columnWin++;
}
if (iArr[index][index] == i2) {
diagonalWin++;
}
if (iArr[index][2 - index] == i2) {
antiDiagonalWin++;
}
}
if (rowWin == 3 || columnWin == 3 || diagonalWin == 3 || antiDiagonalWin == 3) {
winner = this.whoseTurn;
} else if (this.numberOfPlays == 9) {
winner = 0;
} else {
winner = -1;
}
if (winner < 0) {
return false;
}
Intent returnIntent = new Intent();
returnIntent.putExtra("edu.miami.cs.geoff.tictactoc.winner", winner);
setResult(-1, returnIntent);
finish();
return true;
}
/* access modifiers changed from: protected */
public void onDestroy() {
TicTacTocPlay.super.onDestroy();
this.myHandler.removeCallbacks(this.myProgresser);
}
}

SQL of union Tables second table displays empty values onItemClick in listview

I am new to android and I'm developing a dictionary with multiple languages joined in one listview basically I'm trying to do a search all from all tables but if I clicked a word that has on table2 it displays an empty word and definition in the fragment.
This is from DbHelperClass
public Word getWordForAll(String word, int dicType) {
String tableName1 = getAllTableName1(dicType);
String tableName2 = getAllTableName2(dicType);
String q = "SELECT * FROM "+ tableName1 +" WHERE word = ? UNION SELECT * FROM " + tableName2 + " WHERE word = ?";
Cursor result = mDB.rawQuery(q, new String[]{word});
Word word1 = new Word();
while (result.moveToNext()) {
word1.word = result.getString(result.getColumnIndex(COL_WORD));
word1.definition = result.getString(result.getColumnIndex(COL_DEFINITION));
}
return word1;
}
public String getTableName(int dicType) {
String tableName = "";
if (dicType == R.id.language1) {
tableName = lang1;
} else if (dicType == R.id.language2) {
tableName = lang2;
}
return tableName;
}
//same for tableName2
public String getAllTableName1(int dicType) {
String tableName1 = "";
if (dicType == R.id.action_all) {
tableName1 = lang1;
}
return tableName1;
}
This is from the definition fragment
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
tvWord = (TextView) view.findViewById(R.id.tvWord);
tvDefinition = (TextView) view.findViewById(R.id.tvDefinition);
//here mDicType is integer value from onOptionItemSelected in MainActivity
if (mDicType == R.id.action_all){
final Word word = mDBHelper.getWordForAll(value, mDicType);
tvWord.setText(word.word);
tvDefinition.setText(word.definition);
Word bookmarkWord = mDBHelper.getWordFromBookmark(value);
int isMark = bookmarkWord == null ? 0 : 1;
btnBookmark.setTag(isMark);
int icon = bookmarkWord == null ? R.drawable.bookmark:R.drawable.bookmarked;
btnBookmark.setImageResource(icon);
btnBookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = (int) btnBookmark.getTag();
if (i == 0){
btnBookmark.setImageResource(R.drawable.bookmarked);
btnBookmark.setTag(1);
mDBHelper.addBookmark(word);
}else if (i == 1){
btnBookmark.setImageResource(R.drawable.bookmark);
btnBookmark.setTag(0);
mDBHelper.removeBookmark(word);
}
}
});
} else {
final Word word = mDBHelper.getWord(value,mDicType);
tvWord.setText(word.word);
tvDefinition.setText(word.definition);
Word bookmarkWord = mDBHelper.getWordFromBookmark(value);
int isMark = bookmarkWord == null ? 0 : 1;
btnBookmark.setTag(isMark);
int icon = bookmarkWord == null ? R.drawable.bookmark:R.drawable.bookmarked;
btnBookmark.setImageResource(icon);
btnBookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = (int) btnBookmark.getTag();
if (i == 0){
btnBookmark.setImageResource(R.drawable.bookmarked);
btnBookmark.setTag(1);
mDBHelper.addBookmark(word);
}else if (i == 1){
btnBookmark.setImageResource(R.drawable.bookmark);
btnBookmark.setTag(0);
mDBHelper.removeBookmark(word);
}
}
});
}
}
This is from my Main Activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.language1) {
Global.saveState(this, "dic_type", String.valueOf(id));
ArrayList<String> source = dbHelper.getWord(id);
dictionaryFragment.resetDataSource(source);
return true;
} else if (id == R.id.language2) {
Global.saveState(this, "dic_type", String.valueOf(id));
ArrayList<String> source = dbHelper.getWord(id);
dictionaryFragment.resetDataSource(source);
return true;
} else if (id == R.id.action_all) {
Global.saveState(this, "dic_type", String.valueOf(id));
ArrayList<String> source = dbHelper.getWordAll(id);
dictionaryFragment.resetDataSource(source);
return true;
}
return super.onOptionsItemSelected(item);
}
And on onCreateOptionsMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
menuSetting = menu.findItem(R.id.action_settings);
String id = Global.getState(this, "dic_type");
if (id != null)
onOptionsItemSelected(menu.findItem(Integer.valueOf(id)));
else{
ArrayList<String> source = dbHelper.getWord(R.id.language1);
dictionaryFragment.resetDataSource(source);
}
return true;
}

How to make logic for n input in tictactoe game

i made the tictactoe game using dynamic layout and applied with logic of 3*3 matrix,if i enter 3 in input so it will make 3*3 matrix, if i will enter 4 in input so it will create 4*4 matrix,i have already make the logic for 3*3 matrix so now i want to make logic for tictactoe which can be applicable for all input.
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
GridLayout gridLayout;
LinearLayout linear;
FrameLayout frameLayout;
ArrayList<Button> buttons = new ArrayList<>();
Boolean player1 = true;
int turn, n;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.res, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int i1 = item.getItemId();
if (i1 == R.id.reset) {
resetBoard();
Toast.makeText(this, "game reset", Toast.LENGTH_SHORT).show();
} else if (i1 == R.id.newgame) {
resetgame();
Toast.makeText(this, "new game", Toast.LENGTH_SHORT).show();
} else if (i1 == R.id.homebtn) {
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
private void resetgame() {
resetBoard();
;
}
private void resetBoard() {
for (int i = 0; i < n * n; i++) {
buttons.get(i).setText("");
turn = 0;
player1 = true;
buttons.get(i).setEnabled(true);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
gridLayout = findViewById(R.id.grid);
frameLayout = findViewById(R.id.linearlayout);
linear = findViewById(R.id.linear);
Intent intent = getIntent();
String s = intent.getStringExtra("str");
n = parseInt(s);
linear.setGravity(Gravity.CENTER);
linear.setGravity(LinearLayout.HORIZONTAL);
gridLayout.setOrientation(GridLayout.VERTICAL);
for (int i = 0; i < n * n; i++) {
Button buttonView = new Button(this);
buttonView.setId(i);
buttonView.setOnClickListener(this);
gridLayout.setColumnCount(n);
gridLayout.setRowCount(n);
gridLayout.addView(buttonView);
buttons.add(buttonView);
}
}
#Override
public void onClick(View view) {
if (!((Button) view).getText().toString().equals("")) {
return;
}
if (player1) {
((Button) view).setText("X");
} else {
((Button) view).setText("O");
}
turn++;
if (checkforwin(view)) {
if (player1) {
player1win();
} else {
player2win();
}
} else if (turn == n * n) {
draw();
} else {
player1 = !player1;
}
}
private void player1win() {
Toast.makeText(this, "player 1 win", Toast.LENGTH_SHORT).show();
for (int i = 0; i < n * n; i++) {
if (buttons.get(i).getVisibility() == View.VISIBLE) {
buttons.get(i).setEnabled(false);
}
}
}
private void player2win() {
Toast.makeText(this, "player 2 win", Toast.LENGTH_SHORT).show();
for (int i = 0; i < n * n; i++) {
if (buttons.get(i).getVisibility() == View.VISIBLE) {
buttons.get(i).setEnabled(false);
}
}
}
private void draw() {
Toast.makeText(this, "draw", Toast.LENGTH_SHORT).show();
for (int i = 0; i < n * n; i++) {
if (buttons.get(i).getVisibility() == View.VISIBLE) {
buttons.get(i).setEnabled(false);
}
}
}
private boolean checkforwin(View view)
{
for (int i = 0; i<n; i++)
{
if (buttons.get(i).getText().toString().equals("X") && buttons.get(i + 3).getText().toString().equals("X") && buttons.get(i + 6).getText().toString().equals("X") ||
buttons.get(i).getText().toString().equals("O") && buttons.get(i + 3).getText().toString().equals("O") && buttons.get(i + 6).getText().toString().equals("O"))
{
return true;
}
}
for (int i=0;i<n*n;i=i+3)
{
if (buttons.get(i).getText().toString().equals("X") && buttons.get(i + 1).getText().toString().equals("X") && buttons.get(i + 2).getText().toString().equals("X") ||
buttons.get(i).getText().toString().equals("O") && buttons.get(i + 1).getText().toString().equals("O") && buttons.get(i + 2).getText().toString().equals("O"))
{
return true;
}
}
for (int i = 2; i<n; i++)
{
if (buttons.get(i).getText().toString().equals("X") && buttons.get(i + 2).getText().toString().equals("X") && buttons.get(i + 4).getText().toString().equals("X") ||
buttons.get(i).getText().toString().equals("O") && buttons.get(i + 2).getText().toString().equals("O") && buttons.get(i + 4).getText().toString().equals("O"))
{
return true;
}
}
for(int i = 0; i<n-2; i++)
{
if (buttons.get(i).getText().toString().equals("X") && buttons.get(i + 4).getText().toString().equals("X") && buttons.get(i + 8).getText().toString().equals("X") ||
buttons.get(i).getText().toString().equals("O") && buttons.get(i + 4).getText().toString().equals("O") && buttons.get(i + 8).getText().toString().equals("O"))
{
return true;
}
}
return false;
}
}
there is no error for 3*3 matrix,but i want to make dynamic logic which is applicable for all input.

tic tac toe game, multiplayer android

am new to android and was using the sample api's using the bluetooth chat code i created a tic tac toe game,
i'm able to connect two devices via bluetooth and can use the bluetooth name as the opponent's name
eg if my device name is "ABC" and opponents "DEF"
then the names in my device will be You : 0 DEF: 0
opponets device will have names YOU : 0 ABC : 0
( the score is initially set to 0).
where the problem is :
each of these device consider it as player 1 and can make a move. But i want to restrict it, the player who first tries to connect the device gets the 1st move and then the other.
how can i deal with the situation ??? please help
my code :
public class test extends Activity {
// Debugging
private static final String TAG = "TicTacToe";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
// Layout Views
private TextView mTitle;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothGameService mGameService = null;
// Member object for the chat services
private BluetoothChatService mChatService = null;
//game variable
// player names initialized with default values.
CharSequence player_name_1 = "Player 1";
CharSequence player_name_2 = "Player 2";
// score initialized to 0.
public static int ben = 0;
int game_mode = 0;
int count = 0; // to count the number of moves made.
int player = 1; // sets the player no. to 1 by default.
int score_player_1 = 0;
int score_player_2 = 0;
int arr[][] = {{0,0,0},{0,0,0},{0,0,0}}; // array which stores the movements made.
// dialog IDs
final int NAME_DIALOG_ID = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.tictactoe);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
final Button st = (Button) findViewById(R.id.start);
st.setEnabled(false);
}
// set player names
protected Dialog onCreateDialog(int id){
Dialog mdialog = new Dialog(this);
switch(id) {
case NAME_DIALOG_ID:
mdialog.setContentView(R.layout.name);
mdialog.setTitle("Player Names");
mdialog.setCancelable(true);
final EditText namep1 = (EditText) mdialog.findViewById(R.id.namep1);
final EditText namep2 = (EditText) mdialog.findViewById(R.id.namep2);
Button ok_b = (Button) mdialog.findViewById(R.id.ok);
ok_b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
player_name_2 = mConnectedDeviceName; //player 2 name
player_name_1 = "You"; //player 1 name
score_player_1 = 0;
score_player_2 = 0;
new_game(namep1.getText()); //calling fn
dismissDialog(1);
}
});
break;
default:
mdialog = null;
}
return mdialog;
}
OnClickListener button_listener = new View.OnClickListener() {
public void onClick(View v) {
ImageButton ibutton = (ImageButton) v;
// Button inactive for further clicks until a result is obtained.
ibutton.setClickable(false);
ibutton.setBackgroundResource(R.drawable.xo);
// Increment Count on clicking the button.
count++;
if ((count % 2 != 0)) {
player = 1;
ibutton.setImageResource(R.drawable.system_cross);
}
else if ((count % 2 == 0)) {
player = 2; // human player.
ibutton.setImageResource(R.drawable.system_dot);
}
// after_move function to check the result and decide.
after_move(ibutton);
}
};
public void new_game(CharSequence player_name) {
setContentView(R.layout.tictactoe);
final ImageButton b3 = (ImageButton) findViewById(R.id.b3);
final ImageButton b2 = (ImageButton) findViewById(R.id.b2);
final ImageButton b1 = (ImageButton) findViewById(R.id.b1);
final ImageButton b6 = (ImageButton) findViewById(R.id.b6);
final ImageButton b5 = (ImageButton) findViewById(R.id.b5);
final ImageButton b4 = (ImageButton) findViewById(R.id.b4);
final ImageButton b9 = (ImageButton) findViewById(R.id.b9);
final ImageButton b8 = (ImageButton) findViewById(R.id.b8);
final ImageButton b7 = (ImageButton) findViewById(R.id.b7);
// set the OnClickListeners.
b1.setOnClickListener(button_listener);
b2.setOnClickListener(button_listener);
b3.setOnClickListener(button_listener);
b4.setOnClickListener(button_listener);
b5.setOnClickListener(button_listener);
b6.setOnClickListener(button_listener);
b7.setOnClickListener(button_listener);
b8.setOnClickListener(button_listener);
b9.setOnClickListener(button_listener);
// Re-enable the Click-able property of buttons.
b1.setClickable(true);
b2.setClickable(true);
b3.setClickable(true);
b4.setClickable(true);
b5.setClickable(true);
b6.setClickable(true);
b7.setClickable(true);
b8.setClickable(true);
b9.setClickable(true);
// dismissDialog(NAME_DIALOG_ID);
// dismissDialog(HELP_DIALOG_ID);
// update the score board with the already existing values.
// this line should come ONLY after the player name is set in the above lines.
set_score(3);
// reset the array arr.
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
arr[i][j] = 0;
/* *********************************************************
* Initiates the computer's chance during start of the game,
* as well as when there is a win / loose and the next
* chance is for the computer.
* *********************************************************
if ((game_mode == 1) && (count % 2 != 0))
CompGame();
*/
}
public void set_score(int player_number) {
TextView tv = (TextView) findViewById(R.id.scoreboard);
if (player_number == 1)
score_player_1 += 1;
else if (player_number == 2)
score_player_2 += 1;
else ; // Don't change score, but set the score board right.
CharSequence score_txt = player_name_1 + " : " + score_player_1 + " " + player_name_2 + " : " + score_player_2;
tv.setText(score_txt);
}
public void after_move (ImageButton ib) {
CharSequence pos_str = ""; // position as a string.
int pos = 0;
boolean result = false;
pos_str = (CharSequence) ib.getTag(); // get the position from the tag.
pos = (int) pos_str.charAt(0) - 48; // char to integer conversion.
// set the values in the array according to the player number.
if (player == 1) {
if (pos < 4)
arr[0][pos - 1] = 1;
else if (pos < 7)
arr[1][(pos - 1) % 3] = 1;
else if (pos < 10)
arr[2][(pos - 1) % 3] = 1;
}
else {
if (pos < 4)
arr[0][pos - 1] = 2;
else if (pos < 7)
arr[1][(pos - 1) % 3] = 2;
else if (pos < 10)
arr[2][(pos - 1) % 3] = 2;
}
// Check for the game result.
result = result_check(player);
// Result check section.
if (result == true) {
// check for the player number.
if (player == 1) {
set_score(1);
if (game_mode == 0) {
show_result("Congrats. " + player_name_1 + " wins !!");
}
}
else {
set_score(2);
if (game_mode == 0) { // human vs human
show_result("Congrats. " + player_name_2 + " wins !!");
}
}
return;
}
else if ((result == false) && arr_isFull()) {
show_result(" Game Draw ! "); // leave the space, or else dialog becomes cramped.
return;
}
else { } // continue game.
}
public boolean result_check(int player_local) {
boolean win = true;
int k = 0;
// check for horizontal condition only.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (arr[i][j] != player_local) { // check with player number.
win = false;
break;
}
} // column loop.
if (win == true) {
return true;
}
win = true;
} // row loop.
win = true; // resetting win to true.
// checking for vertical condition only.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (arr[j][i] != player_local) {
win = false;
break;
}
} // column loop.
if (win == true) {
return true;
}
win = true;
} // row loop.
win = true; // reset win to true.
// check for diagonal condition 1.
for (int i = 0; i < 3; i++)
if (arr[i][k++] != player_local) {
win = false;
break;
}
if (win == true) {
return true;
}
k = 2;
win = true; // reset win to true;
// check for diagonal condition 2.
for (int i = 0; i < 3; i++)
if (arr[i][k--] != player_local) {
win = false;
break;
}
if (win == true) {
return true;
}
return false;
}
public boolean show_result(CharSequence message) //function to select the game mode
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// reset the game environment.
new_game(player_name_2);
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
public boolean arr_isFull () {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (arr[i][j] == 0)
return false;
return true;
}
#Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mGameService == null)
setupGame();
}
}
private void setupGame() {
Log.d(TAG, "setupGame()");
// Initialize the BluetoothGameService to perform bluetooth connections
mGameService = new BluetoothGameService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mGameService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mGameService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mGameService.start();
}
}
}
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mGameService != null) mGameService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
/**
* Sends a message.
* #param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothGameService.STATE_CONNECTED:
mTitle.setText(R.string.title_connected_to);
mTitle.append(mConnectedDeviceName);
//mConversationArrayAdapter.clear();
break;
case BluetoothGameService.STATE_CONNECTING:
mTitle.setText(R.string.title_connecting);
break;
case BluetoothGameService.STATE_LISTEN:
case BluetoothGameService.STATE_NONE:
mTitle.setText(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
//mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
//mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
if(ben>0)
{
final Button st = (Button) findViewById(R.id.start); // enable start button
st.setEnabled(true);
}
else
{
final Button st = (Button) findViewById(R.id.start); // disable start button
st.setEnabled(false);
}
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mGameService.connect(device);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupGame();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
ben = ben + 1;
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
return true;
case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
return false;
}
//when start is pressed
public void start(View v){
//showDialog(NAME_DIALOG_ID);
player_name_2 = mConnectedDeviceName; //player 2 name
player_name_1 = "You"; //player 1 name
score_player_1 = 0;
score_player_2 = 0;
new_game(player_name_1); //calling fn
}
//when back | return button is pressed
public void back(View v){
player_name_1 = "Player 1";
player_name_2 = "Player 2";
count = 0;
player = 1;
score_player_1 = 0;
score_player_2 = 0;
Intent open = new Intent("com.example.tictactoechat_abs.STARTINGPOINT");
startActivity(open);
}
}
I would suggest when the connection is made, and before the game begins, that you transmit a message on the client saying 'the game is starting and I am going first'. You can presumably tell who tried to connect if one person presses 'join' and the other presses 'host'.
Alternatively you could randomise it by having both sides send a random number and whoever is the highest goes first.
You could create a player class that will represent a player. In there you could set a instance variable to the desired number, incrementing it by one each time. The player with the lowest number then could go first, followed by the rest of the players in order of that number. You can then have a class to manage all the player objects. That class will be responsible for checking for the next available number and assigning it to a player.

Android toast message (identify the correct answer using radio button)

I'm developing a quiz. I got an error while showing my toast message. The error is, if the user taps the correct answer, toast says it is the wrong answer even if I tap the correct choice. Help is really appreciated! Here is the code:
public class Question2 extends Activity {
/** Called when the activity is first created. */
TextView question, items = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioGroup answers = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review = false;
Button next = null;
int score = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startquiz);
try {
score = getIntent().getIntExtra("score",0);
items = (TextView)findViewById(R.id.displayitems);
question = (TextView) findViewById(R.id.displayquestion);
answer1 = (RadioButton) findViewById(R.id.option1);
answer2 = (RadioButton) findViewById(R.id.option2);
answer3 = (RadioButton) findViewById(R.id.option3);
answers = (RadioGroup) findViewById(R.id.QueGroup1);
next = (Button) findViewById(R.id.selected);
next.setOnClickListener(nextListener);
selected = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(selected, -1);
correctAns = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(correctAns, -1);
this.showQuestion(0, review);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
private void showQuestion(int qIndex, boolean review) {
try {
JSONObject aQues = Question1.getQuesList().getJSONObject(
qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.BLACK);
answer2.setTextColor(Color.BLACK);
answer3.setTextColor(Color.BLACK);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("", selected[qIndex] + "");
if (selected[qIndex] == 0)
answers.check(R.id.option1);
if (selected[qIndex] == 1)
answers.check(R.id.option2);
if (selected[qIndex] == 2)
answers.check(R.id.option3);
setText();
if (quesIndex == (Question1.getQuesList().length() - 1))
next.setEnabled(false);
if (quesIndex < (Question1.getQuesList().length() - 1))
next.setEnabled(true);
if (review) {
Log.d("review", selected[qIndex] + "" + correctAns[qIndex]);
;
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
Log.d("", Arrays.toString(selected));
Log.d("", Arrays.toString(correctAns));
}
private OnClickListener nextListener = new OnClickListener() {
public void onClick(View v) {
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i] != -1) && (correctAns[i] == selected[i]))
{
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
}
}
quesIndex++;
try {
if (quesIndex >= Question1.getQuesList().length())
quesIndex = Question1.getQuesList().length() - 1;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
showQuestion(quesIndex, review);
}
};
private void setText() throws JSONException {
this.setTitle("Question " + (quesIndex + 1) + " out of "
+ Question1.getQuesList().length());
items.setGravity(250);
}
public void reload() {
setAnswer();
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
Your If() condition should be like this:-
if ((correctAns[i] != -1) && (correctAns[i].equalsIgnoreCase(selected[i]))) {
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
}
It seems like you can change your condition. Are users be able to select multiple answers?
And try that thin with condition like
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i].euqalsIgnoreCase(selected[i]))){
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
}
}
Try this and let me know that it works or not.

Categories