Android- Error Message - java

I have been recently having an error when compiling my android code onto an emulator. The game is that when you click a button, it gives you a math question displayed on a textView, and user types their answer (in numbers) and clicks the button 'check' When I click that button, it always returns false.
Anyone knows how to fix this?
Java Class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
mathQuestion = findViewById(R.id.magic_textview);
redCircle = findViewById(R.id.math_ball);
yellowbox = findViewById(R.id.yellow_box);
yellowboxY = 1550f - 130f;
yellowbox.setY(yellowboxY);
yellowboxX = 472f;
yellowbox.setX(yellowboxX);
type_answer = findViewById(R.id.type_answer);
Button checkButton = findViewById(R.id.check_button);
checkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(redCircleX == yellowboxX && redCircleY == yellowboxY){
mathQuestion.setText("What is "+math_int1+" + "+math_int2+" ?");
math_int1 = r.nextInt(20);
math_int2 = r.nextInt(20)+1;
string_math_int1 = String.valueOf(math_int1);
string_math_int2 = String.valueOf(math_int2);
Button checkAnswer = findViewById(R.id.check_answer);
checkAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Error? Always returning false?
if (type_answer.getText().toString().contains (Integer.toString( math_int1 + math_int2))) {
Toast t = Toast.makeText(GameActivity.this, "Success!", Toast.LENGTH_SHORT);
t.show();
} else {
Toast t2= Toast.makeText(GameActivity.this, type_answer.getText().toString(), Toast.LENGTH_SHORT);
t2.show();
}
}
});
}else{
Toast.makeText(GameActivity.this, "Incorrect Or Error", Toast.LENGTH_SHORT).show();
}
}
});
Button upButton = findViewById(R.id.up_button);
upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveUp();
}
});
Button downButton = findViewById(R.id.down_button);
downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveDown();
}
});
Button leftButton = findViewById(R.id.left_button);
leftButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveLeft();
}
});
Button rightButton = findViewById(R.id.right_button);
rightButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveRight();
}
});
Button resetCircleXY = findViewById(R.id.reset_button);
resetCircleXY.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initCircleXY();
Toast.makeText(GameActivity.this, "Reset Ball's Position", Toast.LENGTH_SHORT).show();
}
});
upButton.performClick();
leftButton.performClick();
redCircleY = 1550f;
redCircle.setY(redCircleY);
redCircleX = 472f;
redCircle.setX(redCircleX);
}
private void moveUp(){
redCircleY -= ballMoveDis;
redCircle.setY(redCircleY);
}
private void moveDown(){
redCircleY += ballMoveDis;
redCircle.setY(redCircleY);
}
private void moveLeft(){
redCircleX += ballMoveDis;
redCircle.setX(redCircleX);
}
private void moveRight(){
redCircleX -= ballMoveDis;
redCircle.setX(redCircleX);
}
private void initCircleXY(){
redCircleY = 1550f;
redCircle.setY(redCircleY);
redCircleX = 472f;
redCircle.setX(redCircleX);
}
}
Help is greatly appreciated, Thanks

