Check Scores in Android Studio - android

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));
}
}

Related

Simple Math Game?

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...
}
}
});

SQLite database columns stay Null on update method in different activities

I use SQLite database to save data from different activities in my app. in the first activity I use the add method to create a row in the table and the next activities use update method to update the created columns. my previous question which is somehow similar can be found here :
Previous Question
Previously my problem was with not using setId. Now my problem is with the third activity. after calling the update method, the columns stay Null. I tried passing the id from NewProjectActivity to the MainActivity and then to the IntensityActivity but I don't know why the columns don't get updated. Here are the codes :
SQLite Helper:
public class SQLiteHelper extends SQLiteOpenHelper implements ProjectDAO {
public SQLiteHelper(Context context) {
super(context, "my_db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("CREATE TABLE tbl_project_info (id INTEGER PRIMARY KEY," +
"name TEXT," +
"company_name TEXT," +
"address TEXT," +
"length1 TEXT," +
"length2 TEXT," +
"length3 TEXT," +
"length4 TEXT," +
"length5 TEXT," +
"diameter1 Text," +
"diameter2 Text," +
"diameter3 Text," +
"diameter4 Text," +
"diameter5 Text," +
"surface Text," +
"soilResistance Text," +
"intensity Text," +
"allowedIntensity Text," +
"intensityResult Text)");
} catch (SQLiteException e) {
Log.e("SQLITE", "onCreate: " + e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public long addProject(Project project) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", project.getName());
contentValues.put("company_name", project.getCompany_name());
contentValues.put("address", project.getAddress());
contentValues.put("length1", project.getLength1());
contentValues.put("length2", project.getLength2());
contentValues.put("length3", project.getLength3());
contentValues.put("length4", project.getLength4());
contentValues.put("length5", project.getLength5());
contentValues.put("diameter1", project.getDiameter1());
contentValues.put("diameter2", project.getDiameter2());
contentValues.put("diameter3", project.getDiameter3());
contentValues.put("diameter4", project.getDiameter4());
contentValues.put("diameter5", project.getDiameter5());
contentValues.put("surface", project.getSurface());
contentValues.put("soilResistance", project.getSoilResistance());
contentValues.put("intensity", project.getIntensity());
contentValues.put("allowedIntensity", project.getAllowedIntensity());
contentValues.put("intensityResult", project.getIonS());
long result = db.insert("tbl_project_info", null, contentValues);
db.close();
return result;
}
#Override
public int getProjectsCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
#Override
public boolean updateProject(Project project) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("length1", project.getLength1());
contentValues.put("length2", project.getLength2());
contentValues.put("length3", project.getLength3());
contentValues.put("length4", project.getLength4());
contentValues.put("length5", project.getLength5());
contentValues.put("diameter1", project.getDiameter1());
contentValues.put("diameter2", project.getDiameter2());
contentValues.put("diameter3", project.getDiameter3());
contentValues.put("diameter4", project.getDiameter4());
contentValues.put("diameter5", project.getDiameter5());
contentValues.put("surface", project.getSurface());
contentValues.put("soilResistance", project.getSoilResistance());
contentValues.put("intensity", project.getIntensity());
contentValues.put("allowedIntensity", project.getAllowedIntensity());
contentValues.put("intensityResult", project.getIonS());
db.update("tbl_project_info", contentValues, "id = ?", new String[]{String.valueOf(project.getId())});
db.close();
return true;
}
#Override
public List<Project> getAllProjects() {
List<Project> projects = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
if (cursor.moveToFirst()) {
do {
Project project = new Project();
project.setName(cursor.getString(0));
project.setCompany_name(cursor.getString(1));
project.setAddress(cursor.getString(2));
projects.add(project);
} while (cursor.moveToNext());
}
return projects;
}
}
NewProjectActivity :
public class NewProjectActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_project);
projectDAO = DBInjector.provideProjectDao(this);
setupViews();
}
private void setupViews() {
final EditText projectNameET = findViewById(R.id.et_newProject_projectName);
final EditText companyNameET = findViewById(R.id.et_newProject_companyName);
final EditText addressET = findViewById(R.id.et_newProject_address);
Button saveInfoBTN = findViewById(R.id.btn_newProject_saveInfo);
saveInfoBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long projectID = -1;
if (projectNameET.length() > 0) {
if (companyNameET.length() > 0) {
if (addressET.length() > 0) {
Project project = new Project();
project.setName(projectNameET.getText().toString());
project.setCompany_name(companyNameET.getText().toString());
project.setAddress(addressET.getText().toString());
projectID = projectDAO.addProject(project);
if (projectID > 0){
Toast.makeText(NewProjectActivity.this, "Success", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(NewProjectActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
}else {
companyNameET.setError("company name not entered");
}
}else{
projectNameET.setError("project name not entered");
}
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(NewProjectActivity.this);
manager.setID(projectID);
Intent intent = new Intent(NewProjectActivity.this,MainActivity.class);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
});
}
}
MainActivity :
public class MainActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
private long mProjectID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
projectDAO = DBInjector.provideProjectDao(this);
mProjectID = getIntent().getLongExtra("IE_PROJECTID",0);
final EditText lengthET1 = findViewById(R.id.et_main_length1);
final EditText lengthET2 = findViewById(R.id.et_main_length2);
final EditText lengthET3 = findViewById(R.id.et_main_length3);
final EditText lengthET4 = findViewById(R.id.et_main_length4);
final EditText lengthET5 = findViewById(R.id.et_main_length5);
final EditText diameterET1 = findViewById(R.id.et_main_diameter1);
final EditText diameterET2 = findViewById(R.id.et_main_diameter2);
final EditText diameterET3 = findViewById(R.id.et_main_diameter3);
final EditText diameterET4 = findViewById(R.id.et_main_diameter4);
final EditText diameterET5 = findViewById(R.id.et_main_diameter5);
Button calculateButton = findViewById(R.id.btn_main_calculate);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float Le1 = 0;
if (lengthET1.length() > 0) {
String L1 = lengthET1.getText().toString();
Le1 = Float.parseFloat(L1);
}
float Di1 = 0;
if (diameterET1.length() > 0) {
String D1 = diameterET1.getText().toString();
Di1 = Float.parseFloat(D1);
}
float Le2 = 0;
if (lengthET2.length() > 0) {
String L2 = lengthET2.getText().toString();
Le2 = Float.parseFloat(L2);
}
float Di2 = 0;
if (diameterET2.length() > 0) {
String D2 = diameterET2.getText().toString();
Di2 = Float.parseFloat(D2);
}
float Le3 = 0;
if (lengthET3.length() > 0) {
String L3 = lengthET3.getText().toString();
Le3 = Float.parseFloat(L3);
}
float Di3 = 0;
if (diameterET3.length() > 0) {
String D3 = diameterET3.getText().toString();
Di3 = Float.parseFloat(D3);
}
float Le4 = 0;
if (lengthET4.length() > 0) {
String L4 = lengthET4.getText().toString();
Le4 = Float.parseFloat(L4);
}
float Di4 = 0;
if (diameterET4.length() > 0) {
String D4 = diameterET4.getText().toString();
Di4 = Float.parseFloat(D4);
}
float Le5 = 0;
if (lengthET5.length() > 0) {
String L5 = lengthET5.getText().toString();
Le5 = Float.parseFloat(L5);
}
float Di5 = 0;
if (diameterET5.length() > 0) {
String D5 = diameterET5.getText().toString();
Di5 = Float.parseFloat(D5);
}
final float Surface1 = (float) (Le1 * Di1 * Math.PI);
final float Surface2 = (float) (Le2 * Di2 * Math.PI);
final float Surface3 = (float) (Le3 * Di3 * Math.PI);
final float Surface4 = (float) (Le4 * Di4 * Math.PI);
final float Surface5 = (float) (Le5 * Di5 * Math.PI);
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(MainActivity.this);
manager.setSuface(Surface);
Project project = new Project();
project.setId(mProjectID);
project.setLength1(lengthET1.getText().toString());
project.setDiameter1(diameterET1.getText().toString());
project.setLength2(lengthET2.getText().toString());
project.setDiameter2(diameterET2.getText().toString());
project.setLength3(lengthET3.getText().toString());
project.setDiameter3(diameterET3.getText().toString());
project.setLength4(lengthET4.getText().toString());
project.setDiameter4(diameterET4.getText().toString());
project.setLength5(lengthET5.getText().toString());
project.setDiameter5(diameterET5.getText().toString());
project.setSurface(String.valueOf(Surface));
projectDAO.updateProject(project);
}
});
}
}
IntensityActivity :
public class IntensityActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
private long mProjectID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intensity);
projectDAO = DBInjector.provideProjectDao(this);
mProjectID = getIntent().getLongExtra("IE_PROJECTID",0);
final float Result = getIntent().getFloatExtra("Result",0);
final Button resistanceBTN1 = findViewById(R.id.btn_intensity_R1);
final Button resistanceBTN2 = findViewById(R.id.btn_intensity_R2);
final Button resistanceBTN3 = findViewById(R.id.btn_intensity_R3);
final Button resistanceBTN4 = findViewById(R.id.btn_intensity_R4);
final Button resistanceBTN5 = findViewById(R.id.btn_intensity_R5);
final View RL = findViewById(R.id.rl_intensity_allowedIntensity);
final TextView allowedResistance = findViewById(R.id.tv_intensity_allowedIntensityNumber);
final TextView surfaceNumber = findViewById(R.id.tv_intensity_surfaceNumber);
final EditText intensityNumber = findViewById(R.id.et_intensity_intensityNumber);
Button calculateButton = findViewById(R.id.btn_intensity_calculate);
final Button goToVoltageButton = findViewById(R.id.btn_intensity_goToVoltage);
final TextView formulaResultNumber = findViewById(R.id.tv_intensity_resultNumber);
String Sur = Float.toString(Result);
surfaceNumber.setText(Sur);
final double R1 = Result*0.250;
final double R2 = Result*0.125;
final double R3 = Result*0.050;
final double R4 = Result*0.025;
final double R5 = Result*0.010;
final String Re1 = Double.toString(R1);
final String Re2 = Double.toString(R2);
final String Re3 = Double.toString(R3);
final String Re4 = Double.toString(R4);
final String Re5 = Double.toString(R5);
resistanceBTN1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re1);
}
});
resistanceBTN2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re2);
}
});
resistanceBTN3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re3);
}
});
resistanceBTN4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re4);
}
});
resistanceBTN5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re5);
}
});
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String I = intensityNumber.getText().toString();
float In = Float.parseFloat(I);
float R = In/Result;
String Res = String.valueOf(R);
formulaResultNumber.setText(Res);
goToVoltageButton.setVisibility(View.VISIBLE);
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(IntensityActivity.this);
manager.setIntensity(In);
}
});
goToVoltageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(IntensityActivity.this,SimpleVoltage.class);
startActivity(intent);
Project project = new Project();
project.setId(mProjectID);
project.setAllowedIntensity(String.valueOf(allowedResistance));
project.setIntensity(intensityNumber.getText().toString());
projectDAO.updateProject(project);
}
});
}
}
From MainActivity to IntensityActivity, What I found is that you are always passing -1 in Project ID
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
Instead you can pass the same ID you have got on this activity from Intent
Just update your code in MainActivity as below and pass mProjectID.
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",mProjectID);
startActivity(intent);
}
Hope this will help.
try this way in your update method,
db.update("tbl_project_info", contentValues, "id="+String.valueOf(project.getId()), null);
Also you need to change following line into MainActivity.java
long projectID = -1;
to
long projectID = mProjectID;

