Send a value from Mainactivity and display the value in another activity - java

I am trying to make a simple quiz app and I want to display the score value in another activity(another screen) i.e. when I press the submit button the score activity should open and display the total score.
I have tried using intents but it hasn't worked. I am new at android programming and there could be some silly mistakes.
This is the MainActivity.java file.
package com.example.android.conanquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Question 1 Methods
public void question1_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.haibara:
if (checked) {
String correct = "Right Answer";
display_answer1(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q1_o1);
display_answer1(wrong);
}
break;
}
}
private void display_answer1(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_1);
quantityTextView.setText(answer);
}
//Question 2 Methods
public void question2_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.true_op:
if (checked) {
String correct = "Right Answer";
display_answer2(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q2_o1);
display_answer2(wrong);
}
break;
}
}
private void display_answer2(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_2);
quantityTextView.setText(answer);
}
//Question 3 Methods
public void question3_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q3_op3:
if (checked) {
String correct = "Right Answer";
display_answer3(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q3_o3);
display_answer3(wrong);
}
break;
}
}
private void display_answer3(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_3);
quantityTextView.setText(answer);
}
//Question 4 Methods
public void question4_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q4_op1:
if (checked) {
String correct = "Right Answer";
display_answer4(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q4_o1);
display_answer4(wrong);
}
break;
}
}
private void display_answer4(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_4);
quantityTextView.setText(answer);
}
//Question 5 Methods
public void question5_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q5_op3:
if (checked) {
String correct = "Right Answer";
display_answer5(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q5_o3);
display_answer5(wrong);
}
break;
}
}
private void display_answer5(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_5);
quantityTextView.setText(answer);
}
//Submit Button
public void onClickSubmit(View view){
Intent scoreActivity = new Intent(MainActivity.this,Score.class);
scoreActivity.putExtra("sendScore", score);
startActivity(scoreActivity);
}
}
This is the other activity java(Score.java) file
package com.example.android.conanquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class Score extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
Intent scoreActivity = getIntent();
int totalScore = scoreActivity.getIntExtra("sendScore", 0);
displayScore(totalScore);
}
public void displayScore(int score) {
TextView scoreTextView = (TextView) findViewById(R.id.score);
scoreTextView.setText(score);
}
}

Try to print score on button click using log. if score is not null than write below code.
From Activity
Intent intent = new Intent(getBaseContext(), Score.class);
intent.putExtra("EXTRA_SCORE", score);
startActivity(intent);
To Activity
Intent intent = getIntent();
int intValue = intent.getIntExtra("EXTRA_SCORE", 0);

Related

I don't understand this error message, any help would be helpful

