tic tac toe game, multiplayer android - java

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.

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

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

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)) {

How can I send the "SCAN_RESULT" to another activity with zxing in eclipse

How can I put the result of the QR "SCAN_RESULT" in different activity, this is my problem.
In the splash screen I need to go to the QRScanner (CaptureActivity), and then, to the ActivityQR who will send the info. to the SQLite.
The problem is: When I get de QRCode in string ("SCAN_RESULT") on "CaptureActivity.java", the app close because the app need "back" to the previous activity with this:
getIntent();
I try to modify this codeline, but this not solve my problem.
How can I put the "SCAN_RESULT" in the ActivityQR? I don't know how open other activity (this case ActivityQR) when the code had gottenm and put this String value on the ActivityQR
I Use "CaptureActivity" of ZXing (ZebraCrossing)
Thanks in advance.
SplashScreen.java :
{
Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, com.google.zxing.client.android.CaptureActivity.class);
startActivity(mainIntent)
}
ActivityQR.java
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(REQUEST_CODE == requestCode && RESULT_OK == resultCode){
txResult.setText(data.getStringExtra("SCAN_RESULT"));
}
}
CaptureActivity.java
public class CaptureActivity extends Activity implements SurfaceHolder.Callback {
private static final String TAG = CaptureActivity.class.getSimpleName();
private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;
private static final String[] ZXING_URLS = { "http://zxing.appspot.com/scan", "zxing://scan/" };
public static final int HISTORY_REQUEST_CODE = 0x0000bacc;
private static final Collection<ResultMetadataType> DISPLAYABLE_METADATA_TYPES =
EnumSet.of(ResultMetadataType.ISSUE_NUMBER,
ResultMetadataType.SUGGESTED_PRICE,
ResultMetadataType.ERROR_CORRECTION_LEVEL,
ResultMetadataType.POSSIBLE_COUNTRY);
private CameraManager cameraManager;
private CaptureActivityHandler handler;
private Result savedResultToShow;
private ViewfinderView viewfinderView;
private TextView statusView;
private View resultView;
private Result lastResult;
private boolean hasSurface;
private boolean copyToClipboard;
private IntentSource source;
private String sourceUrl;
private ScanFromWebPageManager scanFromWebPageManager;
private Collection<BarcodeFormat> decodeFormats;
private Map<DecodeHintType,?> decodeHints;
private String characterSet;
private HistoryManager historyManager;
private InactivityTimer inactivityTimer;
private BeepManager beepManager;
private AmbientLightManager ambientLightManager;
ViewfinderView getViewfinderView() {
return viewfinderView;
}
public Handler getHandler() {
return handler;
}
CameraManager getCameraManager() {
return cameraManager;
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.capture);
hasSurface = false;
historyManager = new HistoryManager(this);
historyManager.trimHistory();
inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this);
ambientLightManager = new AmbientLightManager(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
}
#Override
protected void onResume() {
super.onResume();
// CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
// want to open the camera driver and measure the screen size if we're going to show the help on
// first launch. That led to bugs where the scanning rectangle was the wrong size and partially
// off screen.
cameraManager = new CameraManager(getApplication());
viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
viewfinderView.setCameraManager(cameraManager);
resultView = findViewById(R.id.result_view);
statusView = (TextView) findViewById(R.id.status_view);
handler = null;
lastResult = null;
resetStatusView();
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
// The activity was paused but not stopped, so the surface still exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(surfaceHolder);
} else {
// Install the callback and wait for surfaceCreated() to init the camera.
surfaceHolder.addCallback(this);
}
beepManager.updatePrefs();
ambientLightManager.start(cameraManager);
inactivityTimer.onResume();
Intent intent = getIntent();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
&& (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));
source = IntentSource.NONE;
decodeFormats = null;
characterSet = null;
if (intent != null) {
String action = intent.getAction();
String dataString = intent.getDataString();
if (Intents.Scan.ACTION.equals(action)) {
// Scan the formats the intent requested, and return the result to the calling activity.
source = IntentSource.NATIVE_APP_INTENT;
decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
decodeHints = DecodeHintManager.parseDecodeHints(intent);
if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
if (width > 0 && height > 0) {
cameraManager.setManualFramingRect(width, height);
}
}
String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
if (customPromptMessage != null) {
statusView.setText(customPromptMessage);
}
} else if (dataString != null &&
dataString.contains("http://www.google") &&
dataString.contains("/m/products/scan")) {
// Scan only products and send the result to mobile Product Search.
source = IntentSource.PRODUCT_SEARCH_LINK;
sourceUrl = dataString;
decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
} else if (isZXingURL(dataString)) {
// Scan formats requested in query string (all formats if none specified).
// If a return URL is specified, send the results there. Otherwise, handle it ourselves.
source = IntentSource.ZXING_LINK;
sourceUrl = dataString;
Uri inputUri = Uri.parse(dataString);
scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
// Allow a sub-set of the hints to be specified by the caller.
decodeHints = DecodeHintManager.parseDecodeHints(inputUri);
}
characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
}
}
private static boolean isZXingURL(String dataString) {
if (dataString == null) {
return false;
}
for (String url : ZXING_URLS) {
if (dataString.startsWith(url)) {
return true;
}
}
return false;
}
#Override
protected void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
ambientLightManager.stop();
cameraManager.closeDriver();
if (!hasSurface) {
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.removeCallback(this);
}
super.onPause();
}
#Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (source == IntentSource.NATIVE_APP_INTENT) {
setResult(RESULT_CANCELED);
finish();
return true;
}
if ((source == IntentSource.NONE || source == IntentSource.ZXING_LINK) && lastResult != null) {
restartPreviewAfterDelay(0L);
return true;
}
break;
case KeyEvent.KEYCODE_FOCUS:
case KeyEvent.KEYCODE_CAMERA:
// Handle these events so they don't launch the Camera app
return true;
// Use volume up/down to turn on light
case KeyEvent.KEYCODE_VOLUME_DOWN:
cameraManager.setTorch(false);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
cameraManager.setTorch(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.capture, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
switch (item.getItemId()) {
case R.id.menu_share:
intent.setClassName(this, ShareActivity.class.getName());
startActivity(intent);
break;
case R.id.menu_history:
intent.setClassName(this, HistoryActivity.class.getName());
startActivityForResult(intent, HISTORY_REQUEST_CODE);
break;
case R.id.menu_settings:
intent.setClassName(this, PreferencesActivity.class.getName());
startActivity(intent);
break;
case R.id.menu_help:
intent.setClassName(this, HelpActivity.class.getName());
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
if (requestCode == HISTORY_REQUEST_CODE) {
int itemNumber = intent.getIntExtra(Intents.History.ITEM_NUMBER, -1);
if (itemNumber >= 0) {
HistoryItem historyItem = historyManager.buildHistoryItem(itemNumber);
decodeOrStoreSavedBitmap(null, historyItem.getResult());
}
}
}
}
private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
// Bitmap isn't used yet -- will be used soon
if (handler == null) {
savedResultToShow = result;
} else {
if (result != null) {
savedResultToShow = result;
}
if (savedResultToShow != null) {
Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow);
handler.sendMessage(message);
}
savedResultToShow = null;
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
/**
* A valid barcode has been found, so give an indication of success and show the results.
*
* #param rawResult The contents of the barcode.
* #param scaleFactor amount by which thumbnail was scaled
* #param barcode A greyscale bitmap of the camera data which was decoded.
*/
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
Intent it = getIntent();
it.putExtra("SCAN_RESULT", rawResult.getText());
it.putExtra("SCAN_FORMAT", rawResult.getBarcodeFormat().toString());
setResult(Activity.RESULT_OK, it);
finish();
inactivityTimer.onActivity();
lastResult = rawResult;
ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
boolean fromLiveScan = barcode != null;
if (fromLiveScan) {
historyManager.addHistoryItem(rawResult, resultHandler);
// Then not from history, so beep/vibrate and we have an image to draw on
beepManager.playBeepSoundAndVibrate();
drawResultPoints(barcode, scaleFactor, rawResult);
}
switch (source) {
case NATIVE_APP_INTENT:
case PRODUCT_SEARCH_LINK:
handleDecodeExternally(rawResult, resultHandler, barcode);
break;
case ZXING_LINK:
if (scanFromWebPageManager == null || !scanFromWebPageManager.isScanFromWebPage()) {
handleDecodeInternally(rawResult, resultHandler, barcode);
} else {
handleDecodeExternally(rawResult, resultHandler, barcode);
}
break;
case NONE:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (fromLiveScan && prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.msg_bulk_mode_scanned) + " (" + rawResult.getText() + ')',
Toast.LENGTH_SHORT).show();
// Wait a moment or else it will scan the same barcode continuously about 3 times
restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS);
} else {
handleDecodeInternally(rawResult, resultHandler, barcode);
}
break;
}
}
/**
* Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
*
* #param barcode A bitmap of the captured image.
* #param scaleFactor amount by which thumbnail was scaled
* #param rawResult The decoded results which contains the points to draw.
*/
private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) {
ResultPoint[] points = rawResult.getResultPoints();
if (points != null && points.length > 0) {
Canvas canvas = new Canvas(barcode);
Paint paint = new Paint();
paint.setColor(getResources().getColor(R.color.result_points));
if (points.length == 2) {
paint.setStrokeWidth(4.0f);
drawLine(canvas, paint, points[0], points[1], scaleFactor);
} else if (points.length == 4 &&
(rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A ||
rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) {
// Hacky special case -- draw two lines, for the barcode and metadata
drawLine(canvas, paint, points[0], points[1], scaleFactor);
drawLine(canvas, paint, points[2], points[3], scaleFactor);
} else {
paint.setStrokeWidth(10.0f);
for (ResultPoint point : points) {
if (point != null) {
canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint);
}
}
}
}
}
private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) {
if (a != null && b != null) {
canvas.drawLine(scaleFactor * a.getX(),
scaleFactor * a.getY(),
scaleFactor * b.getX(),
scaleFactor * b.getY(),
paint);
}
}
// Put up our own UI for how to handle the decoded contents.
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.VISIBLE);
ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
if (barcode == null) {
barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
R.drawable.launcher_icon));
} else {
barcodeImageView.setImageBitmap(barcode);
}
TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
formatTextView.setText(rawResult.getBarcodeFormat().toString());
TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
typeTextView.setText(resultHandler.getType().toString());
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
timeTextView.setText(formatter.format(new Date(rawResult.getTimestamp())));
TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
metaTextView.setVisibility(View.GONE);
metaTextViewLabel.setVisibility(View.GONE);
Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
if (metadata != null) {
StringBuilder metadataText = new StringBuilder(20);
for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
metadataText.append(entry.getValue()).append('\n');
}
}
if (metadataText.length() > 0) {
metadataText.setLength(metadataText.length() - 1);
metaTextView.setText(metadataText);
metaTextView.setVisibility(View.VISIBLE);
metaTextViewLabel.setVisibility(View.VISIBLE);
}
}
TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
CharSequence displayContents = resultHandler.getDisplayContents();
contentsTextView.setText(displayContents);
// Crudely scale betweeen 22 and 32 -- bigger font for shorter text
int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view);
supplementTextView.setText("");
supplementTextView.setOnClickListener(null);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
resultHandler.getResult(),
historyManager,
this);
}
int buttonCount = resultHandler.getButtonCount();
ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
buttonView.requestFocus();
for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
TextView button = (TextView) buttonView.getChildAt(x);
if (x < buttonCount) {
button.setVisibility(View.VISIBLE);
button.setText(resultHandler.getButtonText(x));
button.setOnClickListener(new ResultButtonListener(resultHandler, x));
} else {
button.setVisibility(View.GONE);
}
}
if (copyToClipboard && !resultHandler.areContentsSecure()) {
ClipboardInterface.setText(displayContents, this);
}
}
// Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
private void handleDecodeExternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
if (barcode != null) {
viewfinderView.drawResultBitmap(barcode);
}
long resultDurationMS;
if (getIntent() == null) {
resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS;
} else {
resultDurationMS = getIntent().getLongExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS,
DEFAULT_INTENT_RESULT_DURATION_MS);
}
if (resultDurationMS > 0) {
String rawResultString = String.valueOf(rawResult);
if (rawResultString.length() > 32) {
rawResultString = rawResultString.substring(0, 32) + " ...";
}
statusView.setText(getString(resultHandler.getDisplayTitle()) + " : " + rawResultString);
}
if (copyToClipboard && !resultHandler.areContentsSecure()) {
CharSequence text = resultHandler.getDisplayContents();
ClipboardInterface.setText(text, this);
}
if (source == IntentSource.NATIVE_APP_INTENT) {
// Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
// the deprecated intent is retired.
Intent intent = new Intent(getIntent().getAction());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
byte[] rawBytes = rawResult.getRawBytes();
if (rawBytes != null && rawBytes.length > 0) {
intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes);
}
Map<ResultMetadataType,?> metadata = rawResult.getResultMetadata();
if (metadata != null) {
if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) {
intent.putExtra(Intents.Scan.RESULT_UPC_EAN_EXTENSION,
metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString());
}
Number orientation = (Number) metadata.get(ResultMetadataType.ORIENTATION);
if (orientation != null) {
intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue());
}
String ecLevel = (String) metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL);
if (ecLevel != null) {
intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel);
}
#SuppressWarnings("unchecked")
Iterable<byte[]> byteSegments = (Iterable<byte[]>) metadata.get(ResultMetadataType.BYTE_SEGMENTS);
if (byteSegments != null) {
int i = 0;
for (byte[] byteSegment : byteSegments) {
intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment);
i++;
}
}
}
sendReplyMessage(R.id.return_scan_result, intent, resultDurationMS);
} else if (source == IntentSource.PRODUCT_SEARCH_LINK) {
// Reformulate the URL which triggered us into a query, so that the request goes to the same
// TLD as the scan URL.
int end = sourceUrl.lastIndexOf("/scan");
String replyURL = sourceUrl.substring(0, end) + "?q=" + resultHandler.getDisplayContents() + "&source=zxing";
sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
} else if (source == IntentSource.ZXING_LINK) {
if (scanFromWebPageManager != null && scanFromWebPageManager.isScanFromWebPage()) {
String replyURL = scanFromWebPageManager.buildReplyURL(rawResult, resultHandler);
sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
}
}
}
private void sendReplyMessage(int id, Object arg, long delayMS) {
if (handler != null) {
Message message = Message.obtain(handler, id, arg);
if (delayMS > 0L) {
handler.sendMessageDelayed(message, delayMS);
} else {
handler.sendMessage(message);
}
}
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a RuntimeException.
if (handler == null) {
handler = new CaptureActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager);
}
decodeOrStoreSavedBitmap(null, null);
} catch (IOException ioe) {
Log.w(TAG, ioe);
displayFrameworkBugMessageAndExit();
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
displayFrameworkBugMessageAndExit();
}
}
private void displayFrameworkBugMessageAndExit() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.msg_camera_framework_bug));
builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
builder.setOnCancelListener(new FinishListener(this));
builder.show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
resetStatusView();
}
private void resetStatusView() {
resultView.setVisibility(View.GONE);
statusView.setText(R.string.msg_default_status);
statusView.setVisibility(View.VISIBLE);
viewfinderView.setVisibility(View.VISIBLE);
lastResult = null;
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
}
your SplashScreen Java should look like this:
{
Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, com.google.zxing.client.android.CaptureActivity.class);
// use startActivityForResult instead of startActivity
startActivityForResult(mainIntent)
}
but I guess you already solved you problem!

