I have this code which is not working:
public class MainActivity extends AppCompatActivity {
int quantity=2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i( "MainActivity", "modriodfw" + (R.string.Thankyou));
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
EditText nombre = (EditText) findViewById(R.id.nombre);
String nombre1 = nombre.getText().toString();
boolean cream = getstate();
boolean chocolate = getcState();
int price = calculatePrice(cream, chocolate);
String summary = createOrderSummary(price, cream,chocolate,nombre1);
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, (R.string.OrderMail) + nombre1);
intent.putExtra(Intent.EXTRA_TEXT, summary);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
displayMessage(summary);
}
public void clearText(View view)
{
EditText nombre = (EditText) findViewById(R.id.nombre);
nombre.setText("");
}
private boolean getcState()
{
CheckBox state = (CheckBox) findViewById(R.id.chocolate);
boolean chocolateState = state.isChecked();
return chocolateState;
}
private boolean getstate()
{
CheckBox state = (CheckBox) findViewById(R.id.cream);
boolean creamState = state.isChecked();
return (creamState);
}
private String createOrderSummary(int price, boolean cream, boolean chocolate,String nombre1)
{
String summary = (R.string.name) + nombre1;
if(cream && chocolate == false){
summary += "\n" + quantity + (R.string.name);
}
if(chocolate && cream == false){
summary += "\n" + quantity + (R.string.SummaryCream);
}
if(chocolate && cream){
summary += "\n" + quantity + (R.string.SummaryBoth);
}
summary += "\nTotal: $" +price;
summary += "\n" + (R.string.Thankyou);
return summary;
}
private int calculatePrice(boolean cream, boolean chocolate) {
int price = 5;
if (cream) {
price = price + 1;
}
if (chocolate) {
price = price + 2;
}
price = price * quantity;
return price;
}
public void increase(View view) {
if (quantity == 99){
Toast.makeText(this, (R.string.high), Toast.LENGTH_SHORT).show();
return;
}
quantity= quantity + 1;
display(quantity);
}
public void decrease(View view){
if (quantity == 1){
Toast.makeText(this, (R.string.less), Toast.LENGTH_SHORT).show();
return;
}
quantity= quantity - 1;
display(quantity);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int numb) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText("" + numb);
}
/**
* This method displays the given text on the screen.
*/
private void displayMessage(String Summary) {
TextView summaryTextView = (TextView) findViewById(R.id.Summary_text_view);
summaryTextView.setText(Summary);
}
and all I get is this:
2131099680
Total: $10
2131099676
and it should be
Name:
summary
total $
Thank You!
im using java in android studio.
You need to do context.getString(R.string.your_string), as R.string.your_string on its own is just a reference.
You have forgotten to call getString method in four places. I update your code :
private String createOrderSummary(int price, boolean cream, boolean chocolate,String nombre1)
{
String summary = getString(R.string.name) + nombre1;
if(cream && chocolate == false){
summary += "\n" + quantity + getString(R.string.SummaryChocolate);
}
if(chocolate && cream == false){
summary += "\n" + quantity + getString(R.string.SummaryCream);
}
if(chocolate && cream){
summary += "\n" + quantity + getString(R.string.SummaryBoth);
}
summary += "\nTotal: $" +price;
summary += "\n" + getString(R.string.Thankyou);
return summary;
}`enter code here`
Related
I am new in Android and I would like to create simple Math quiz. I have a one textview that I display random question with random operator as below code.I would like, user will input their answer to EditText and submit their answer with ImageButton that I called submit answer. My question is, I could not handle to check user answer on Edittext via different method.How can I check user answer that evaluate the answer after submitbutton ?
public class MainActivity extends AppCompatActivity {
int number1, number2, result;
public EditText answer;
char operator;
ImageButton submitAnswer;
Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rnd = new Random();
number1 = rnd.nextInt(100) + 1;
number2 = rnd.nextInt(100) + 1;
generateOperator();
TextView question = findViewById(R.id.questionText);
question.setText(number1 + " " + operator + " " + number2 + " " + "=" + " " + "?");
}
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1+number2;
} else if (op == 2) {
operator = '-';
result= number1-number2;
} else if (op == 3) {
operator = '*';
result = number1+number2;
}
return operator;
}
public void submitAnswer(View view) {
submitAnswer = findViewById(R.id.submitButton);
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( result == Integer.valueOf(answer.getText().toString())){
Toast.makeText(view.getContext(), "Correct",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(view.getContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
First of all, edir your generateOperator() method to keep answer.
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1 + number2;
} else if (op == 2) {
operator = '-';
result = number1 - number2;
} else if (op == 3) {
operator = '*';
result = number1 * number2;
}
return operator;
}
And then you can simply compare your result and the user's answer.
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(result == Integer.valueOf(answer.getText().toString())){
//Answer is ok.
}
else {
//Some code...
}
}
});
I have a problem with my app and i can’t figure it out how to solve it :(
I made a quiz app. Radio Buttons works okey, open question works okey, I have a problem with Checkboxes. When I select all 3 checkboxes (where the correct answers are two), it still marks me as the correct answer… What am I doing wrong? Thanks! :(
package com.example.francesco.askzelda;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button submit;
int correctAnswers = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Make sure that user can only choose the two of the answers not all of them.
public void checkTwoBox(View view) {
CheckBox firstcheck = (CheckBox) findViewById(R.id.optionQ3_1);
CheckBox secondcheck = (CheckBox) findViewById(R.id.optionQ3_2);
CheckBox thirdcheck = (CheckBox) findViewById(R.id.optionQ3_3);
if (firstcheck.isChecked() && secondcheck.isChecked()) {
thirdcheck.setChecked(false);
}
if (thirdcheck.isChecked() && secondcheck.isChecked()) {
firstcheck.setChecked(false);
}
if (thirdcheck.isChecked() && firstcheck.isChecked()) {
secondcheck.setChecked(false);
}
}
//Show the result
public void submitResult(View view) {
//figure out if the user choose the right answer
RadioButton firstRightBox = (RadioButton) findViewById(R.id.option1_rb);
boolean hasClickedFirst1 = firstRightBox.isChecked();
RadioButton secondRightBox = (RadioButton) findViewById(R.id.optionQ2_2_rb);
boolean hasClickedSecond2 = secondRightBox.isChecked();
CheckBox thirdRightBox = (CheckBox) findViewById(R.id.optionQ3_1);
boolean hasClickedThird1 = thirdRightBox.isChecked();
CheckBox thirdSecondRightBox = (CheckBox) findViewById(R.id.optionQ3_3);
boolean hasClickedThird3 = thirdSecondRightBox.isChecked();
EditText answerText = (EditText) findViewById(R.id.question_4_editText);
String MasterSword = answerText.getText().toString();
//figure out if the user choose the wrong answer
RadioButton firstWrongBox = (RadioButton) findViewById(R.id.option2_rb);
boolean hasClickedFirst2 = firstWrongBox.isChecked();
RadioButton firstWrongBox2 = (RadioButton) findViewById(R.id.option3_rb);
boolean hasClickedFirst3 = firstWrongBox2.isChecked();
RadioButton secondWrongBox = (RadioButton) findViewById(R.id.optionQ2_1_rb);
boolean hasClickedSecond1 = secondWrongBox.isChecked();
RadioButton secondWrongBox2 = (RadioButton) findViewById(R.id.optionQ2_3_rb);
boolean hasClickedSecond3 = secondWrongBox2.isChecked();
CheckBox thirdWrongBox = (CheckBox) findViewById(R.id.optionQ3_2);
boolean hasClickedThird2 = thirdWrongBox.isChecked();
int correctAnswer = calculateCorrectAnswer(hasClickedFirst1, hasClickedSecond2, hasClickedThird1, hasClickedThird2, hasClickedThird3, MasterSword);
int wrongAnswer = calculateWrongAnswer(hasClickedFirst2, hasClickedFirst3, hasClickedSecond1, hasClickedSecond3, hasClickedThird2, hasClickedThird1, hasClickedThird3, MasterSword);
int emptyAnswer = calculateEmptyAnswer(hasClickedFirst1, hasClickedSecond2, hasClickedThird1, hasClickedThird2, hasClickedThird3, MasterSword, hasClickedFirst2, hasClickedFirst3, hasClickedSecond1, hasClickedSecond3);
String quizMessage = createOrderSummary(correctAnswer, wrongAnswer, emptyAnswer);
// Toast Message
String toast_1 = getString(R.string.toast_1);
String toast_2 = getString(R.string.toast_2);
String toast_3 = getString(R.string.toast_3);
Toast.makeText(MainActivity.this,toast_1 + " " + correctAnswer + " " + toast_2 + " \n" + toast_3, Toast.LENGTH_LONG).show();
displayMessage(quizMessage);
}
private String createOrderSummary(int correctAnswer, int wrongAnswer, int emptyAnswer) {
String msg1 = getString(R.string.thank1);
String msg2 = getString(R.string.thank2);
String msg3 = getString(R.string.total_correct);
String msg4 = getString(R.string.total_wrong);
String msg5 = getString(R.string.total_empty1);
String msg6 = getString(R.string.total_empty2);
String msg7 = getString(R.string.final_msg1);
String msg8 = getString(R.string.final_msg2);
String msg9 = getString(R.string.final_msg3);
String quizMessage = msg1 + " " + " " + msg2;
quizMessage += "\n" + msg3 + " " + correctAnswer;
quizMessage += "\n" + msg4 + " " + wrongAnswer;
quizMessage += "\n" + msg5 + " " + emptyAnswer + " " + msg6;
if (correctAnswer <= wrongAnswer) {
quizMessage += "\n" + msg7;
} else {
quizMessage += "\n" + msg8;
}
quizMessage += "\n" + msg9;
return quizMessage;
}
//Calculates correct
public int calculateCorrectAnswer(boolean first1, boolean second2, boolean third1, boolean third2, boolean third3, String LeoTolstoy) {
int correct = 0;
if (first1) {
correct = correct + 1;
}
if (second2) {
correct = correct + 1;
}
if (third1 & third3) {
correct = correct + 1;
}
if (LeoTolstoy.equals("Master Sword")) {
correct = correct + 1;
}
int correctAnswer = correct;
return correctAnswer;
}
//Calculates false
public int calculateWrongAnswer(boolean first2, boolean first3, boolean second1, boolean second3, boolean third2, boolean third1, boolean third3, String MasterSowrd) {
int wrong = 0;
if (first2) {
wrong = wrong + 1;
}
if (first3) {
wrong = wrong + 1;
}
if (second1) {
wrong = wrong + 1;
}
if (second3) {
wrong = wrong + 1;
}
if ((third1 & third2) || (third3 & third2) || (third3 & third2 & third1)) {
wrong = wrong + 1;
}
if (!MasterSowrd.equals("Master Sword") && !MasterSowrd.equals("")) {
wrong = wrong + 1;
}
int wrongAnswer = wrong;
return wrongAnswer;
}
//calculate empty questions
public int calculateEmptyAnswer(boolean first1, boolean second2, boolean third1, boolean third2, boolean third3, String MasterSowrd, boolean first2, boolean first3, boolean second1, boolean second3) {
int empty = 0;
if (!first1 && !first2 && !first3) {
empty = empty + 1;
}
if (!second1 && !second2 && !second3) {
empty = empty + 1;
}
if ((!third1 && !third3 && !third2) || (third1 && !third3 && !third2) || (third3 && !third1 && !third2) || (third2 && !third1 && !third3)) {
empty = empty + 1;
}
if (MasterSowrd.equals("")) {
empty = empty + 1;
}
int emptyAnswer = empty;
return emptyAnswer;
}
//This method displays the given text on the screen.
public void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.result_text_view);
orderSummaryTextView.setText(message);
}
}
You could do something like this:
public void runThisEveryTimeTheUserClicksAnyCheckBox(CheckBox mostRecentlySelectedCheckBox) {
CheckBox firstcheck = (CheckBox) findViewById(R.id.optionQ3_1);
CheckBox secondcheck = (CheckBox) findViewById(R.id.optionQ3_2);
CheckBox thirdcheck = (CheckBox) findViewById(R.id.optionQ3_3);
CheckBox[] allCheckBoxes = new CheckBox[]{firstcheck, secondcheck, thirdcheck};
int totalChecked = 0;
for (CheckBox checkBox : allCheckBoxes) {
if ( checkBox.isSelected() ) {
totalChecked++;
}
}
if (totalChecked == 3) {
mostRecentlySelectedCheckBox.setSelected(false);
}
}
Then you won't need the checkTwoBox method anymore.
I wrote the core to add PDF pages to shared-preference for bookmarks, but when I click the image neither the image get changed nor the page number added to the book mark list.
Below is my code. It show me no error and image get clicked but the page number not added to spinner for book mark list.
Before I used a textview for the task and that was working fine but now I want a tag image to get changed when I tag or un-tag a page.
#EActivity(R.layout.activity_main)
#OptionsMenu(R.menu.actionbar)
public class PDFViewActivity extends SherlockActivity implements OnPageChangeListener, View.OnClickListener {
public static final String SAMPLE_FILE = "myfile.pdf";
public static final String KEY_BOOKMARKS = "bookmarks_pages";
#ViewById
PDFView pdfView;
#NonConfigurationInstance
String pdfName = SAMPLE_FILE;
#NonConfigurationInstance
Integer pageNumber = 1;
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
Spinner bookmarkSp;
ArrayAdapter<String> dataAdapter;
private final int TotalPages = 57;
#AfterViews
void afterViews() {
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
display(pdfName, false);
}
int check = 0;
private void display(String assetFileName, boolean jumpToFirstPage) {
if (jumpToFirstPage) pageNumber = 1;
int x = TotalPages;
int[] page_seq = new int[TotalPages];
for (int i = 0; i < TotalPages; i++) {
page_seq[i] = --x;
Log.d("testdesp", "" + page_seq[i]);
}
// .pages(2,1,0)
pdfView.fromAsset(assetFileName)
.defaultPage(TotalPages)
.pages(page_seq)
.onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
((TextView) findViewById(R.id.tv_total_page)).setText("/ " + pdfView.getPageCount());
}
})
.onPageChange(this)
.load();
findViewById(R.id.btn_go).setOnClickListener(this);
findViewById(R.id.tag_btn).setOnClickListener(this);
bookmarkSp = (Spinner) findViewById(R.id.sp_bookmark_list);
List<String> list = new ArrayList<String>();
String pages = sharedpreferences.getString(KEY_BOOKMARKS, "");
String[] split = pages.split(",");
list.add("");
for (String val : split)
if (val.length() > 0) {
int value = Integer.parseInt(val);
// value = pdfView.getPageCount() - (value - 1);
value = TotalPages - (value - 1);
list.add("" + value);
}
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bookmarkSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (++check > 1) {
String val = (String) parent.getItemAtPosition(position);
if (val.length() > 0) {
int value = Integer.parseInt(val);
value = pdfView.getPageCount() - (value - 1);
pdfView.jumpTo(value);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
bookmarkSp.setAdapter(dataAdapter);
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
((EditText) findViewById(R.id.et_page_number)).setText(pageCount - (pageNumber - 1) + "");
if (check(page))
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.tagged);
else
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.untaged);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private boolean displaying(String fileName) {
return fileName.equals(pdfName);
}
#Override
public void onClick(View view) {
view.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_out));
switch (view.getId()) {
case R.id.btn_go:
int page = Integer.parseInt(((EditText) findViewById(R.id.et_page_number)).getText().toString());
page = TotalPages - (page - 1);
pdfView.jumpTo(page);
break;
case R.id.tag_btn:
if (((ImageView) findViewById(R.id.tag_btn)).getDrawable().getConstantState() == getResources().getDrawable(R.drawable.untaged).getConstantState() ) {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "") + pageNumber + ",").commit();
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.tagged);
dataAdapter.add(pdfView.getPageCount() - (pageNumber - 1) + "");
dataAdapter.notifyDataSetChanged();
} else if (((ImageView) findViewById(R.id.tag_btn)).getDrawable().getConstantState() == getResources().getDrawable(R.drawable.tagged).getConstantState() ) {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "").replace(pageNumber + ",", "")).commit();
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.untaged);
dataAdapter.remove(TotalPages - (pageNumber - 1) + "");
dataAdapter.notifyDataSetChanged();
}
break;
}
}
boolean check(int page) {
String number = sharedpreferences.getString(KEY_BOOKMARKS, "");
Log.d("testdisp", pdfView.getPageCount() + " ** " + number + " ****" + number.contains(page + ","));
return number.contains(page + ",");
}
}
I resolved my issue by adding a drawable resource
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#drawable/tagged" />
<item android:state_checked="false" android:drawable="#drawable/untaged" />
</selector>
and made below changes in my java activity code.
if (((CheckBox) findViewById(R.id.chk_tag)).isChecked()) {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "") + pageNumber + ",").commit();
((CheckBox) findViewById(R.id.chk_tag)).setChecked(true);
dataAdapter.add(pdfView.getPageCount() - (pageNumber - 1) + "");
dataAdapter.notifyDataSetChanged();
} else {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "").replace(pageNumber + ",", "")).commit();
((CheckBox) findViewById(R.id.chk_tag)).setChecked(false);
}
I am trying to get the string of the EditText and if it is " I want to get " also but the string is appearing this in the EditText
android.support.v7.widget.AppCompatEditText{42e33310 VFED..CL .F ....ID40,40-1160,315 #7f0c006f app:id\CalculatorDisplay}
after getting it and giving it to the EditText again
and here is a part of the onClick that works when I press a button and the rest of it is not dealing with this problem the problem is in NoRepeatNumber as I tested that when I get it in TestTV TextView I saw the code above
public void onClick(View view) {
TestTV.setText("enterd ");
String buttonPressed = ((Button) view).getText().toString();
PublicButtonPressed = buttonPressed;
if (DIGITS.contains(buttonPressed)) {
SinOrNumber=2;
TestTV.append("numbering");
// digit was pressed
if (!Started) {
mCalculatorDisplay.setText("");
TestTV.append("\nenterd setText");
} else {
TestTV.append("\nenterd setText eslse");
}
if (Started) {
OperationEnded = true;
}
if (NumberingEnded) {
FullNumber = String.valueOf(Number[Ni]);
Ni++;
NumberingEnded = false;
FullCalculation= FullNumber + " ";
NoRepeatNumber="";
DisplayCalculations();
}
FullNumber = FullNumber + buttonPressed;
Number[Ni] = Integer.parseInt(FullNumber);
TestTV.append("\nNumber[" + Ni + "] =" + + Number[Ni] + "\n" + "buttonPressed =" + buttonPressed + "\nFullNumber =" + FullNumber);
//DisplayCalculations();
if ("".equals(mCalculatorDisplay)) {
TestTV.append("\nentered equal\"\"");
NoRepeatNumber="";
} else {
if (NoRepeatNumber == "") {
NoRepeatNumber = String.valueOf(mCalculatorDisplay);
TestTV.append("\nNoRepeatNumber =" + NoRepeatNumber);
}
}
if(!NumberingEnded){
mCalculatorDisplay.setText(NoRepeatNumber + FullNumber);
}
if (!Started) {
Started = true;
}
if (userIsInTheMiddleOfTypingANumber) {
if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
// ERROR PREVENTION
// Eliminate entering multiple decimals
} else {
Number[Ni] = Integer.parseInt(FullNumber);
}
}
userIsInTheMiddleOfTypingANumber = true;
} else {}}
Call mCalculatorDisplay.getText().toString() instead of String.valueOf(mCalculatorDisplay).
I guess mCalculatorDisplay is an EditText?
Update: NoRepeatNumber = String.valueOf(mCalculatorDisplay); - this is the problem part
This is my Code. When the user enters their answer and press the Submit Button which is the AnswerCheck Method, i would like the score to be shown in a TextView for example - if they input the right answer, the TextView would state 1 correct out of 1. I would like some help, Thanks
public class Perimeter extends AppCompatActivity {
private int number;
private int number2;
private String myString;
private String myString2;
private int perimeter;
private Random rand;
private Random rand2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perimeter);
rand = new Random();
rand2 = new Random();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public void PerimeterGame(View view) {
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
}
}
Set two global int variables
private int totalQuestion = 0;
and private int correctQuestions = 0;
Inside public void PerimeterGame(View view) increment totalQuestion by one.
When the answer is correct, inside public void AnswerCheck(View view) increment correctQuestion by one.
Finally, display the text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
Hope it helps.
public class Perimeter extends AppCompatActivity {
// Code ommitted
private int totalQuestion = 0 ;
private int correctQuestions = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Code ommitted
}
public void PerimeterGame(View view) {
// Increment totalQuestion
totalQuestion++;
number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
myString = String.valueOf(number);
myText.setText(myString);
number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
myString2 = String.valueOf(number2);
myText2.setText(myString2);
((TextView) findViewById(R.id.question)).setText
("Find the perimeter of a rectange with a width of " + myString + "cm" + " and " + "length of " + myString2 + "cm" + ".");
}
public void AnswerCheck(View view) {
EditText num = (EditText) findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString());
perimeter = (number + number2 + number + number2);
if (val == perimeter) {
correctQuestions++;
Toast.makeText(this, "The answer is correct", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "The answer is incorrect ", Toast.LENGTH_SHORT).show();
}
findViewById(R.id.showsolbutton).setEnabled(true);
// Display text
youTextView.setText(String.valueOf(correctQuestions) + " correct out of " + String.valueOf(totalQuestion));
}
}