I tried to build my app, and this error message was produced.
Unexpected character '=' (code 61) (expected a name start character)
at [row,col {unknown-source}]: [41,21]
I have cleaned my code and tried to clean my code and inspected my code and i can't find anything wrong my code, and help would be gratefully recieved.
This is my MainActivity.
package com.michaeldoughty.android.football_quiz;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import
androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.*;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity
{
// to answer true for the question
private Button mTrueButton;
// to answer false for the question
private Button mFalseButton;
// to get the next question
private ImageButton mNextButton;
// to cheat
private Button mCheatButton;
// to hold the questions
private TextView mQuestionTextView;
// whether the user is a cheater
private boolean mIsCheater;
// a key used for the onSaveInstanceState
private final String KEY_INDEX = "index";
// An ActivityResultLauncher for the CheatActivity
ActivityResultLauncher<Intent> cheatActivityResultLauncher =
registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>()
{
#Override
public void onActivityResult (ActivityResult
result)
{
//checking if there is a result code from the
returned intent
if (result.getResultCode () == RESULT_OK)
{
// to check is there is any data in the
returned intent
if (result.getData() == null)
{
return;
}
// setting that the user is a cheater
mIsCheater = true;
}
}
});
// an array of Question objects
private Question [] mQuestionBank = new Question []
{
new Question (R.string.question_euro, true),
new Question (R.string.question_world_cup, false),
new Question (R.string.question_premier_league,
false),
new Question (R.string.question_england, true),
new Question (R.string.question_fa_cup, false),
new Question (R.string.question_league_cup, true)
};
// the index of the current question being displayed
private int mCurrentIndex = 0;
// to hold the percentage of correct answers
private double percentage = 0;
// to hold the amount of correct answers
private double correct = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// to check if there is a value of mCurrentIndex in the
savedInstanceState
if (savedInstanceState != null)
{
mCurrentIndex = savedInstanceState.getInt (KEY_INDEX,
0);
}
// to create the mQuestionTextView
mQuestionTextView = (TextView) findViewById
(R.id.question_text_view);
mQuestionTextView.setOnClickListener(new
View.OnClickListener()
{
#Override
public void onClick(View view)
{
// update the mCurrrentIndex
mCurrentIndex++;
// enable the mTrueButton and mFalseButton
mTrueButton.setEnabled (true);
mFalseButton.setEnabled (true);
if (mCurrentIndex < 6)
{
// call the updateQuestion method
updateQuestion();
}
else
{
displayPercentage ();
mCurrentIndex = 0;
updateQuestion();
}
}
});
// call the updateQuestion method
updateQuestion ();
// to create the mTrueButton
mTrueButton = (Button) findViewById (R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// call the checkAnswer method
checkAnswer (true);
// disable the mTrueButton and mFalseButton
mTrueButton.setEnabled (false);
mFalseButton.setEnabled (false);
}
});
// to create the mFalseButton
mFalseButton = (Button) findViewById (R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// call the checkAnswer method
checkAnswer (false);
// disable the mTrueButton and mFalseButton
mTrueButton.setEnabled (false);
mFalseButton.setEnabled (false);
}
});
// to create the mNextButton
mNextButton = (ImageButton) findViewById
(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// update the mCurrrentIndex
mCurrentIndex++;
// enable the mTrueButton and mFalseButton
mTrueButton.setEnabled (true);
mFalseButton.setEnabled (true);
if (mCurrentIndex < 6)
{
// call the updateQuestion method
updateQuestion();
}
else
{
displayPercentage ();
mCurrentIndex = 0;
updateQuestion();
}
}
});
// to create the mCheatButton
mCheatButton = (Button) findViewById (R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean answerIsTrue = mQuestionBank
[mCurrentIndex].isAnswerTrue ();
Intent intent = CheatActivity.newIntent
(MainActivity.this, answerIsTrue);
cheatActivityResultLauncher.launch (intent);
}
});
}
/**
The onSaveInstanceState method saves savedInstanceState when
the activity is stopped.
#param savedInstanceState, the bundle of the activity.
*/
#Override
public void onSaveInstanceState (Bundle savedInstanceState)
{
// call the super's constructor
super.onSaveInstanceState (savedInstanceState);
// to add the mCurrentIndex to the bundle
savedInstanceState.putInt (KEY_INDEX, mCurrentIndex);
}
/**
The updateQuestion method updates the question.
*/
public void updateQuestion ()
{
// get the next question
int question = mQuestionBank [mCurrentIndex].getTextResId
();
// to display the next question
mQuestionTextView.setText (question);
}
/**
The checkAnswer method checks the user's answer, to see if
its correct or not
#param userPressedTrue, the user's answer.
*/
public void checkAnswer (boolean userPressedTrue)
{
// getting the correct answer
boolean answerIsTrue = mQuestionBank
[mCurrentIndex].isAnswerTrue ();
// the message in the toast
int messageResId = 0;
// checking the user's answer and setting the right meassge
if (userPressedTrue == answerIsTrue)
{
messageResId = R.string.correct_toast;
correct++;
}
else
{
messageResId = R.string.incorrect_toast;
}
// displaying the meessage in a toast
Toast toast;
toast = Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT);
toast.setGravity (Gravity.TOP|Gravity.CENTER, 0, 0);
toast.show ();
}
/**
The displayPercentage displays the percentage of correct
answers the user had guessed.
*/
public void displayPercentage ()
{
// working out the percentage
percentage = (correct / mQuestionBank.length) * 100;
DecimalFormat df = new DecimalFormat("#.00");
// displaying the percentage as a toast
Toast.makeText(this, "You have guessed " +
df.format(percentage) + "%!", Toast.LENGTH_SHORT).show ();
// to set the correct and percentage back to zero
correct = 0;
percentage = 0;
}
}
Here is my CheatActivity
// an extra key for the intent which tells the CheatActivity
what the answer is
private static final String EXTRA_ANSWER_IS_TRUE =
"com.michaeldoughty.android.football_quiz_answer_is_true";
// an extra key for the intent which tells the MainActivity if
the user has cheated
private static final String EXTRA_ANSWER_IS_SHOWN =
"com.michaeldoughty.android.football_quiz_answer_shown";
// if the answer is true or not
private boolean mAnswerIsTrue;
// to hold the correct answer
private TextView mAnswerTextView;
// a button to show the correct answer
private Button mShowAnswerButton;
// to create an intent to create a CheatActivity
public static Intent newIntent (Context packageContext,
boolean answerIsTrue)
{
Intent intent = new Intent (packageContext,
CheatActivity.class);
intent.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
return intent;
}
public static boolean wasAnswerShown (Intent result)
{
return result.getBooleanExtra (EXTRA_ANSWER_IS_SHOWN,
false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
// to get the mAnswerIsTrue
mAnswerIsTrue = getIntent ().getBooleanExtra
(EXTRA_ANSWER_IS_TRUE, false);
// to create the mAnswerTextView
mAnswerTextView = findViewById (R.id.answer_text_view);
// to create the mShowAnswerButton
mShowAnswerButton = findViewById (R.id.show_answer_button);
mShowAnswerButton.setOnClickListener(new
View.OnClickListener()
{
#Override
public void onClick(View view)
{
if (mAnswerIsTrue)
{
mAnswerTextView.setText (R.string.true_button);
}
else
{
mAnswerTextView.setText
(R.string.false_button);
}
setAnswerShownResult (true);
}
});
}
/**
The setAnswerShownResult creates an Intent, to send the
isAnswerShown to the MainActivity.
#param isAnswerShown, whether the user has cheated or not.
*/
private void setAnswerShownResult (boolean isAnswerShown)
{
Intent data = new Intent ();
data.putExtra (EXTRA_ANSWER_IS_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
}
Here is my Question class
package com.michaeldoughty.android.football_quiz;
public class Question
{
// to hold the text res id of the question
private int mTextResId;
// to hold if the answer is true or false
private boolean mAnswerTrue;
/**
Constructor
*/
public Question (int textResId, boolean answerTrue)
{
mTextResId = textResId;
mAnswerTrue = answerTrue;
}
public int getTextResId()
{
return mTextResId;
}
public void setTextResId(int textResId)
{
mTextResId = textResId;
}
public boolean isAnswerTrue()
{
return mAnswerTrue;
}
public void setAnswerTrue(boolean answerTrue)
{
mAnswerTrue = answerTrue;
}
}

Android Java calling method

So, I tried to call all the methods from overView but is not working, I tried with "view" in the parentheses and then is constantly crashing when I start the app.... Can someone help, this is the whole code. I tried not to include the first four methods but then is not working the way it's suppose to.
public class MainActivity extends AppCompatActivity {
int health = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void checkQuestionOne(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_one_yes:
if(checked)
health += 1;
break;
case R.id.question_one_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionTwo(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_two_yes:
if(checked)
health += 1;
break;
case R.id.question_two_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionThree(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_three_yes:
if(checked)
health += 1;
break;
case R.id.question_three_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionFour(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question_four_yes:
if(checked)
health += 1;
break;
case R.id.question_four_no:
if(checked)
health -= 1;
break;
}
}
public void checkQuestionFive() {
EditText gettingQuestionFive = findViewById(R.id.sleep_hours);
int answerQuestionFive = Integer.parseInt(gettingQuestionFive.getText().toString());
if (answerQuestionFive > 7) {
health += 1;
} else if (answerQuestionFive == 7) {
health += 1;
} else {
health -=1;
}
}
private void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.summary);
orderSummaryTextView.setText(message);
}
public void overView(View view){
checkQuestionOne();
checkQuestionTwo();
checkQuestionThree();
checkQuestionFour();
checkQuestionFive();
String Message = health + " is your score. If is 3 or above, you have a healthy life";
displayMessage(Message);
}
}
I think you have forgot to call the overView() method in the onCreate() method of activity. You can call it like this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Pass your view in argument
overView(View view)
}

Multiple categories quiz app

I'm making a quiz app with question about different countries. I already made it work for one country, but now I'd like to make it work for all the countries, but I don't exactly know how. I've made a question library and a quizactivity, but I don't know how to proceed right now, so I hope someone can help me.
Here is my quizactivity:
package com.example.quizapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends AppCompatActivity {
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
private TextView mScoreView;
private TextView mQuestionView;
private Button mButtonChoice1;
private Button mButtonChoice2;
private Button mButtonChoice3;
private Button mButtonChoice4;
private String mAnswerFrankrijk;
private int mScoreFrankrijk = 0;
private int mQuestionNumber = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mScoreView = (TextView)findViewById(R.id.score1);
mQuestionView = (TextView)findViewById(R.id.question1);
mButtonChoice1 = (Button)findViewById(R.id.choice1);
mButtonChoice2 = (Button)findViewById(R.id.choice2);
mButtonChoice3 = (Button)findViewById(R.id.choice3);
mButtonChoice4 = (Button)findViewById(R.id.choice4);
updateQuestion();
//Start of Button Listener for Button1
mButtonChoice1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice1.getText() == mAnswerFrankrijk){
mScoreFrankrijk = mScoreFrankrijk + 1;
updateScore(mScoreFrankrijk);
updateQuestion();
//This line of code is optiona
Toast.makeText(QuizActivity.this, "Goed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(QuizActivity.this, "Fout", Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button1
//Start of Button Listener for Button2
mButtonChoice2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice2.getText() == mAnswerFrankrijk){
mScoreFrankrijk = mScoreFrankrijk + 1;
updateScore(mScoreFrankrijk);
updateQuestion();
//This line of code is optiona
Toast.makeText(QuizActivity.this, "Goed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(QuizActivity.this, "Fout", Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button2
//Start of Button Listener for Button3
mButtonChoice3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice3.getText() == mAnswerFrankrijk){
mScoreFrankrijk = mScoreFrankrijk + 1;
updateScore(mScoreFrankrijk);
updateQuestion();
//This line of code is optiona
Toast.makeText(QuizActivity.this, "Goed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(QuizActivity.this, "Fout", Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button3
//Start of Button Listener for Button3
mButtonChoice4.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice4.getText() == mAnswerFrankrijk){
mScoreFrankrijk = mScoreFrankrijk + 1;
updateScore(mScoreFrankrijk);
updateQuestion();
//This line of code is optional
Toast.makeText(QuizActivity.this, "Goed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(QuizActivity.this, "Fout", Toast.LENGTH_SHORT).show();
updateQuestion();
}
}
});
//End of Button Listener for Button3
}
private void updateQuestion(){
mQuestionView.setText(mQuestionLibrary.getQuestionFrankrijk(mQuestionNumber));
mButtonChoice1.setText(mQuestionLibrary.getChoice1Frankrijk(mQuestionNumber));
mButtonChoice2.setText(mQuestionLibrary.getChoice2Frankrijk(mQuestionNumber));
mButtonChoice3.setText(mQuestionLibrary.getChoice3Frankrijk(mQuestionNumber));
mButtonChoice4.setText(mQuestionLibrary.getChoice4Frankrijk(mQuestionNumber));
mAnswerFrankrijk = mQuestionLibrary.getCorrectAnswerFrankrijk(mQuestionNumber);
mQuestionNumber++;
}
private void updateScore(int point) {mScoreView.setText("" + mScoreFrankrijk);
}
}
And here is my question library:
package com.example.quizapp;
public class QuestionLibrary {
private String mQuestionsFrankrijk [] = {
"Wat is de hoofdstad van Frankrijk?",
"Wat is de bijnaam van het Franse nationale voetbalelftal",
"Welke van de volgende landen grenst niet aan Frankrijk?",
"Bij welke sport hoort 'le maillot jaune'?",
"Welk museum in Parijs heeft een piramide als ingang?"
};
private String mChoicesFrankrijk [][] = {
{"Lyon", "Parijs", "Nice", "Bordeaux"},
{"La France", "Le Coq Sportif", "Les Bleus", "Les Gagnants"},
{"Zwitserland", "België", "Spanje", "Oostenrijk"},
{"Tennis", "Wielrennen", "Rugby", "Cricket"},
{"Musée d'Orsay", "Musée Rodin", "Louvre", "Centre Georges Pompidou"},
};
private String mCorrectAnswers [] = {"Parijs", "Les Bleus", "Oostenrijk", "Wielrennen", "Louvre"};
public String getQuestionFrankrijk(int a) {
String question = mQuestionsFrankrijk[a];
return question;
}
public String getChoice1Frankrijk(int a) {
String choice0 = mChoicesFrankrijk[a][0];
return choice0;
}
public String getChoice2Frankrijk(int a) {
String choice1 = mChoicesFrankrijk[a][1];
return choice1;
}
public String getChoice3Frankrijk(int a) {
String choice2 = mChoicesFrankrijk[a][2];
return choice2;
}
public String getChoice4Frankrijk(int a) {
String choice3 = mChoicesFrankrijk[a][3];
return choice3;
}
public String getCorrectAnswerFrankrijk(int a) {
String answer = mCorrectAnswers[a];
return answer;
}
}
The easiest solution I can think is to make QuestionLibrary an interface or abstract class. Then implement a Country1QuestionLibrary with a specific country's questions and Country2QuestionLibrary with another set of questions. Then you can dynamically swap out the set of questions being presented to the user by doing
questionLibrary = new Country1QuestionLibrary();
Then you need a way for your user to change the country. On the UI, add another button that's "Change Country" implemented similarly to how your other buttons are working. In the onClickListener, assign the other implementation of QuestionLibrary to the available questions and refresh the question and answers views.
As with most things programming, there are a bunch of ways to implement this. If you can implement the path I'm showing, take some time to try and come up with a different solution on your own after seeing the downfalls or restrictions of this solution.

