I am listening to the button on the onCreate task and then calling a function via the XML. The button has a "Button Button02;" on the public class MainActivity, I am listening and all other buttons are working this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* some shit*/
// 2. Access the Button defined in layout XML
// and listen for it here
Button01 = (Button) findViewById(R.id.Button01);
Button02 = (Button) findViewById(R.id.Button02);
Button03 = (Button) findViewById(R.id.Button03);
// X. Instantiate the first text
updateQuotes(textView01);
}
The function I'm trying to call is:
public void calcGold (View view) {
String goldStr = "", purityStr = "", weightStr = "", priceStr = "";
double gold, purity, weight, price;
try {
goldStr = EditText01.getText().toString();
purityStr = EditText02.getText().toString();
weightStr = EditText03.getText().toString();
priceStr = EditText04.getText().toString();
} catch (Exception e) {
Context context1 = getApplicationContext();
CharSequence text1 = "Não foi possível ler as entradas";
Toast toast = Toast.makeText(context1, text1, Toast.LENGTH_SHORT);
toast.show();
}
if (goldStr.isEmpty() || "".equals(goldStr)) {
gold = 0.0;
} else {
gold = Double.parseDouble(EditText01.getText().toString());
}
if (purityStr.isEmpty() || "".equals(purityStr)) {
purity = 0.0;
} else {
purity = Double.parseDouble(EditText02.getText().toString()) / 100;
}
if (weightStr.isEmpty() || "".equals(weightStr)) {
weight = 0.0;
} else {
weight = Double.parseDouble(EditText03.getText().toString());
}
if (priceStr.isEmpty() || "".equals(priceStr)) {
price = 0.0;
} else {
price = Double.parseDouble(EditText04.getText().toString());
}
// price = gold * weight * purity
if (gold == 0) {
gold = price / (purity * weight);
String tempVar = "" + gold;
EditText01.setText(tempVar);
} else if (purity == 0) {
purity = price / (gold * weight);
String tempVar = "" + (purity * 100);
EditText02.setText(tempVar);
} else if (weight == 0) {
weight = price / (gold * purity);
String tempVar = "" + weight;
EditText03.setText(tempVar);
} else if (price == 0){
price = gold * weight * purity;
String tempVar = "";
tempVar = tempVar + price;
EditText04.setText(tempVar);
} else {
Context context = getApplicationContext();
CharSequence text = "Todas as caixas estão cheias";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
And the button on the activity_main.xml is:
<Button
android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginEnd="10dp"
android:layout_marginTop="30dp"
android:onClick="calcGold"
android:text="#string/calc"/>
Still, it crashes when pressing it on a device other than the emulator.
Related
I'm new in programming and I need your help, I have a error when insert number in editText txt50, app crashes please help me, I don't know what is the error:
code:
public class Main2Activity extends AppCompatActivity {
private EditText cinco, cien, doscientos, quinientos, mil, dosmil, cincomil, diezmil, veintemil, cincuentamil, cienmil;
private TextView diezmob;
public static final String nombres = "names";
TextView txtBienvenido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
txtBienvenido = (TextView) findViewById(R.id.txtbienvenido);
String usuario = getIntent().getStringExtra("names");
txtBienvenido.setText("¡Bienvenido(a) Hermano(a) " + usuario + "!");
diezmob = (TextView) findViewById(R.id.txtdiezmob);
cinco = (EditText) findViewById(R.id.txt50);
cien = (EditText) findViewById(R.id.txt100);
doscientos = (EditText) findViewById(R.id.txt200);
quinientos = (EditText) findViewById(R.id.txt500);
mil = (EditText) findViewById(R.id.txt1000);
dosmil = (EditText) findViewById(R.id.txt2000);
cincomil = (EditText) findViewById(R.id.txt5000);
diezmil = (EditText) findViewById(R.id.txt10000);
veintemil = (EditText) findViewById(R.id.txt20000);
cincuentamil = (EditText) findViewById(R.id.txt50000);
cienmil = (EditText) findViewById(R.id.txt100000);
cinco.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if ((cinco.toString().equals("")) && (!cinco.toString().equals(null)) && (cinco.toString().isEmpty() || (cinco.toString().length() >= 0))) {
double valor1 = Double.parseDouble((cinco.getText().toString()));
double valor2 = Double.parseDouble((cien.getText().toString()));
double valor3 = Double.parseDouble((doscientos.getText().toString()));
double valor4 = Double.parseDouble((quinientos.getText().toString()));
double valor5 = Double.parseDouble((mil.getText().toString()));
double valor6 = Double.parseDouble((dosmil.getText().toString()));
double valor7 = Double.parseDouble((cincomil.getText().toString()));
double valor8 = Double.parseDouble((diezmil.getText().toString()));
double valor9 = Double.parseDouble((veintemil.getText().toString()));
double valor10 = Double.parseDouble((cincuentamil.getText().toString()));
double valor11 = Double.parseDouble((cienmil.getText().toString()));
double suma = (valor1 * 50) + (valor2 * 100) + (valor3 * 200) + (valor4 * 500) + (valor5 * 1000) + (valor6 * 2000) + (valor7 * 5000) + (valor8 * 10000) + (valor9 * 20000) + (valor10 * 50000) + (valor11 * 100000);
String resultado = String.valueOf((int) suma);
diezmob.setText(String.valueOf(resultado));
} else {
diezmob.setText("0");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
} }
LogCat: Error when insert number in editText txt50, the app crashes:
java.lang.NumberFormatException: Invalid double: ""
I resolve this error with this code, any error please say it.
package com.example.josue.login;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
private TextView diezmob;
public static final String nombres = "names";
TextView txtBienvenido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
txtBienvenido = (TextView) findViewById(R.id.txtbienvenido);
String usuario = getIntent().getStringExtra("names");
txtBienvenido.setText("¡Bienvenido(a) Hermano(a) " + usuario + "!");
diezmob = (TextView) findViewById(R.id.txtdiezmob);
findViewById(R.id.btncalcular).setOnClickListener(this);
findViewById(R.id.btncalcular5).setOnClickListener(this);
findViewById(R.id.btncalcular10).setOnClickListener(this);
findViewById(R.id.btncalcular15).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btncalcular:
double cinco, cien, doscientos, quinientos, mil, dosmil, cincomil, diezmil, veintemil, cincuentamil, cienmil;
String Cinco = ((EditText) findViewById(R.id.txt50)).getText().toString();
String Cien = ((EditText) findViewById(R.id.txt100)).getText().toString();
String Doscientos = ((EditText) findViewById(R.id.txt200)).getText().toString();
String Quinientos = ((EditText) findViewById(R.id.txt500)).getText().toString();
String Mil = ((EditText) findViewById(R.id.txt1000)).getText().toString();
String Dosmil = ((EditText) findViewById(R.id.txt2000)).getText().toString();
String Cincomil = ((EditText) findViewById(R.id.txt5000)).getText().toString();
String Diezmil = ((EditText) findViewById(R.id.txt10000)).getText().toString();
String Veintemil = ((EditText) findViewById(R.id.txt20000)).getText().toString();
String Cincuentamil = ((EditText) findViewById(R.id.txt50000)).getText().toString();
String Cienmil = ((EditText) findViewById(R.id.txt100000)).getText().toString();
if (Cinco != null && !Cinco.equals("")) {
cinco = Double.valueOf(Cinco);
}else{
cinco = 0;
}
if (Cien != null && !Cien.equals("")){
cien = Double.valueOf(Cien);
}else{
cien=0;
}
if (Doscientos != null && !Doscientos.equals("")) {
doscientos = Double.valueOf(Doscientos);
}else{
doscientos=0;
}
if (Quinientos != null && !Quinientos.equals("")) {
quinientos = Double.valueOf(Quinientos);
}else{
quinientos = 0;
}
if (Mil != null && !Mil.equals("")){
mil = Double.valueOf(Mil);
}else{
mil = 0;
}
if (Dosmil != null && !Dosmil.equals("")) {
dosmil = Double.valueOf(Dosmil);
}else {
dosmil = 0;
}
if (Cincomil != null && !Cincomil.equals("")) {
cincomil = Double.parseDouble(Cincomil);
}else {
cincomil = 0;
}
if (Diezmil !=null && !Diezmil.equals("")) {
diezmil = Double.valueOf(Diezmil);
}else {
diezmil = 0;
}
if (Veintemil != null && !Veintemil.equals("")) {
veintemil = Double.valueOf(Veintemil);
}else {
veintemil = 0;
}
if (Cincuentamil != null && !Cincuentamil.equals("") ) {
cincuentamil = Double.valueOf(Cincuentamil);
}else {
cincuentamil = 0;
}
if (Cienmil != null && !Cienmil.equals("") ) {
cienmil = Double.valueOf(Cienmil);
}else {
cienmil = 0;
}
double suma = (cinco * 50) + (cien * 100) + (doscientos * 200) + (quinientos * 500) + (mil * 1000) +
(dosmil * 2000) + (cincomil * 5000) + (diezmil * 10000) + (veintemil * 20000) + (cincuentamil * 50000) +
(cienmil * 100000);
String resultado = String.valueOf((int)(suma));
diezmob.setText(String.valueOf(resultado));
break;
case R.id.btncalcular5:
Intent i = new Intent(this, Main5Activity.class);
i.putExtra("dato",diezmob.getText().toString());
startActivity(i);
break;
case R.id.btncalcular10:
Intent ii = new Intent(this, Main5Activity.class);
startActivity(ii);
break;
case
R.id.btncalcular15:
Intent iii = new Intent(this, Main5Activity.class);
startActivity(iii);
break;
default:
break;
}
}
}
Let's evaluate this:
if ((cinco.toString().equals("")) && (!cinco.toString().equals(null)) && (cinco.toString().isEmpty() || (cinco.toString().length() >= 0))) {
double valor1 = Double.parseDouble((cinco.getText().toString()));
You are saying if ("cinco is an empty string") and (not null) and ((isEmpty(same as empty string)) or is a length >= 0) then parse double
I am pretty sure the only time this evaluates to true is if cinco is empty which will result in a NumberFormatException because you are trying to parse cinco for a double while it is empty. You will have to handle exceptions with a try-catch block:
try {
double valor1 = Double.parseDouble((cinco.getText().toString()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
or construct if statements that don't allow cinco to be evaluated if it is empty:
if(cinco.toString() != null && !(cinco.toString().isEmpty() {
double valor1 = Double.parseDouble((cinco.getText().toString()));
}
edit: All of the Double.parseDouble in your code will throw NumberFormatExceptions not just cinco by the way. That one is just first so this answer applies to all of the parses.
I want to calculate the average of grades, now I have the basics and the layout. When the EditText is left open it throws a NumberFormatException. Can someone explain me how to check for this?
Any tips etc. are welcome!
P.S. my EditText are set to NumberDecimal, so I have no 'wrong input' type.
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
final Button addGradeButton = findViewById(R.id.addGradeButton)
calaculateButton.setOnClickListener(new View.onClickListener() {
#SupressLint("SetTextI18n")
public void onClick(View v) {
double grade[] = {Double.parseDouble(((EditText) findViewById(R.id.grade1)).getText().toString());
double weight[] = {Double.parseDouble(((EditText) findViewById(R.id.weight1)).getText().toString());
double weightTotal = weight[0]; double sum = grade[0] * weight[0]
double average = sum / weightTotal
#SuppressLint("DefaultLocale") String averageResult = String.format(%.2f, average);
averageView.setText(averageText + " " + averageResult);
Check your error condititions before attempting to do the thing that creates the error
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
final Button addGradeButton = findViewById(R.id.addGradeButton)
EditText[] grades = new EditText[] {
(EditText) findViewById(R.id.grade1)
};
EditText[] weights = new EditText[] {
(EditText) findViewById(R.id.weight1)
};
calculateButton.setOnClickListener(new View.onClickListener() {
#Override
public void onClick(View v) {
String grade1 = grades[0].getText().toString();
String weight1 = weights[0].getText().toString();
if (TextUtils.isEmpty(grade1) || TextUtils.isEmpty(weight1)) {
return; // TODO: Show some error
}
double sum = Double.parseDouble(grade1) * Double.parseDouble(weight1);
You can try a "try - catch" to manage the exception like this.
try {
double grade = Double.parseDouble(((EditText) findViewById(R.id.numberanswer)).getText().toString());
answer.setText("" + grade);
} catch (NumberFormatException e){
Toast.makeText(getApplicationContext(),"Please insert a number",Toast.LENGTH_SHORT).show();
}
I've completed it with a "try-catch" statement, this catches the NumberFormatException every time when a field is left open.
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
final Button addGradeButton = findViewById(R.id.addGradeButton)
calaculateButton.setOnClickListener(new View.onClickListener() {
#SupressLint("SetTextI18n")
public void onClick(View v) {
try {
double grade[] = {Double.parseDouble(((EditText) findViewById(R.id.grade1)).getText().toString());
double weight[] = {Double.parseDouble(((EditText) findViewById(R.id.weight1)).getText().toString());
double weightTotal = weight[0]; double sum = grade[0] * weight[0]
double average = sum / weightTotal
#SuppressLint("DefaultLocale") String averageResult = String.format(%.2f, average);
averageView.setText(averageText + " " + averageResult);
{ catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "There is a empty field!", Toast.LENGTH_LONG).show();
}
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
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.
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.