How to Block the account When Username and password are Wrong - java

My Requirement is using count.when we press the button three times i want to appear toast message as Blocked ??please any one can show the code or condition.Any Error in Programming?
public void empbtn(View v) {
EditText et11,et22;
int counter = 3;
int i;
String unames[] = {"Anil","Ramesh","Khaja"};
String passwds[] = {"anil","ramesh","khaja"};
et11 = (EditText)findViewById(R.id.empname);
et22 = (EditText)findViewById(R.id.emppass);
String uname = et11.getText().toString();
String pass = et22.getText().toString();
if(uname.equals(""))
{
et11.setError("PLS ENTER NAME");
}
else if (pass.equals(passwds))
{
//et22.setError("pls enter password");
Toast.makeText(main.this, "valid", Toast.LENGTH_SHORT).show();
}
else {
counter++;
if (counter > 3)
{
Toast.makeText(main.this, "blocked", Toast.LENGTH_SHORT).show();
}
else {
for (i = 0; i < unames.length; i++) {
if (uname.equals(unames[i]) && pass.equals(passwds[i])) {
setContentView(R.layout.home);
TextView tv = (TextView) findViewById(R.id.names);
tv.setText(uname);
break;
}
}
if (i == unames.length) {
Toast.makeText(main.this, "INVALID", Toast.LENGTH_SHORT).show();
}
}
}

You could put a boolean as a flag to know when is valid:
boolean isValid = false;
for (i = 0; i < unames.length; i++) {
if (uname.equals(unames[i]) && pass.equals(passwds[i])) {
setContentView(R.layout.home);
TextView tv = (TextView) findViewById(R.id.names);
tv.setText(uname);
isValid=true
break;
}
}
if (!isValid) {
Toast.makeText(main.this, "INVALID", Toast.LENGTH_SHORT).show();
}
EDIT
Try with this:
if (i == unames.length-1) {
Toast.makeText(main.this, "INVALID", Toast.LENGTH_SHORT).show();
}

Related

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.

Android Development. RadioButton keeps unselecting

I am building a little quiz app and let's say on Question 1, I select option B, then submit and the quiz gives me the next question. However for question 2 if I try to select B, the RadioButton quickly unchecks itself and it is completely uncheckable, until I select another radio button and then try B again. The pattern is, whatever option I selected in the previous question, is uncheckable in the next question unless I click on a different radiobutton and then try again. I'm attaching my code. Any help please?
public class MainActivity extends AppCompatActivity {
QuestionBank allQuestions = new QuestionBank();
String pickedAnswer = "", correctAnswer = "";
final int numberOfQuestions = allQuestions.list.size();
int questionNumber = 0;
boolean noSelection = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextQuestion();
}
private void nextQuestion() {
if (questionNumber <= numberOfQuestions - 1) {
TextView questionLabel = (TextView) findViewById(R.id.question_text_view);
String fullQuestion = allQuestions.list.get(questionNumber).questionSet.get("question").toString();
fullQuestion += "\n\na) " + allQuestions.list.get(questionNumber).questionSet.get("a");
fullQuestion += "\nb) " + allQuestions.list.get(questionNumber).questionSet.get("b");
fullQuestion += "\nc) " + allQuestions.list.get(questionNumber).questionSet.get("c");
fullQuestion += "\nd) " + allQuestions.list.get(questionNumber).questionSet.get("d");
correctAnswer = allQuestions.list.get(questionNumber).questionSet.get("answer").toString();
questionLabel.setText(fullQuestion);
questionNumber++;
} else {
restart();
}
}
public void getSelectedAnswer() {
RadioButton radio_1 = (RadioButton) findViewById(R.id.option1_button);
RadioButton radio_2 = (RadioButton) findViewById(R.id.option2_button);
RadioButton radio_3 = (RadioButton) findViewById(R.id.option3_button);
RadioButton radio_4 = (RadioButton) findViewById(R.id.option4_button);
if (radio_1.isChecked()) {
pickedAnswer = "a";
radio_1.setChecked(false);
} else if (radio_2.isChecked()) {
pickedAnswer = "b";
radio_2.setChecked(false);
} else if (radio_3.isChecked()) {
pickedAnswer = "c";
radio_3.setChecked(false);
} else if (radio_4.isChecked()) {
pickedAnswer = "d";
radio_4.setChecked(false);
} else {
noSelection = true;
}
}
public void submitAnswer(View view) {
getSelectedAnswer();
if (noSelection) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Please select an answer!");
a_builder.show();
noSelection = false;
} else {
checkAnswer();
nextQuestion();
}
}
public void checkAnswer() {
if (correctAnswer == pickedAnswer) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Right Answer!");
a_builder.show();
} else {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Wrong Answer!");
a_builder.show();
}
pickedAnswer = "";
correctAnswer = "";
}
public void restart() {
questionNumber = 0;
//Collections.shuffle(allQuestions.list);
nextQuestion();
}
}
call setChecked(false) on all the buttons after submitting or before showing next question

Dialog not dismiss in if condition

I am try to dismiss dialog in if condition true part but it is not worked.
In dialog entered in if condition but not dismiss.in If condition toast message display properly.
public void showIncomingCall() {
int getTotal = 0;
if(showincoming != null && showincoming.isShowing() )
{
//adapter1.notifyDataSetChanged();
//showincoming.dismiss();
return;
}
else {
showincoming = new Dialog(MainActivity.this);
showincoming.requestWindowFeature(Window.FEATURE_NO_TITLE);
showincoming.setContentView(R.layout.custome_dialog);
listdialog = (ListView) showincoming.findViewById(R.id.incoming_list);
//adapter1 = new CustomeListAdapter(MainActivity.this);
listdialog.setAdapter(adapter1);
//adapter1.notifyDataSetChanged();
close = (ImageButton) showincoming.findViewById(R.id.dialog_close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showincoming.dismiss();
adapter1.notifyDataSetChanged();
}
});
adapter1.notifyDataSetChanged();
for (int i = 0; i < listdialog.getCount(); i++) {
parentView = getViewByPosition(i, listdialog);
String getString = ((TextView) parentView.findViewById(R.id.tvLineStatus)).getText().toString();
if (getString.toString().equals("Idle") || getString.toString().equals("Disconnect") || getString.toString().equals("Dialing")) {
getTotal += 1;
}
}
if (getTotal >= 7) {
showincoming.dismiss();
Toast.makeText(getApplicationContext(),"getTotal" + getTotal,Toast.LENGTH_LONG).show();
adapter1.notifyDataSetChanged();
//adapter1.setNotifyOnChange(true);
}
//Toast.makeText(MainActivity.this,getTotal+"getTotal",Toast.LENGTH_LONG).show();
adapter1.notifyDataSetChanged();
listdialog.invalidateViews();
if(!showincoming.isShowing()) {
showincoming.show();
}
}
}
showincoming = new Dialog(MainActivity.this);
declare this below int getTotal = 0;
i.e outside else statement
then you can get referance of dialog object and can dissmiss dialog. try this and let me know

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