Android: pass variables to/out button anonymous class

package com.example.rami.androidstudio_312332604_guessgame;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
ArrayList<Character> lettersguessed = new ArrayList<Character>();
int counter = 6;
private String changeCharInPosition(int position, char ch, String str) {
char[] charArray = str.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
private void start() {
TextView errortext = (TextView) findViewById(R.id.statustext);
Button button = (Button) findViewById(R.id.guessbt);
TextView tv = (TextView) findViewById(R.id.guessingtext);//get the textview from the activity
TextView testtext = (TextView) findViewById(R.id.testtext);//get the testview from the activity
EditText edittext = (EditText) findViewById(R.id.editText);
String[] world = getResources().getStringArray(R.array.words);// get the array from string xml
Random rand = new Random();
errortext.setText("");
int randomNum = rand.nextInt(world.length);
String country = world[randomNum];
String s = "";
for (int i = 0; i < country.length(); i++) {
if (country.charAt(i) != ' ')
s += '?';
else
s += ' ';
}
tv.setText(s);
testtext.setText(world[randomNum]);
button.setEnabled(true);
//Toast toast = Toast.makeText(getApplicationContext(), points, Toast.LENGTH_LONG);
//toast.show();
}
// Remove the below line after defining your own ad unit ID.
private static final String TOAST_TEXT = "Test ads are being shown. "
+ "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID.";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start();
Button button = (Button) findViewById(R.id.guessbt);
button.setOnClickListener(new View.OnClickListener() {
ArrayList<Character> lettersguessed = new ArrayList<Character>();
int counter = 6;
private void clear() {
ImageView img = (ImageView) findViewById(R.id.errorimg);
TextView errortext = (TextView) findViewById(R.id.statustext);
img.setImageResource(R.mipmap.error_num0);
counter = 6;
lettersguessed.clear();
errortext.setText("");
}
public void onClick(View v) {
EditText guessedtext = (EditText) findViewById(R.id.editText);
Button button = (Button) findViewById(R.id.guessbt);
TextView questionstext = (TextView) findViewById(R.id.guessingtext);
TextView errortext = (TextView) findViewById(R.id.statustext);
if (guessedtext.getText().length() != 1) {//to make sure it's one char
Toast toast = Toast.makeText(getApplicationContext(), "Please Enter One Char", Toast.LENGTH_SHORT);
toast.show();
guessedtext.setText("");
return;
}
String country = ((TextView) findViewById(R.id.testtext)).getText().toString();
char uc = Character.toUpperCase(guessedtext.getText().charAt(0));
char lc = Character.toLowerCase(guessedtext.getText().charAt(0));
guessedtext.setText("");
if (lettersguessed.contains(uc)) {
Toast toast = Toast.makeText(getApplicationContext(), "You tried that before", Toast.LENGTH_SHORT);
toast.show();
return;
}
lettersguessed.add(uc);
boolean right = false;
for (int i = 0; i < country.length(); i++) {
char cc = country.charAt(i);
if (cc == uc || cc == lc) {
right = true;
questionstext.setText(changeCharInPosition(i, cc, questionstext.getText().toString()));
errortext.setText("You have guessed: " + lettersguessed.toString() + " (" + counter + " tries left)");
}
}
if (!right) {
if (counter == 1) {
Toast toast = Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_SHORT);
toast.show();
clear();
//points=-20;
return;
}
ImageView img = (ImageView) findViewById(R.id.errorimg);
counter--;
img.setImageResource(R.mipmap.error_num1);
errortext.setText("You have guessed: " + lettersguessed.toString() + " (" + counter + " tries left)");
}
if (questionstext.getText().toString().indexOf('?') < 0) {
Toast toast = Toast.makeText(getApplicationContext(), "Done it!", Toast.LENGTH_SHORT);
toast.show();
button.setEnabled(false);
clear();
//points += 20;
return;
}
}
});
Button newtb = (Button) findViewById(R.id.newbt);
newtb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
start();
}
});
Button giveupbt = (Button) findViewById(R.id.giveupbt);
giveupbt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Button button = (Button) findViewById(R.id.guessbt);
String country = ((TextView) findViewById(R.id.testtext)).getText().toString();
TextView guessedtext = (TextView) findViewById(R.id.guessingtext);
guessedtext.setText(country);
button.setEnabled(false);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ArrayList<Character> lettersguessed = new ArrayList<Character>();
int counter = 6;
**These two variables, I want to reach or to make this class vars and reach them from the anonymous class. Because I want to read this and change their value
More info: the button is the guessing button for guessing countries names game and after entering the char into edittext you click this button to make your guess.
Any Ideas?
Just make these two variables as final and then access them in your inner class.
So it then becomes,
final ArrayList<Character> lettersguessed = new ArrayList<Character>();
final int[] counter = new int[1];
counter[0] = 6;
just replace counter by counter[0].