First mistake
string_math_int1 = String.valueOf(math_int1);
string_math_int2 = String.valueOf(math_int1); // this should be math_int2
BUT consider adding two strings
string_math_int1 + string_math_int2)
"10" + "20"
equals
"1020" not "30"
Maybe
if (type_answer.getText().toString().equals(String.valueOf (math_int1 + math_int2) {

Answer to newly formatted question:
Your issue has to do with comparing two strings when you want to check their int values. You could try using Integer.parseInt() on your EditText's entry. Just be aware you will need to do a try on it to catch an exception in the case of your EditText having any non numeric characters.
Answer to previous question about crash before edit:
Your crash isn't with your EditText. It is this line:
Toast.makeText(GameActivity.this,math_int1 + math_int2 , Toast.LENGTH_SHORT).show();
By passing it an int value, it is attempting to look up a string with that id. If your intent is to display the sum of those ints, it should look something like:
Toast.makeText(GameActivity.this, String.valueOf(math_int1 + math_int2), Toast.LENGTH_SHORT).show();

Related

I want to count my every right and wrong answer submitted in my quiz app and want to display score in textview

This is the method I have created to check the condition
For the right answer, I am showing the png image and the same for the wrong answer
#SuppressLint("SetTextI18n")
private void checkAnswer(boolean userPressed) {
boolean answerProvided = mQuestionBank[mCurrentIndex].isQuestionTrueAnswer();
int messageStringId = 0;
if (answerProvided == userPressed) {
messageStringId = R.string.correct_toast;
mGreenTick.setImageResource(R.drawable.green_tick);
mGreenTick.setVisibility(View.VISIBLE);
}
else {
messageStringId = R.string.incorrect_toast;
mGreenTick.setImageResource(R.drawable.red_cross);
mGreenTick.setVisibility(View.VISIBLE);
}
// Toast.makeText(MainActivity.this, messageStringId, Toast.LENGTH_SHORT).show();
}
I have called the method checkAnswer() method in the true button click and false button click below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Does nothing yet, but soon!
checkAnswer(true);
mTrueButton.setEnabled(false);
mFalseButton.setEnabled(false);
mMoreInfoButton.setVisibility(View.VISIBLE);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Does nothing yet, but soon!
checkAnswer(false);
mFalseButton.setEnabled(false);
mTrueButton.setEnabled(false);
mMoreInfoButton.setVisibility(View.VISIBLE);
}
});
Now, i have used intent method in Score Button click and in the ScoreActivity.class i want to show the
store in textview.
please tell me how to count the true answer and wrong answer and store the score in the variable which i
can show in textview
Please help me.
mScoreButton = (Button)findViewById(R.id.score_button);
mScoreButton.setVisibility(View.INVISIBLE);
mScoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScoreActivity.class);
startActivity(intent);
finish();
}
});
private int trueCount = 0;
private int falseCount = 0;
#SuppressLint("SetTextI18n")
private void checkAnswer(boolean userPressed) {
boolean answerProvided = mQuestionBank[mCurrentIndex].isQuestionTrueAnswer();
int messageStringId = 0;
if (answerProvided == userPressed) {
trueCount++;
messageStringId = R.string.correct_toast;
mGreenTick.setImageResource(R.drawable.green_tick);
mGreenTick.setVisibility(View.VISIBLE);
}
else {
falseCount++;
messageStringId = R.string.incorrect_toast;
mGreenTick.setImageResource(R.drawable.red_cross);
mGreenTick.setVisibility(View.VISIBLE);
}
// Toast.makeText(MainActivity.this, messageStringId, Toast.LENGTH_SHORT).show();
}
...
//Displaying int textView
textView.setText(String.format("Right count: %d False count: %d", rightCount, falseCount));
mFinalMarks = (TextView)findViewById(R.id.final_marks);
mFinalMarks.setText("Final Score is: " + getIntent().getStringExtra("PLUS_MARKS") + "Marks out of 10 ");
getIntent().getStringExtra("PLUS_MARKS");
// it is showing null instead of score

My algorithm never met the requirements to start an Activity?

