Hi I need some help to create a function can fill an EditText by the first Letter and the first Vowel of another EditText.
Something like this:
EditText = Jhon
Output = JO
I have this but still not working;
public class MainActivity extends Activity {
private EditText Result;
private EditText MyName;
private EditText showResult;
private String MyVowel;
private String cadena, PartOne;
private int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Result = (TextView) findViewById(R.id.showResult);
MyName= (EditText)findViewById(R.id.NameInput);
getInfo = (Button)findViewById(R.id.getInfoButton);
getInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String inputText = myName.getText().toString();
String partOne= inputText.substring(0,1);
for(int i=0;i <inputText.length();i++){
if((inputText.charAt(i) == 'a') ||
(inputText.charAt(i) == 'e') ||
(inputText.charAt(i) == 'i') ||
(inputText.charAt(i) == 'o') ||
(inputText.charAt(i) == 'u')) {
System.out.println(cadena);
}
}
showResult.setText(PartOne);
}
});
}
}
You havn't said what your issue is. If you are stuck at the logic see the below code,
private String getShortForm(String inputText){
List<Character> vowels = new ArrayList<Character>() {
{
add('a');
add('e');
add('i');
add('o');
add('u');
add('A');
add('E');
add('I');
add('O');
add('U');
}
};
String partOne = inputText.substring(0, 1);
for (int i = 0; i < inputText.length(); i++) {
char c = inputText.charAt(i);
if(vowels.contains(c)){
partOne += c;
break;
}
}
return partOne.toUpperCase();
}
Usage inside onClick,
Result.setText(getShortForm(inputText));
Here's the solution
public class MainActivity extends AppCompatActivity{
private TextView Result;
private EditText MyName;
private Button getInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Result = (TextView) findViewById(R.id.showResult);
MyName= (EditText)findViewById(txtText);
getInfo = (Button)findViewById(btnSpeak);
getInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputText = MyName.getText().toString();
String partOne= inputText.substring(0,1);
Log.e("inputText: "+inputText, "part one: "+partOne);
String vowels = "";
for(int i=0;i <inputText.length();i++){
if((inputText.charAt(i) == 'a') ||
(inputText.charAt(i) == 'e') ||
(inputText.charAt(i) == 'i') ||
(inputText.charAt(i) == 'o') ||
(inputText.charAt(i) == 'u') ||
(inputText.charAt(i) == 'A') ||
(inputText.charAt(i) == 'E') ||
(inputText.charAt(i) == 'I') ||
(inputText.charAt(i) == 'O') ||
(inputText.charAt(i) == 'U')){
vowels = vowels+inputText.charAt(i);
}
}
Log.e("inputText: "+inputText, "vowelsFinal: "+vowels);
String partTwo = vowels.substring(0,1);
Log.e("inputText: "+inputText, "partTwo: "+partTwo);
String finalString = partOne+partTwo;
Log.e("inputText: "+inputText, "finalString: "+finalString);
Result.setText(finalString);
}
});
}
}
Hope this solves your issue :)
Related
I am currently doing a quiz app and the question should be coming out based on the answer. The below is my code. I have been looking online to try various options and cannot find a way to resolve it without making lots of errors. The code for my quiz activity is below. Thanks.
quiz.java
public class quiz extends AppCompatActivity implements View.OnClickListener {
TextView questionNo, question;
RadioGroup rg;
Button quiz_nextBtn, quiz_PrevBtn;
RadioButton rb1, rb2;
int current_question = 0;
int next_question=0;
private quizAdapter[] questionBank = new quizAdapter[]{
new quizAdapter(R.string.q1, R.string.q1_a1, R.string.q1_a2),
new quizAdapter(R.string.q2, R.string.q2_a1, R.string.q2_a2),
new quizAdapter(R.string.q3, R.string.q3_a1, R.string.q3_a2),
new quizAdapter(R.string.q4, R.string.q4_a1, R.string.q4_a2),
new quizAdapter(R.string.q5, R.string.q5_a1, R.string.q5_a2),
new quizAdapter(R.string.q6, R.string.q6_a1, R.string.q6_a2),
new quizAdapter(R.string.q7, R.string.q7_a1, R.string.q7_a2)
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
rg = findViewById(R.id.quiz_answer);
rb1 = findViewById(R.id.rb1);
rb2 = findViewById(R.id.rb2);
questionNo = findViewById(R.id.quiz_questionNo);
question = findViewById(R.id.quiz_question);
quiz_nextBtn = findViewById(R.id.quiz_nextBtn);
quiz_PrevBtn = findViewById(R.id.quiz_PrevBtn);
quiz_nextBtn.setOnClickListener(this);
quiz_PrevBtn.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.quiz_nextBtn:
if(current_question<7){
current_question++;
if(current_question == 6){
question.setText("We are finish");
}
else {
if(current_question == 0 && rb1.isChecked()){
current_question = 1;
}
else if (current_question == 0 && rb2.isChecked()){
current_question = 4;
}
else if (current_question == 1 && rb1.isChecked()){
current_question = 2;
}
else if (current_question == 1 && rb2.isChecked()){
current_question = 3;
}
else if (current_question == 4 && rb1.isChecked()){
current_question = 5;
}
else if (current_question == 4 && rb2.isChecked()){
current_question = 6;
}
updateQuestion();
}
}
break;
case R.id.quiz_PrevBtn:
if (current_question > 0) {
current_question = (current_question - 1) % questionBank.length;
updateQuestion();
}
}
}
private void updateQuestion() {
Log.d("Current", "onClick: " + current_question);
question.setText(questionBank[current_question].getQuestion());
rb1.setText(questionBank[current_question].getRb1());
rb2.setText(questionBank[current_question].getRb2());
}
}
quizAdapter.java
public class quizAdapter {
private int question;
private int rb1;
private int rb2;
public quizAdapter(int question, int rb1, int rb2)
{
this.question = question;
this.rb1 = rb1;
this.rb2 = rb2;
}
public int getQuestion()
{
return question;
}
public int getRb1()
{
return rb1;
}
public int getRb2()
{
return rb2;
}
}
I think a better way would be to use a HashMap and set the quiz answers and questions as key value pairs, for what your trying to implement you will have multiple keys (the value of the current question and option chosen) for a single value(the next question to be shown).
one way to do it would be to create a custom HashMap like below
import java.util.HashMap;
import java.util.Map;
class Key<K1, K2> {
public K1 key1;
public K2 key2;
public Key(K1 key1, K2 key2) {
this.key1 = key1;
this.key2 = key2;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
if (key1 != null ? !key1.equals(key.key1) : key.key1 != null) return false;
if (key2 != null ? !key2.equals(key.key2) : key.key2 != null) return false;
return true;
}
#Override
public int hashCode() {
int result = key1 != null ? key1.hashCode() : 0;
result = 31 * result + (key2 != null ? key2.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "[" + key1 + ", " + key2 + "]";
}
}
class Main
{
public static void main(String[] args) {
// Create a HashMap with Key as key
Map<Key, String> multiKeyMap = new HashMap<>();
// [key1, key2] -> value1
Key k12 = new Key("key1", "key2");
multiKeyMap.put(k12, "value1");
// [key3, key4] -> value2
Key k34 = new Key("key3", "key4");
multiKeyMap.put(k34, "value2");
// print multi-key map
System.out.println(multiKeyMap);
// print value corresponding to key1 and key2
System.out.println(multiKeyMap.get(k12));
}
}
more explanation can be found in this link
https://www.techiedelight.com/implement-map-with-multiple-keys-multikeymap-java/
I'm making a tictactoe app where corresponding messages reflect whose (Player X or Player Y) turn it is and who wins. This worked with no issues. Then I added a feature using Preferences and Fragments, where the user could add specific names to Player X and Player Y and the messages would implement their names. However, now everytime I open the app it remembers a previous session of the game. I think it loads the game as it was the previous time it was paused. How can I get it to load a new game everytime the emulator opens?
I'm sure it's something simple, I'm just new to AndroidStudio and I'm out of ideas. Thank you!
This is my Activity code
package com.asebastian.tictactoe;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class TictactoeActivity extends Activity implements OnClickListener {
private Button btn1;
private Button btn2;
private Button btn3;
private Button btn4;
private Button btn5;
private Button btn6;
private Button btn7;
private Button btn8;
private Button btn9;
private TextView txtmsg;
private int r = 0;
private String btn1txt = " ";
private String btn2txt = " ";
private String btn3txt = " ";
private String btn4txt = " ";
private String btn5txt = " ";
private String btn6txt = " ";
private String btn7txt = " ";
private String btn8txt = " ";
private String btn9txt = " ";
private String Xname = " ";
private String Yname = " ";
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tictactoe);
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
txtmsg = (TextView)findViewById(R.id.txtMessage);
txtmsg.setText("Player X's turn");
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.tictactoe,menu);
return true;
}
#Override
public void onPause(){
SharedPreferences.Editor editor = prefs.edit();
editor.putString("btn1txt",btn1.getText().toString());
editor.putString("btn2txt",btn2.getText().toString());
editor.putString("btn3txt",btn3.getText().toString());
editor.putString("btn4txt",btn4.getText().toString());
editor.putString("btn5txt",btn5.getText().toString());
editor.putString("btn6txt",btn6.getText().toString());
editor.putString("btn7txt",btn7.getText().toString());
editor.putString("btn8txt",btn8.getText().toString());
editor.putString("btn9txt",btn9.getText().toString());
editor.putInt("r",r);
editor.commit();
super.onPause();
}
#Override
public void onResume(){
super.onResume();
btn1.setText(prefs.getString("btn1txt",""));
btn2.setText(prefs.getString("btn2txt",""));
btn3.setText(prefs.getString("btn3txt",""));
btn4.setText(prefs.getString("btn4txt",""));
btn5.setText(prefs.getString("btn5txt",""));
btn6.setText(prefs.getString("btn6txt",""));
btn7.setText(prefs.getString("btn7txt",""));
btn8.setText(prefs.getString("btn8txt",""));
btn9.setText(prefs.getString("btn9txt",""));
Xname = prefs.getString("pref_edittextX","");
Yname = prefs.getString("pref_edittextY","");
txtmsg.setText(Xname + "'s turn");
r = prefs.getInt("r",0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.new_game){
btn1.setEnabled(true);
btn2.setEnabled(true);
btn3.setEnabled(true);
btn4.setEnabled(true);
btn5.setEnabled(true);
btn6.setEnabled(true);
btn7.setEnabled(true);
btn8.setEnabled(true);
btn9.setEnabled(true);
btn1.setText("");
btn2.setText("");
btn3.setText("");
btn4.setText("");
btn5.setText("");
btn6.setText("");
btn7.setText("");
btn8.setText("");
btn9.setText("");
r = 0;
txtmsg.setText("Player X's turn");
}
else if (item.getItemId() == R.id.action_settings) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn1) {
r++;
if ((r % 2) == 0) {
btn1.setText("O");
} else {
btn1.setText("X");
}
}
if (v.getId() == R.id.btn2) {
r++;
if ((r % 2) == 0) {
btn2.setText("O");
} else {
btn2.setText("X");
}
}
if (v.getId() == R.id.btn3) {
r++;
if ((r % 2) == 0) {
btn3.setText("O");
} else {
btn3.setText("X");
}
}
if (v.getId() == R.id.btn4) {
r++;
if ((r % 2) == 0) {
btn4.setText("O");
} else {
btn4.setText("X");
}
}
if (v.getId() == R.id.btn5) {
r++;
if ((r % 2) == 0) {
btn5.setText("O");
} else {
btn5.setText("X");
}
}
if (v.getId() == R.id.btn6) {
r++;
if ((r % 2) == 0) {
btn6.setText("O");
} else {
btn6.setText("X");
}
}
if (v.getId() == R.id.btn7) {
r++;
if ((r % 2) == 0) {
btn7.setText("O");
} else {
btn7.setText("X");
}
}
if (v.getId() == R.id.btn8) {
r++;
if ((r % 2) == 0) {
btn8.setText("O");
} else {
btn8.setText("X");
}
}
if (v.getId() == R.id.btn9) {
r++;
if ((r % 2) == 0) {
btn9.setText("O");
} else {
btn9.setText("X");
}
}
if (Xname.isEmpty() && Yname.isEmpty()) {
if ((r % 2) == 0) {
txtmsg.setText("Player X's turn");
} else {
txtmsg.setText("Player Y's turn");
}
} else {
if ((r % 2) == 0) {
txtmsg.setText(Xname + "'s turn");
} else {
txtmsg.setText(Yname + "'s turn");
}
}
btn1txt = btn1.getText().toString();
btn2txt = btn2.getText().toString();
btn3txt = btn3.getText().toString();
btn4txt = btn4.getText().toString();
btn5txt = btn5.getText().toString();
btn6txt = btn6.getText().toString();
btn7txt = btn7.getText().toString();
btn8txt = btn8.getText().toString();
btn9txt = btn9.getText().toString();
calcWinner();
}
public void calcWinner() {
if (btn1txt == "X" && btn2txt == "X" && btn3txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn1txt == "O" && btn2txt == "O" && btn3txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn4txt == "X" && btn5txt == "X" && btn6txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn4txt == "O" && btn5txt == "O" && btn6txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn7txt == "X" && btn8txt == "X" && btn8txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn7txt == "O" && btn8txt == "O" && btn9txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn1txt == "X" && btn4txt == "X" && btn7txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn1txt == "O" && btn4txt == "O" && btn7txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn2txt == "X" && btn5txt == "X" && btn8txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn2txt == "O" && btn5txt == "O" && btn8txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn3txt == "X" && btn6txt == "X" && btn9txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn3txt == "O" && btn6txt == "O" && btn9txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn1txt == "X" && btn5txt == "X" && btn9txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn1txt == "O" && btn5txt == "O" && btn9txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn3txt == "X" && btn5txt == "X" && btn7txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn3txt == "O" && btn5txt == "O" && btn7txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (r == 9) {
txtmsg.setText("Tie Game!");
disableButtons();
}
}
public void disableButtons(){
btn1.setEnabled(false);
btn2.setEnabled(false);
btn3.setEnabled(false);
btn4.setEnabled(false);
btn5.setEnabled(false);
btn6.setEnabled(false);
btn7.setEnabled(false);
btn8.setEnabled(false);
btn9.setEnabled(false);
}
}
This is my Fragment code:
package com.asebastian.tictactoe;
import android.os.Bundle;
import android.preference.PreferenceFragment;
/**
* A simple {#link Fragment} subclass.
*/
public class SettingsFragment extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
This is the code to add the Fragment:
package com.asebastian.tictactoe;
import android.app.Activity;
import android.os.Bundle;
public class SettingsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,new
SettingsFragment()).commit();
}
}
So i guess by Storing/Restoring to/from SharedPreferences that you are trying to save the state of the activity!
And that is wrong (unless you deleted the SharedPreferences saved content in onDestroy()) becuase every time you open the app again the on onResume() will be called and hence state will be restored from SharedPreferences.
See The Activity Lifecycle
So, The solution is not to use SharedPreferences to save/restore activity state but instead override the methods onSaveInstanceState & onRestoreInstanceState like this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putString("btn1txt",btn1.getText().toString());
// and So on
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
and
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
btn1.setText(savedInstanceState.getString("btn1txt"));
// and so on
}
Note:
The system calls onRestoreInstanceState() after the onStart()method.
Also The system calls onRestoreInstanceState() only if there is a saved state to restore.
See Saving and restoring activity state
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I wrote a code for tictactoe game, however it it showing me this error at run time:
Exception: Unable to instantiate activity ComponentInfo{com.tictactoe.ajaykulkarni.tictactoe/com.tictactoe.ajaykulkarni.tictactoe.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
My MainActivity is:
package com.tictactoe.ajaykulkarni.tictactoe;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//protected DrawerLayout mdrawerLayout;
/*Game plan*/
private TicTacToeGame mGame;
// Buttons making up the board
private Button mBoardButtons[];
private Button mNewGame;
// Various text displayed
private TextView mInfoTextView;
private TextView mPlayerOneCount;
private TextView mTieCount;
private TextView mPlayerTwoCount;
private TextView mPlayerOneText;
private TextView mPlayerTwoText;
private int mPlayerOneCounter = 0;
private int mTieCounter = 0;
private int mPlayerTwoCounter = 0;
private boolean mPlayerOneFirst = true;
private boolean mIsSinglePlayer = false;
private boolean mIsPlayerOneTurn = true;
private boolean mGameOver = false;
boolean mGameType = getIntent().getExtras().getBoolean("gameType");
private Button[] getmBoardButtons() {
mBoardButtons = new Button[mGame.getBOARD_SIZE()];
mBoardButtons[0] = (Button) findViewById(R.id.one);
mBoardButtons[1] = (Button) findViewById(R.id.two);
mBoardButtons[2] = (Button) findViewById(R.id.three);
mBoardButtons[3] = (Button) findViewById(R.id.four);
mBoardButtons[4] = (Button) findViewById(R.id.five);
mBoardButtons[5] = (Button) findViewById(R.id.six);
mBoardButtons[6] = (Button) findViewById(R.id.seven);
mBoardButtons[7] = (Button) findViewById(R.id.eight);
mBoardButtons[8] = (Button) findViewById(R.id.nine);
addListenerOnButton();
// setup the textviews
mInfoTextView = (TextView) findViewById(R.id.information);
mPlayerOneCount = (TextView) findViewById(R.id.humanCount);
mTieCount = (TextView) findViewById(R.id.tiesCount);
mPlayerTwoCount = (TextView) findViewById(R.id.androidCount);
mPlayerOneText = (TextView) findViewById(R.id.human);
mPlayerTwoText = (TextView) findViewById(R.id.android);
// set the initial counter display values
mPlayerOneCount.setText(Integer.toString(mPlayerOneCounter));
mTieCount.setText(Integer.toString(mTieCounter));
mPlayerTwoCount.setText(Integer.toString(mPlayerTwoCounter));
// create a new game object
mGame = new TicTacToeGame();
// start a new game
startNewGame(mGameType);
return mBoardButtons;
}
//mBoardButtons = new Button[mGame.getBOARD_SIZE()];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.play) {
Log.d("DEBUG", "Play option selected!");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
} else if (id == R.id.exit) {
Log.d("DEBUG", "Exit option selected!");
MainActivity.this.finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void addListenerOnButton(){
mNewGame = (Button) findViewById(R.id.NewGame);
mNewGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startNewGame(mIsSinglePlayer);
}
});
}
// start a new game
// clears the board and resets all buttons / text
// sets game over to be false
private void startNewGame(boolean isSingle)
{
this.mIsSinglePlayer = isSingle;
mGame.clearBoard();
for (int i = 0; i < mBoardButtons.length; i++)
{
mBoardButtons[i].setText("");
mBoardButtons[i].setEnabled(true);
mBoardButtons[i].setOnClickListener(new ButtonClickListener(i));
///mBoardButtons[i].setBackgroundDrawable(getResources().getDrawable(R.drawable.blank));
}
if (mIsSinglePlayer)
{
mPlayerOneText.setText("User:");
mPlayerTwoText.setText("Android:");
if (mPlayerOneFirst)
{
mInfoTextView.setText(R.string.first_human);
mPlayerOneFirst = false;
}
else
{
mInfoTextView.setText(R.string.turn_computer);
int move = mGame.getComputerMove();
setMove(mGame.PLAYER_TWO, move);
mPlayerOneFirst = true;
}
}
mGameOver = false;
}
private class ButtonClickListener implements View.OnClickListener
{
int location;
public ButtonClickListener(int location)
{
this.location = location;
}
public void onClick(View view)
{
if (!mGameOver)
{
if (mBoardButtons[location].isEnabled())
{
if (mIsSinglePlayer)
{
setMove(mGame.PLAYER_ONE, location);
int winner = mGame.checkForWinner();
if (winner == 0)
{
mInfoTextView.setText(R.string.turn_computer);
int move = mGame.getComputerMove();
setMove(mGame.PLAYER_TWO, move);
winner = mGame.checkForWinner();
}
if (winner == 0)
mInfoTextView.setText(R.string.turn_human);
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner == 2)
{
mInfoTextView.setText(R.string.result_human_wins);
mPlayerOneCounter++;
mPlayerOneCount.setText(Integer.toString(mPlayerOneCounter));
mGameOver = true;
}
else
{
mInfoTextView.setText(R.string.result_android_wins);
mPlayerTwoCounter++;
mPlayerTwoCount.setText(Integer.toString(mPlayerTwoCounter));
mGameOver = true;
}
}
else
{
if (mIsPlayerOneTurn)
setMove(mGame.PLAYER_ONE, location);
else
setMove(mGame.PLAYER_TWO, location);
int winner = mGame.checkForWinner();
if (winner == 0)
{
if (mIsPlayerOneTurn)
{
mInfoTextView.setText(R.string.turn_player_two);
mIsPlayerOneTurn = false;
}
else
{
mInfoTextView.setText(R.string.turn_player_one);
mIsPlayerOneTurn = true;
}
}
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner == 2)
{
mInfoTextView.setText(R.string.result_player_one_wins);
mPlayerOneCounter++;
mPlayerOneCount.setText(Integer.toString(mPlayerOneCounter));
mGameOver = true;
mIsPlayerOneTurn = false;
}
else
{
mInfoTextView.setText(R.string.result_player_two_wins);
mPlayerTwoCounter++;
mPlayerTwoCount.setText(Integer.toString(mPlayerTwoCounter));
mGameOver = true;
mIsPlayerOneTurn = true;
}
}
}
}
}
}
// set move for the current player
private void setMove(char player, int location)
{
mGame.setMove(player, location);
mBoardButtons[location].setEnabled(false);
if (player == mGame.PLAYER_ONE)
mBoardButtons[location].setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_x));
else
mBoardButtons[location].setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_o));
}
}
and TicTacToeGame.class is:
package com.tictactoe.ajaykulkarni.tictactoe;
/**
* Created by Ajay Kulkarni-enEXL on 02/16/2017.
*/
import java.util.Random;
public class TicTacToeGame {
private char mBoard[];
private final static int BOARD_SIZE = 9;
public static final char PLAYER_ONE = 'X';
public static final char PLAYER_TWO = '0';
public static final char EMPTY_SPACE = ' ';
private Random mRand;
public static int getBOARD_SIZE() {
// Return the size of the board
return BOARD_SIZE;
}
public TicTacToeGame(){
mBoard = new char[BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++)
mBoard[i] = EMPTY_SPACE;
mRand = new Random();
}
// Clear the board of all X's and O's
public void clearBoard()
{
for (int i = 0; i < BOARD_SIZE; i++)
{
mBoard[i] = EMPTY_SPACE;
}
}
// set the given player at the given location on the game board.
// the location must be available, or the board will not be changed.
public void setMove(char player, int location)
{
mBoard[location] = player;
}
// Return the best move for the computer to make. You must call setMove()
// to actually make the computer move to that location.
public int getComputerMove()
{
int move;
// First see if there's a move O can make to win
for (int i = 0; i < getBOARD_SIZE(); i++)
{
if (mBoard[i] != PLAYER_ONE && mBoard[i] != PLAYER_TWO)
{
char curr = mBoard[i];
mBoard[i] = PLAYER_TWO;
if (checkForWinner() == 3)
{
setMove(PLAYER_TWO, i);
return i;
}
else
mBoard[i] = curr;
}
}
// See if there's a move O can make to block X from winning
for (int i = 0; i < getBOARD_SIZE(); i++)
{
if (mBoard[i] != PLAYER_ONE && mBoard[i] != PLAYER_TWO)
{
char curr = mBoard[i];
mBoard[i] = PLAYER_ONE;
if (checkForWinner() == 2)
{
setMove(PLAYER_TWO, i);
return i;
}
else
mBoard[i] = curr;
}
}
// Generate random move
do
{
move = mRand.nextInt(getBOARD_SIZE());
} while (mBoard[move] == PLAYER_ONE || mBoard[move] == PLAYER_TWO);
setMove(PLAYER_TWO, move);
return move;
}
// Check for a winner and return a status value indicating who has won.
// Return 0 if no winner or tie yet, 1 if it's a tie, 2 if X won, or 3
// if O won.
public int checkForWinner()
{
// Check horizontal wins
for (int i = 0; i <= 6; i += 3)
{
if (mBoard[i] == PLAYER_ONE &&
mBoard[i+1] == PLAYER_ONE &&
mBoard[i+2] == PLAYER_ONE)
return 2;
if (mBoard[i] == PLAYER_TWO &&
mBoard[i+1] == PLAYER_TWO &&
mBoard[i+2] == PLAYER_TWO)
return 3;
}
// Check vertical wins
for (int i = 0; i <= 2; i++)
{
if (mBoard[i] == PLAYER_ONE &&
mBoard[i+3] == PLAYER_ONE &&
mBoard[i+6] == PLAYER_ONE)
return 2;
if (mBoard[i] == PLAYER_TWO &&
mBoard[i+3] == PLAYER_TWO &&
mBoard[i+6] == PLAYER_TWO)
return 3;
}
// Check for diagonal wins
if ((mBoard[0] == PLAYER_ONE &&
mBoard[4] == PLAYER_ONE &&
mBoard[8] == PLAYER_ONE) ||
mBoard[2] == PLAYER_ONE &&
mBoard[4] == PLAYER_ONE &&
mBoard[6] == PLAYER_ONE)
return 2;
if ((mBoard[0] == PLAYER_TWO &&
mBoard[4] == PLAYER_TWO &&
mBoard[8] == PLAYER_TWO) ||
mBoard[2] == PLAYER_TWO &&
mBoard[4] == PLAYER_TWO &&
mBoard[6] == PLAYER_TWO)
return 3;
// Check for a tie
for (int i = 0; i < getBOARD_SIZE(); i++)
{
// if we find a number, then no one has won yet
if (mBoard[i] != PLAYER_ONE && mBoard[i] != PLAYER_TWO)
return 0;
}
// If we make it through the previous loop, all places are taken, so it's a tie
return 1;
}
}
How can I fix that error?
You are trying to get extras from a field in the Activity, i.e. you are trying to get the extras before the Activity is created. If you get the extras from the onCreate method, it won't be a null value.
Example:
boolean mGameType;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGameType = getIntent().getExtras().getBoolean("gameType");
...
}
EDIT: If you want to send extra from one Activity to another, you should start it this way:
startActivity(new Intent(SenderActivity.this, MainActivity.class)
.putExtra("gameType", true));
Currently, I am making an android app that is going to be a very simple memory game where 1 random button is going to be highlighted, then the user must click the button that was highlighted after the button goes back to normal. If the user gets the button correct the original button that was highlighted the first time will light up, then another random button will light up after just like the first time and they have to click them in order. For further clarification if your unsure its kind of like Simon (The game).
Currently the game is just going to the next random button instead of repeating AND THEN going to a new one and i'm unsure how to change that. Any help would be greatly appreciated!
package com.MakeItMobile.fixmymemory;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainScreen extends Activity implements OnClickListener {
Button buttonRed, buttonYellow, buttonOrange, buttonBlack, buttonGreen,
buttonPurple, buttonPink, buttonLime, buttonDarkBlue;
Random randNumber;
List<Integer> whichButton;
int userInput[] = {};
int counter = 0;
int compareCounter = 0;
int n = 0;
Boolean yourTurn = false;
Boolean aiTurn = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainscreen);
//Getting the buttons
buttonRed = (Button) findViewById(R.id.buttonRed);
buttonYellow = (Button) findViewById(R.id.buttonYellow);
buttonOrange = (Button) findViewById(R.id.buttonOrange);
buttonBlack = (Button) findViewById(R.id.buttonBlack);
buttonGreen = (Button) findViewById(R.id.buttonGreen);
buttonPurple = (Button) findViewById(R.id.buttonPurple);
buttonPink = (Button) findViewById(R.id.buttonPink);
buttonLime = (Button) findViewById(R.id.buttonLime);
buttonDarkBlue = (Button) findViewById(R.id.buttonDarkBlue);
//Setting them clickable
buttonRed.setOnClickListener(this);
buttonYellow.setOnClickListener(this);
buttonOrange.setOnClickListener(this);
buttonBlack.setOnClickListener(this);
buttonGreen.setOnClickListener(this);
buttonPurple.setOnClickListener(this);
buttonPink.setOnClickListener(this);
buttonLime.setOnClickListener(this);
buttonDarkBlue.setOnClickListener(this);
//Giving them a tag for easier comparison in onClick
buttonRed.setTag(1);
buttonYellow.setTag(2);
buttonOrange.setTag(3);
buttonBlack.setTag(4);
buttonGreen.setTag(5);
buttonPurple.setTag(6);
buttonPink.setTag(7);
buttonLime.setTag(8);
buttonDarkBlue.setTag(9);
//Showing a would you like to play dialog
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
switch (which) {
case (DialogInterface.BUTTON_POSITIVE):
whenStarted();
break;
case (DialogInterface.BUTTON_NEGATIVE):
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Would you like to begin?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
// Main loop
public void whenStarted() {
if (aiTurn) {
whichButton = new ArrayList<Integer>();
repeatBack();
randomNumber();
n = randomNumber();
if (n == 1) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 2) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 3) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 4) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 5) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 6) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 7) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 8) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (n == 9) {
delay(R.drawable.buttonblueclicked, R.drawable.buttonblue);
}
whichButton.add(n);
yourTurn = true;
} else if (yourTurn) {
}
}
// Repeating back what buttons were clicked each turn
public void repeatBack() {
for (int i = 0; i < whichButton.size(); i++) {
if (whichButton.get(i) == 1) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 2) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 3) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 4) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 5) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 6) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 7) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 8) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
} else if (whichButton.get(i) == 9) {
delayRepeat(R.drawable.buttonblueclicked, R.drawable.buttonblue);
}
System.out.println("Which button size and number is "
+ whichButton.size());
System.out.println(i);
}
}
// For repeating back the buttons
// On start this method sets the button to the color and waits 1 second
// On finish it changes back to the original image
public void delayRepeat(final int newStartID, final int endID) {
final int time = 1000;
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
for (int i = 0; i < whichButton.size(); i++) {
if (whichButton.get(i) == 1) {
buttonRed.setBackgroundResource(endID);
} else if (whichButton.get(i) == 2) {
buttonYellow.setBackgroundResource(endID);
} else if (whichButton.get(i) == 3) {
buttonOrange.setBackgroundResource(endID);
} else if (whichButton.get(i) == 4) {
buttonBlack.setBackgroundResource(endID);
} else if (whichButton.get(i) == 5) {
buttonGreen.setBackgroundResource(endID);
} else if (whichButton.get(i) == 6) {
buttonPurple.setBackgroundResource(endID);
} else if (whichButton.get(i) == 7) {
buttonPink.setBackgroundResource(endID);
} else if (whichButton.get(i) == 8) {
buttonLime.setBackgroundResource(endID);
} else if (whichButton.get(i) == 9) {
buttonDarkBlue.setBackgroundResource(endID);
}
}
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
for (int i = 0; i < whichButton.size(); i++) {
// TODO Auto-generated method stub
if (whichButton.get(i) == 1) {
buttonRed.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 2) {
buttonYellow.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 3) {
buttonOrange.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 4) {
buttonBlack.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 5) {
buttonGreen.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 6) {
buttonPurple.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 7) {
buttonPink.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 8) {
buttonLime.setBackgroundResource(newStartID);
} else if (whichButton.get(i) == 9) {
buttonDarkBlue
.setBackgroundResource(newStartID);
}
}
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
// creating a blinking color button for each specific random number
// On start this method sets the button to the color and waits 1 second
// On finish it changes back to the original image
public void delay(final int newStartID, final int endID) {
final int time = 1000;
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
if (n == 1) {
buttonRed.setBackgroundResource(endID);
} else if (n == 2) {
buttonYellow.setBackgroundResource(endID);
} else if (n == 3) {
buttonOrange.setBackgroundResource(endID);
} else if (n == 4) {
buttonBlack.setBackgroundResource(endID);
} else if (n == 5) {
buttonGreen.setBackgroundResource(endID);
} else if (n == 6) {
buttonPurple.setBackgroundResource(endID);
} else if (n == 7) {
buttonPink.setBackgroundResource(endID);
} else if (n == 8) {
buttonLime.setBackgroundResource(endID);
} else if (n == 9) {
buttonDarkBlue.setBackgroundResource(endID);
}
new CountDownTimer(time, 1000) {
#Override
public void onFinish() {
// TODO Auto-generated method stub
if (n == 1) {
buttonRed.setBackgroundResource(newStartID);
} else if (n == 2) {
buttonYellow.setBackgroundResource(newStartID);
} else if (n == 3) {
buttonOrange.setBackgroundResource(newStartID);
} else if (n == 4) {
buttonBlack.setBackgroundResource(newStartID);
} else if (n == 5) {
buttonGreen.setBackgroundResource(newStartID);
} else if (n == 6) {
buttonPurple.setBackgroundResource(newStartID);
} else if (n == 7) {
buttonPink.setBackgroundResource(newStartID);
} else if (n == 8) {
buttonLime.setBackgroundResource(newStartID);
} else if (n == 9) {
buttonDarkBlue.setBackgroundResource(newStartID);
}
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
}.start();
}
//Used to generate a different random number each time
public int randomNumber() {
randNumber = new Random();
int n = randNumber.nextInt(9) + 1;
return n;
}
// On click for when they click each button
// Buttons are set to specific tags in the onCreate
// Checks if the tag is equal to what the output of whichButton.get(x) is
// If it isn't they fail
public void onClick(View v) {
// TODO Auto-generated method stub
int tag = (Integer) v.getTag();
for (int x = 0; x < whichButton.size(); x++) {
if (tag == 1 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 2 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 3 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 4 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 5 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 6 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 7 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 8 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else if (tag == 9 && tag == whichButton.get(x)) {
aiTurn = true;
whenStarted();
} else {
aiTurn = false;
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
switch (which) {
case (DialogInterface.BUTTON_POSITIVE):
aiTurn = true;
whenStarted();
break;
case (DialogInterface.BUTTON_NEGATIVE):
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You failed, would you like to play again?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
}
}
}
In your onClick(...) handler you're calling whenStarted() each time.
In the whenStarted() method you do this...
whichButton = new ArrayList<Integer>();
...which basically sets whichButton to a new empty ArrayList.
Move that line elsewhere in your code so it only initializes the ArrayList at the start of each game and not at every turn.
The way you are going about this is overcomplicated. Instead of using else-if blocks to pick the button from a random number, put the buttons in a list or array and get a random buttons like this:
private final Button[] buttons = new Button[] {
findViewById(R.id.buttonRed),
findViewById(R.id.buttonYellow),
/* etc, etc */
};
public Button getRandomButton() {
return buttons[new Random().nextInt(buttons.length)];
}
The reason the sequence isn't playing back correctly is because you aren't storing the sequence as an instance variable. The easiest way to store the sequence would be to store a list of integers. The integers would represent the position of the buttons in your array and you would add a new entry every turn.
private final List<Integer> currentSequence = new ArrayList<>();
public void nextTurn() {
// first play the previous buttons
for (int i : currentSequence) {
Button b = buttons[i];
// then play it here
}
// play a new button and add it to the sequence
Button randomButton = getRandomButton();
// play it here
currentSequence.add(Arrays.asList(buttons).indexOf(randomButton)));
}
Then when you're done with the current game just remember to clear the sequence with.
currentSequence.clear();
I made a simple quiz game for android, right now there's only 10 questions, and 40 answers. (4 answers for each question) Sometimes when I hit a button it gives me more than one correct answer at a time! Any idea what's wrong with this code:
public class ETBetaActivity extends Activity implements View.OnClickListener {
Button answer_1,
answer_2,answer_3,
answer_4,main;
TextView q_textview,
tip;
private String a1,a2,a3,a4 = "";
private int i1 = 0;
public static int correct = 0;
private boolean alive = true;
MediaPlayer button_click;
private String[] questions =
{"Q1",
"Q2",
"Q3",
"Q4",
"Q5", //5
"Q6",
"Q7",
"Q8",
"Q9",
"Q10" //10
};
public static int question_amount = 10;
private String[] answers_correct =
{"Correct answer - 1",
"Correct answer - 2",
"Correct answer - 3",
"Correct answer - 4",
"Correct answer - 5",
"Correct answer - 6",
"Correct answer - 7",
"Correct answer - 8",
"Correct answer - 9",
"Correct answer - 10"
};
private String[][] answers_wrong =
{ {"Q1-1", "Q1-2" , "Q1-3"},
{"Q2-1", "Q2-2" , "Q2-3"},
{"Q3-1", "Q3-2" , "Q3-3"},
{"Q4-1", "Q4-2" , "Q4-3"},
{"Q5-1", "Q5-2" , "Q5-3"},
{"Q6-1", "Q6-2" , "Q6-3"},
{"Q7-1", "Q7-2" , "Q7-3"},
{"Q8-1", "Q8-2" , "Q8-3"},
{"Q9-1", "Q9-2" , "Q9-3"},
{"Q10-1", "Q10-2" , "Q10-3"}
};
List<String> question_list = new ArrayList<String>();
List<String> answer_list_correct = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getData();
Game(i1);
}
#Override
public void onClick(View view) {
if (alive == false) {
// startActivity(new Intent("com.aleksei.etb.END"));
return;
}
button_click = MediaPlayer.create(this, R.raw.button_click);
button_click.start();
switch(view.getId()){
case R.id.button5: //main
break;
case R.id.button1: //answer_1
if(isCorrect(1))
correct++;
break;
case R.id.button2: //answer_2
if(isCorrect(2))
correct++;
break;
case R.id.button3: //answer_3
if(isCorrect(3))
correct++;
break;
case R.id.button4: //answer_3
if(isCorrect(4))
correct++;
break;
default:
break;
}
Game(i1);
tip.setText("Correct answers: "+correct);
}
public static int getResults(){
int value = (int) Math.floor((correct*5)/question_amount);
if(value <= 0)
return 1;
else
return value;
}
private boolean isCorrect(int button){
for (int i = 0; i < answers_correct.length; i++){
if(button == 1 && a1 == answers_correct[i]
|| button == 2 && a2 == answers_correct[i]
|| button == 3 && a3 == answers_correct[i]
|| button == 4 && a4 == answers_correct[i])
return true;
}
return false;
}
private void Game(int q){
if(i1 == question_amount) { //no more questions
startActivity(new Intent("com.aleksei.etb.END"));
alive = false;
return;
}
try {
main.setText("Dunno");
String answer_list[] = {
answers_correct[q], answers_wrong[q][0] , answers_wrong[q][1] , answers_wrong[q][2]
};
Collections.shuffle(Arrays.asList(answer_list));
answer_1.setText(answer_list[0]);
answer_2.setText(answer_list[1]);
answer_3.setText(answer_list[2]);
answer_4.setText(answer_list[3]);
a1 = answer_list[0];
a2 = answer_list[1];
a3 = answer_list[2];
a4 = answer_list[3];
q_textview.setText(questions[q]);
} catch (Exception ex){}
i1++;
}
private void getData(){
//Getting the data
main = (Button) findViewById(R.id.button5);
answer_1 = (Button) findViewById(R.id.button1);
answer_2 = (Button) findViewById(R.id.button2);
answer_3 = (Button) findViewById(R.id.button3);
answer_4 = (Button) findViewById(R.id.button4);
q_textview = (TextView) findViewById(R.id.question);
tip = (TextView) findViewById(R.id.answ1);
//Making the buttons, actually work
main.setOnClickListener(this);
answer_1.setOnClickListener(this);
answer_2.setOnClickListener(this);
answer_3.setOnClickListener(this);
answer_4.setOnClickListener(this);
//Resets the text
//Note to self: Replace with another ContectView
main.setText("Begin!");
answer_4.setText("");
answer_3.setText("");
answer_2.setText("");
answer_1.setText("");
tip.setText("");
}
}
I even tried something like
private boolean getAnswer = false;
private String correctAnswer;
private boolean isCorrect(int button){
if(getAnswer == true) {
if(button == 1 && a1 == correctAnswer
|| button == 2 && a2 == correctAnswer
|| button == 3 && a3 == correctAnswer
|| button == 4 && a4 == correctAnswer)
return true;
}
return false;
}
Inside Game(int) :
getAnswer = false;
correctAnswer = answers_correct[q];
Didnt help.
I hope I made my self clear, if not, ask.
Thanks.
Edit:
Tried using these in the onCreate method
answer_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isCorrect(1))
correct++;
Game(i1);
tip.setText("Correct answers "+correct);
}
});
answer_2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isCorrect(2))
correct++;
Game(i1);
tip.setText("Correct answers "+correct);
}
});
answer_3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isCorrect(3))
correct++;
Game(i1);
tip.setText("Correct answers "+correct);
}
});
answer_4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isCorrect(4))
correct++;
Game(i1);
tip.setText("Correct answers "+correct);
}
});
Didn't help.
Im a little confused as to why you are having your entire activity be an on click listener instead of setting up your project similar to this
http://developer.android.com/reference/android/widget/Button.html
My guess would be that both the activity view itself AND the button views are executing the onClickListener callback.