UI not updating in Android using AsyncTask

I've searched the internet far and wide about getting the UI to update in real-time in Android to no avail. I implemented an AysncTask class as most of the other posts suggested, but it's still not updating my UI in real-time like I want. It only updates after the program is done running. I've even been getting the "Skipped n frames. The application may be doing too much work in its main thread." error, which I don't understand because I'm trying to do these updates in the UI thread. About 5 seconds into running my program the screen turns black and stays like that until its done finishing. Any help would be much appreciated as I've been pulling my hair out on this one for awhile Here's my code.
EDIT: Solved. Removed the Thread.sleep(n) from my UI thread and added it to my AsyncTask. Thanks everyone!
Main class:
public class Home extends Activity {
// Declare objects
Button turingB, socratesB, voltaireB, descartesB, platoB;
int[] eating, thinking, hungry;
Philosopher socrates, turing, voltaire, descartes, plato;
Philosopher[] philosophers;
Chopstick[] chopsticks;
TextView info;
String value;
Context context;
int toastLength;
boolean turingHungry, socratesHungry, voltaireHungry, descartesHungry, platoHungry;
String running;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Instantiate objects (keep track of each button individually
context = getApplicationContext();
toastLength = Toast.LENGTH_SHORT;
info = (TextView) findViewById(R.id.textView1);
info.setText("Click Start to begin!");
socratesB = (Button) findViewById(R.id.button1);
descartesB = (Button) findViewById(R.id.button5);
platoB = (Button) findViewById(R.id.button4);
voltaireB = (Button) findViewById(R.id.button3);
turingB = (Button) findViewById(R.id.button2);
running = "false";
// Set all philosophers to thinking (blue)
// socratesB.setBackgroundColor(Color.BLUE);
// descartesB.setBackgroundColor(Color.BLUE);
// platoB.setBackgroundColor(Color.BLUE);
// voltaireB.setBackgroundColor(Color.BLUE);
// turingB.setBackgroundColor(Color.BLUE);
turingHungry = false;
socratesHungry = false;
voltaireHungry = false;
descartesHungry = false;
platoHungry = false;
//Button platoTempButton = (Button) findViewById(R.id.button4);
// Listen for buttons
OnClickListener pBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
platoHungry = true;
}
};
//platoTempButton.setOnClickListener(pBtn);
OnClickListener tBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
turingHungry = true;
}
};
OnClickListener sBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
socratesHungry = true;
}
};
OnClickListener vBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
voltaireHungry = true;
}
};
OnClickListener dBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
descartesHungry = true;
}
};
platoB.setOnClickListener(pBtn);
turingB.setOnClickListener(tBtn);
socratesB.setOnClickListener(sBtn);
voltaireB.setOnClickListener(vBtn);
descartesB.setOnClickListener(dBtn);
// Set arrays to count time spent eating, thinking, hungry
eating = new int[5];
thinking = new int[5];
hungry = new int[5];
// Create the chopsticks
chopsticks = new Chopstick[5];
for (int i = 0; i < 5; i ++)
{
chopsticks[i] = new Chopstick(i);
}
for (Chopstick chop: chopsticks)
{
chop.available = true;
}
// Create the philosophers
philosophers = new Philosopher[5];
philosophers[0] = new Philosopher(0, chopsticks[0], chopsticks[1], "Plato", platoB);
philosophers[1] = new Philosopher(1, chopsticks[1], chopsticks[2], "Turing", turingB);
philosophers[2] = new Philosopher(2, chopsticks[2], chopsticks[3], "Socrates", socratesB);
philosophers[3] = new Philosopher(3, chopsticks[3], chopsticks[4], "Voltaire", voltaireB);
philosophers[4] = new Philosopher(4, chopsticks[4], chopsticks[0], "Descartes", descartesB);
// Get sim time from user
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Simulation Time");
alert.setMessage("Please length of time for the simulation to run (in seconds)");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
value = String.valueOf(input.getText());
}
});
alert.show();
// Get info
Bundle extras = getIntent().getExtras();
if (extras != null)
{
running = extras.getString("runApp");
value = extras.getString("numToRun");
}
// Run app
if (running.equals("true"))
{
System.out.println("RUNNING!!!");
run(value);
}
}
public void run(String length)
{
int num = Integer.parseInt(length);
// Run num times
for (int i = 0; i < num; i++)
{
try {
// Pass current index, and data arrays to step method
step(i, eating, thinking, hungry);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Print out some data
for (int j = 0; j < 5; j++)
{
System.out.println("Philosopher " + j + " ate: " + eating[j]);
System.out.println("Philosopher " + j + " thought: " + thinking[j]);
System.out.println("Philosopher " + j + " was hungry: " + hungry[j]);
}
running = "false";
}
// Run simulation n times (n specified by the user)
public void startSim(View v)
{
Intent my_intent = new Intent(this, Home.class);
my_intent.putExtra("runApp", "true");
my_intent.putExtra("numToRun", value);
startActivity(my_intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
// Reset simulation
public void reset(View v)
{
Intent my_intent = new Intent(this, Home.class);
startActivity(my_intent);
}
// Return hunger status of philosopher
public boolean isHungry(String name) {
if (name.equals("Voltaire"))
return voltaireHungry;
else if (name.equals("Socrates"))
return socratesHungry;
else if (name.equals("Plato"))
return platoHungry;
else if (name.equals("Turing"))
return turingHungry;
else if (name.equals("Descartes"))
return descartesHungry;
else
return false;
}
// Step method for simulation
// Takes the current index and each of the data arrays
public void step(int i, int[] eating, int[] thinking, int[] hungry) throws InterruptedException
{
// Make random number
Random randomGenerator = new Random();
int num = randomGenerator.nextInt(10);
// Randomly set a philosopher isFull to false (hungry) (10% chance for each to become hungry if not specified by the user)
if (isHungry(philosophers[0].name))
philosophers[0].isFull = false;
if (num == 1 || isHungry(philosophers[1].name))
philosophers[1].isFull = false;
if (num == 2 || isHungry(philosophers[2].name))
philosophers[2].isFull = false;
if (num == 3 || isHungry(philosophers[3].name))
philosophers[3].isFull = false;
if (num == 4 || isHungry(philosophers[4].name))
philosophers[4].isFull = false;
// For each philosopher
for (Philosopher phil: philosophers)
{
// Print current info
System.out.println("PHIL: " + phil.name + " NUM: " + num + " RIGHT: " + phil.rightChopstick.available + " LEFT: " + phil.leftChopstick.available);
// Temp id var
int tempId = phil.id;
// If philosopher is hungry, try to eat
if (phil.isFull == false)
{
// Try to eat only if both chopsticks are available
if (phil.rightChopstick.pickUp(phil.name) && phil.leftChopstick.pickUp(phil.name))
{
// Change button color
new Background(phil.button).execute((long) 1);
//Toast.makeText(context, phil.name + " is eating.", toastLength).show();
// Increment time spent eating
eating[tempId]++;
}
// Check to see if the philosopher is already eating (has both chopsticks)
else if (phil.rightChopstick.who.equals(phil.name) && phil.leftChopstick.who.equals(phil.name))
{
//Toast.makeText(context, phil.name + " is eating.", toastLength).show();
new Background(phil.button).execute((long) 1);
// Increment eating
eating[tempId]++;
// 30% chance to stop eating
if (num >= 5 && num <=7)
{
// Put down chopsticks
phil.rightChopstick.putDown();
phil.leftChopstick.putDown();
// Stop eating
phil.isFull = true;
}
}
// Hungry
else
{
// Change button color
new Background(phil.button).execute((long) 3);
//Toast.makeText(context, phil.name + " is hungry.", toastLength).show();
// Increment time spent hungry
hungry[tempId]++;
}
}
// Thinking
else
{
new Background(phil.button).execute((long) 2);
//Toast.makeText(context, phil.name + " is thinking.", toastLength).show();
// Increment time spent thinking
thinking[tempId]++;
}
Thread.sleep(1000);
}
// Make each step count as 1 second (1000 miliseconds)
System.out.println("--------------------------------------------------------------");
Thread.sleep(5000);
}
}
Background class (AsyncTask):
public class Background extends AsyncTask<Long, Void, Void>
{
// Variables
String color;
Button button;
public Background(Button button)
{
this.button = button;
}
#Override
protected Void doInBackground(Long... params) {
// Get which color the button needs to be
try
{
// Change the color based on the value passed in
if (params[0] == 3)
{
color = "RED";
}
else if (params[0] == 2)
{
color = "BLUE";
}
else if (params[0] == 1)
{
color = "GREEN";
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set button to that color
System.out.println("Updating color in real time...");
button.setBackgroundColor(Color.parseColor(color));
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Here is one problem
Thread.sleep(1000);
and here is another
Thread.sleep(5000);
these are both making the UI sleep for a total of 6 seconds. You almost never want to call sleep() on the UI Thread. You can do this in doInBackground() or anywhere else that runs on a background Thread.
Edit
You don't set your Listeners. For example:
platoB.setOnClickListener(new pBtn());
Progress can be set with publishProgress in your asynctask, you get a call to onProgressUpdate in the UI thread.

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