I created an Android game, but it isn't working how it should.
Main idea
User clicks CheckedTextView three times and after the third click, a second Activity is started.
Problem
Second Activity isn't starting.
]
Code with an algorithm:
public class StartOfTheGame extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startofthegame);
Window w = getWindow();
w.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
final CheckedTextView checkedTextView = findViewById(R.id.checked_textview);
checkedTextView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String[] seasons = {"1", "2", "3", "4"};
int n = (int)Math.floor(Math.random() * seasons.length);
checkedTextView.toggle();
int a = 0;
if(checkedTextView.isChecked()) {
checkedTextView.setChecked(false);
checkedTextView.setText(seasons[n]);
a++;
}
if (a == 3){
try {
Intent intent = new Intent(StartOfTheGame.this, SecondStageOfTheGame.class);
startActivity(intent);
finish();
} catch (Exception e) {
}
}
}
});
a is a local variable. So, everytime you click, a is first set to 0 at int a = 0;
Try the code below:
checkedTextView.setOnClickListener(new View.OnClickListener(){
private int a = 0; // Add this here
#Override
public void onClick(View v) {
...
// int a = 0; // Remove this
...
if (a == 3){
try {
Intent intent = new Intent(StartOfTheGame.this, SecondStageOfTheGame.class);
startActivity(intent);
finish();
} catch (Exception e) {
}
}
}
}

Android mediaplayer next song onButton Click

Button btnPlayPause, btnNext, btnPrevious;
Bundle b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song);
btnPlayPause = (Button) findViewById(R.id.btnPlayPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPrevious = (Button) findViewById(R.id.btnPrevious);
Intent currSong = getIntent();
b = currSong.getExtras();
btnPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
btnPlayPause.setText("Play");
} else {
mediaPlayer.start();
btnPlayPause.setText("Stop");
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnPlayPause.setText("Play");
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
int songIndex = (int) b.get("songIndex");
#Override
public void onClick(View v) {
if (songIndex < songList.size() - 1) {
songIndex = songIndex + 1;
Toast.makeText(getApplicationContext(), "You Clicked " + songIndex , Toast.LENGTH_SHORT).show();
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setDataSource(songList.get(songIndex).getData());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else{
songIndex=0;
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (songIndex > 0){
songIndex = songIndex-1;
Toast.makeText(getApplicationContext(), "You Clicked " + songIndex , Toast.LENGTH_SHORT).show();
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setDataSource(songList.get(songIndex).getData());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else {
songIndex = songList.size() - 1;
}
}
});
}
}
So when i click on the next button, it plays the second song, but at the end of my songlist it skips the first song from the list stored in [0] and on second click it goes to [1] so there is always one song not playing.
How can i solve this or is there an easier way too go to the next song?
Thanks,
-Vince
EDIT;
Problem 2; when i choose a song, lets say with position 37, and i click on previous it goes to 36, but if i then click on next it goes to 38, so it skips the song i played first.
EDIT 2 ;
Ok problems still persists, but i found out that when i click a few times on previous btn let's say i start from position 25 and go to 15 with the previous btn, and when i then click on next again it just starts to count from 25. How can i solve this? Thanks in advance, - vince
Ok, you have several problems here:
i found out that when i click a few times on previous btn let's say i start from position 25 and go to 15 with the previous btn, and when i then click on next again it just starts to count from 25
In PlayNext's first line, you reassign songIndex to the original songIndex passed to the activity. PlayPrevious uses another songIndex that I can't see where is defined. If you had followed Android guidelines to always prefix with an "m" the class properties vs local variables, you'd easily have realised it.
So when i click on the next button, it plays the second song, but at the end of my songlist it skips the first song from the list stored in [0] and on second click it goes to [1]
The edge cases where user plays the next after the last song, or the previous after the first are incorrectly coded. In those cases you correctly update songIndex, but do not call play.
Besides the problems, what you should do is to rework your code a little using functions, to avoid repeating functionality. That is always prone to these kind of errors. I'd suggest something like this:
int mCurrentIndex; // always prefix class properties with an "m"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song);
Button btnPlayPause = (Button) findViewById(R.id.btnPlayPause),
btnNext = (Button) findViewById(R.id.btnNext),
btnPrevious = (Button) findViewById(R.id.btnPrevious);
Intent currSong = getIntent();
Bundle b = currSong.getExtras();
// load initial index only once
mCurrentIndex = (int) b.get("songIndex");
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = mCurrentIndex > 0 ? mCurrentIndex - 1 : mSongList.size() - 1;
playSongNumber(mCurrentIndex);
}
}
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex++;
mCurrentIndex %= mSongList.size();
playSongNumber(mCurrentIndex);
}
}
}
private void playSongNumber(int index) {
try {
mMediaPlayer.stop();
mMediaPlayer.reset();
mMediaPlayer.setDataSource(mSongList.get(index).getData());
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
slightly cleaner, isn't it?

How to tie If Statements together into one bigger If Statement in Java

I have a basic program. I wish to set the background of individual buttons, based on user click count, then IF all buttons have the same background, the user will proceed to the next activity. Simple enough, or so I thought... I just can't seem to figure out how to compare the IF statements to each-other. I've spent like an hour writing and rewriting code, trying to find an answer. There has to be an easy answer I'm missing and just can't wrap my mind around.
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
Button a1;
Button a2;
Button a3;
Button a4;
static int count1=0;
static int count2=0;
static int count3=0;
static int count4=0;
public void addListenerOnButton() {
final Button a1 = (Button) findViewById(R.id.a1);
a1.setOnClickListener(new OnClickListener()
#Override
public void onClick(View v) {
count1=count1+1;
if(count1==1||count1==4||count1==8)
{ a1.setBackgroundColor(Color.RED);
Toast.makeText(getApplicationContext(),"Button clicked !", Toast.LENGTH_LONG).show();}
else if(count1==2||count1==6)
{a1.setBackgroundColor(Color.BLUE);
Toast.makeText(getApplicationContext(),"Button clicked" +count1, Toast.LENGTH_LONG).show();}
else{a1.setBackgroundColor(Color.YELLOW);
Toast.makeText(getApplicationContext(),"Button clicked" +count1, Toast.LENGTH_LONG).show();
}}});
final Button a2 = (Button) findViewById(R.id.a2);
a2.setOnClickListener(new OnClickListener() {
int clickcount=0;
#Override
public void onClick(View v) {
clickcount=clickcount+1;
if(clickcount==2||clickcount==4||clickcount==7)
{ a2.setBackgroundColor(Color.RED);
Toast.makeText(getApplicationContext(),"Button clicked first time!", Toast.LENGTH_LONG).show();}
else if(clickcount==1||clickcount==3)
{a2.setBackgroundColor(Color.BLUE);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();}
else{a2.setBackgroundColor(Color.YELLOW);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();
}}});
final Button a3 = (Button) findViewById(R.id.a3);
a3.setOnClickListener(new OnClickListener() {
int clickcount=0;
#Override
public void onClick(View v) {
clickcount=clickcount+1;
if(clickcount==1||clickcount==2||clickcount==6)
{ a3.setBackgroundColor(Color.RED);
Toast.makeText(getApplicationContext(),"Button clicked first time!", Toast.LENGTH_LONG).show();}
else if(clickcount==4||clickcount==5||clickcount==7)
{a3.setBackgroundColor(Color.BLUE);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();}
else{a3.setBackgroundColor(Color.YELLOW);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();
}}});
final Button a4 = (Button) findViewById(R.id.a4);
a4.setOnClickListener(new OnClickListener() {
int clickcount=0;
#Override
public void onClick(View v) {
clickcount=clickcount+1;
if(clickcount==3||clickcount==5||clickcount==7||clickcount==8)
{ a4.setBackgroundColor(Color.RED);
Toast.makeText(getApplicationContext(),"Button clicked first time!", Toast.LENGTH_LONG).show();}
else if(clickcount==2||clickcount==9)
{a4.setBackgroundColor(Color.BLUE);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();}
else{a4.setBackgroundColor(Color.YELLOW);
Toast.makeText(getApplicationContext(),"Button clicked" +clickcount, Toast.LENGTH_LONG).show();
}}});
}
}
public void checkFunc(){
if(count1==1)
{
Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com/"));
startActivity(browserIntent);
}
}
}
One way I have considered achieving my goal is something along the lines of
if((a1.setBackgroundColor(Color.BLUE)==true)|| (a2.setBackgroundColor(Color.BLUE)==true))
Edit** So after trying a few things I edited my code a bit and still cant get it to work. Any further suggestions?
You can do the comparison using static variables instead. Also declare the variables globally. It's not a great approach, but here goes:
//global static vars
static int count1=0;
static int count2=0;
static int count3=0;
static int count4=0;
//make sure you include your conditions. I've added this just for reference
public void addListenerOnButton() {
a1.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v)
{
count1++;
}
}
a2.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v)
{
count2++;
}
}
//And so on...
}
public void checkFunc()
{
if(count1==count2==count3==count4)
{
//do something
}
}
I suggest that, declare clickCount variables inside class, not inside click handler. So you can reach each button's click count every clickHandler method. So, write a method that compares clickCount's, and call this method inside every clickHandler.
private int clickCount1, clickCount2, clickCount3, clickCount4;
private void compareClickCounts(){
// Compare clickCounts and change buttons properties
}