R.string provides me numbers

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`

Perimeter in Android Studio

I'm supposed to generate two random numbers, then find the perimeter of a rectangle with them. Then it allows the User to input their answer in a EditText, when the User inputs their answer in the EditText, There is a submit button so that when the user clicks it, it lets the person know if their answer is correct or incorrect. This is displayed as a toast message. The problem i have, is when i click the submit button, it always show says "The answer is incorrect even if i put in the right value in the EditText. Would appreciate some help. Thank You
public class Perimeter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perimeter);
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) {
Random rand = new Random();
int number = rand.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
String myString = String.valueOf(number);
myText.setText(myString);
Random rand2 = new Random();
int number2 = rand2.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
String 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){
int perimeter;
Random randOne = new Random();
int number = randOne.nextInt(12) + 1;
TextView myText = (TextView) findViewById(R.id.rand1);
String myString = String.valueOf(number);
myText.setText(myString);
Random randTwo = new Random();
int number2 = randTwo.nextInt(12) + 1;
TextView myText2 = (TextView) findViewById(R.id.rand2);
String myString2 = String.valueOf(number2);
myText2.setText(myString2);
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();
}
}
}
Your problem is that you are generating completely different random numbers when you go to check the answer. You need to save the numbers in instance variables like so.
public class Perimeter extends AppCompatActivity {
private int number1, number2;
private Random rand;
onCreate() {
rand = new Random();
}
PerimeterGame(View view) {
number1 = rand.nextInt(12) + 1;
number2 = rand.nextInt(12) + 1;
}
AnswerCheck(View view) {
// Don't make new random variables here, just check your inputs.
EditText num = (EditText)findViewById(R.id.answertext);
int val = Integer.parseInt(num.getText().toString() );
int perimeter= 2*(number + number2);
if (val == perimeter) { }
}
}
In AnswerCheck you dont need to generate new numbers again.. you need to get old generated numbers in first method PerimeterGame() and do your formula with them.

TextViews become uneditable after reactivating activity?

So currently I am making an educational application where users can view how to solve a given problem by pressing a button. While my code works fine initially, when I hit the back button and click my View Solution button, my default layout pops up and I cannot edit the last four TextViews. Here is my code:
public class AdditionTensSolutionActivity extends Activity {
public static ArrayList<TextView> explain = new ArrayList<TextView>(3);
public static Button nextstep;
public static int onesnum1 = TensAdditionExerciseActivity.n1display % 10;
public static int onesnum2 = TensAdditionExerciseActivity.n2display % 10;
public static int onesanswer = onesnum1 + onesnum2;
public static int onesanswermod = onesanswer % 10;
public static int tensnum1 = TensAdditionExerciseActivity.n1display / 10;
public static int tensnum2 = TensAdditionExerciseActivity.n2display / 10;
public static int tensanswer = tensnum1 + tensnum2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showsolutionlayout);
TextView numrow1 = (TextView) findViewById(R.id.solproblemrow1);
TextView numrow2 = (TextView) findViewById(R.id.solproblemrow2);
TextView solution = (TextView) findViewById(R.id.solutiontextview);
TextView carryover = (TextView) findViewById(R.id.carryovernumbers);
TextView exp1 = (TextView) findViewById(R.id.explain1);
TextView exp2 = (TextView) findViewById(R.id.explain2);
TextView exp3 = (TextView) findViewById(R.id.explain3);
TextView exp4 = (TextView) findViewById(R.id.explain4);
numrow1.setText(TensAdditionExerciseActivity.n1display + "");
numrow2.setText(" " + TensAdditionExerciseActivity.n2display + " +");
explain.add(exp1);
explain.add(exp2);
explain.add(exp3);
explain.add(exp4);
nextstep = (Button) findViewById(R.id.nextstep);
for (int i = 0; i < 4; i++) {
explain.get(i).setVisibility(View.GONE);
}
solution.setVisibility(View.GONE);
carryover.setVisibility(View.GONE);
explain.get(0).setText("test");
setTextViews();
nextButtonsetOnClickListener();
}
protected void nextButtonsetOnClickListener() {
nextstep.setOnClickListener(new View.OnClickListener() {
int i = 0;
public void onClick(View v) {
explain.get(i).setVisibility(View.VISIBLE);
i++;
if (i > 2 && onesanswer < 10) {
nextstep.setClickable(false);
}
if (i > 3 && onesanswer >= 10) {
nextstep.setClickable(false);
}
}
});
}
protected void setTextViews() {
explain.get(0).setText(
"Add " + (onesnum1) + " and " + (onesnum2) + " which equals "
+ (onesanswer) + ".");
if (onesanswer >= 10) {
explain.get(1).setText(
"Since the answer is 10 or greater, 1 must carry over to the tens place and "
+ onesanswermod + " is left in the ones place.");
explain.get(2).setText(
"Add the tens place digits, " + tensnum1 + " and "
+ tensnum2
+ ". Don't forget to add the carried over 1!");
explain.get(3).setText(
"1 + " + tensnum1 + " + " + tensnum2 + " = "
+ (tensanswer + 1));
} else {
explain.get(1).setText(
"Add the tens place digits: " + tensnum1 + " and "
+ tensnum2 + ".");
explain.get(2).setText(
tensnum1 + " + " + tensnum2 + " = " + tensanswer);
}
Ah, I figured it out. I had my ArrayList set to static rather than final, but I still do not completely the entirety of my error. Would someone be willing to tell me why it made such a big difference?
A static variable / method has only one instance for the entire class. That means, that in the case of your listview, only one exists for all instances of your activity in the entire app, which is why your getting your error. Final means that it can't be initialized anywhere other than the constructor or when the variable is defined. (Difference between Static and final?).

Categories

Resources