My android app says source not found when i'm debugging it

Hello I'm a college student studying Java. I'm working on a android application. It compiles and shows no error. However when it runs, there's a unexpected close error.
Here's my application. When you click on the calculate ws you purpose to change to this screen.
Here's my code:
package com.warhammerdicerrolleralpha;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class myMain extends Activity
{
EditText enternumberofdice;
final TextView textGenerateNumber = (TextView) findViewById(R.id.text4);
private EditText text, text2, text3;
private Button btutorial1;
int number1 = Integer.parseInt(text.getText().toString());
int number2 = Integer.parseInt(text2.getText().toString());
ImageView i = new ImageView(this);
{
i.setAdjustViewBounds(true);
}
private int myFaceValue;
int myNum;
/**
* Called when the activity is first created.
*
* #return
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void go()
{
while (myNum > 0)
{
// TODO Auto-generated method stub
textGenerateNumber.setText(String.valueOf(enternumberofdice));
--myNum;
return;
}
}
public int roll()
{
int val = (int) (6 * Math.random() + 1); // Range 1-6
setValue(val);
return val;
}
{
try
{
myNum = Integer.parseInt(enternumberofdice.getText().toString());
}
catch (NumberFormatException nfe)
{
enternumberofdice.setText("Does not work");
}
}
public int getValue()
{
return myFaceValue;
}
public void setValue(int myFaceValue)
{
this.myFaceValue = myFaceValue;
}
{
switch (myFaceValue)
{
case 5:
i.setImageResource(R.drawable.dicefive);
break;
case 1:
i.setImageResource(R.drawable.diceone);
break;
case 3:
i.setImageResource(R.drawable.dicethree);
break;
case 2:
i.setImageResource(R.drawable.dicetwo);
break;
case 4:
i.setImageResource(R.drawable.dicefour);
break;
case 6:
i.setImageResource(R.drawable.dicesix);
break;
default:
i.setImageResource(R.drawable.error);
break;
}
text = (EditText) findViewById(R.id.editText1);
text2 =(EditText) findViewById(R.id.editText2);
text3 = (EditText) findViewById(R.id.editText3);
btutorial1 = (Button) findViewById(R.id.button1);
btutorial1.setOnClickListener((OnClickListener) this);
Button buttonGenerate = (Button) findViewById(R.id.button1);
enternumberofdice = (EditText) findViewById(R.id.enternumberofdice);
Button buttonGenerate2 = (Button) findViewById(R.id.battlecalculate);
buttonGenerate2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
setContentView(R.layout.main2);
}
});
buttonGenerate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
go();
roll();
}
});
}
public void onClick(View view)
{
switch (view.getId())
{
case R.id.button1:
if (number1 > number2)
{
text3.setText("Three and above");
return;
}
else if (number1 < number2)
{
text3.setText("Five and above");
return;
}
else if (number1 == number2)
{
text3.setText("Four and above");
return;
}
else
{
text3.setText("Not Working");
return;
}
}
}
}
Look at your stack trace, but I think it may be because of this block:
private EditText text, text2, text3;
private Button btutorial1;
int number1 = Integer.parseInt(text.getText().toString());
int number2 = Integer.parseInt(text2.getText().toString());
It looks as though you are trying to parseInt over null values. You need to specify where text, text2, text3 are in your form using similar code to:
TextView textGenerateNumber = (TextView) findViewById(R.id.text4);
Hope that helps.

Categories