Get function value in Android

Question: I am trying to take the index of the selected radio button and use that in the onClick function.
Example:
btnCalc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (getIndex(k) == 0) {
DO THIS
}
if (getIndex(k) == 1) {
DO THAT
}
});
I have the following code in my Android app:
int POS; //global variable assigned right under MainActivity
final RadioGroup rgTypeOfTrip = (RadioGroup) findViewById(R.id.rgTripType);
Button btnCalc = (Button) findViewById(R.id.btnCalculate);
btnCalc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(MainActivity.this, Integer.toString(getIndex(POS1)), Toast.LENGTH_SHORT).show(); //DOESN'T WORK
});
rgTypeOfTrip.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
// Method 1
int pos=rgTypeOfTrip.indexOfChild(findViewById(checkedId));
getIndex(pos);
Toast.makeText(MainActivity.this, String.valueOf(pos), Toast.LENGTH_SHORT).show();
}
});
public int getIndex(int POS1) {
Toast.makeText(MainActivity.this, Integer.toString(POS1), Toast.LENGTH_SHORT).show(); // WORKS
return POS1;
}
How can I achieve this line:
Toast.makeText(MainActivity.this, CALL FUNCTION GETINDEX() to get value, Toast.LENGTH_SHORT).show();
To call the function to get the value of k?
Assuming your question is in the Toast such that it is: "CALL FUNCTION GETINDEX() to get value"
Toast.makeText(MainActivity.this, Integer.toString(getIndex(int)), Toast.LENGTH_SHORT).show();
You pass in the integer that is returned though so you could just go with the following (under my assumptions of your code):
Toast.makeText(MainActivity.this, Integer.toString(int), Toast.LENGTH_S

Categories