I would like to ask for some help with my android code.
It should add one point with correct radiobutton and checkbox click - which it does - but there is an error, which I can't find out why.:
here is the java code:
package com.example.android.myquizapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import static com.example.android.myquizapp.R.id.Tom;
import static com.example.android.myquizapp.R.id.score;
public class MainActivity extends AppCompatActivity {
Button btnSubmit;
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSubmit = (Button)findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
int score = 0;
if (((RadioButton)findViewById(R.id.Monica)).isChecked()) {score++;}
if (((RadioButton)findViewById(R.id.h5)).isChecked()) {score++;}
if (((RadioButton)findViewById(R.id.a3)).isChecked()) {score++;}
if (((CheckBox) findViewById(R.id.Tom)).isChecked()){score++;}
if (((CheckBox) findViewById(R.id.Brad)).isChecked()){score++;}
if (((CheckBox) findViewById(R.id.Bruce)).isChecked()){score++;}
{displayResult(score);}}
});}
private void displayResult() {
String message = "You scored " + score;
message += " out of 6";
message += "\nWell done!";
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0 , 0);
toast.show();
}}
the word "score" is red underlined in Android studio:
{displayResult(score);}}
the app works fine, so not quite understand why.
Can you help me?
Your displayResult() method does not have any arguments. And you are passing an argument to it. That is why your are seeing that red line
And How on the earth is your app working fine. You can't even compile that code with this error.
firstly you have declare int score = 0; globally, So you don't need to declare locally in Onclick method. remove following line from Onclick method.
int score = 0;
then you are passing param score to displayResult() method but you have declared with no params.call
displayResult();
Firstly you are passing the int score to the displayResult() method which is not expecting any arguments and secondly you are wrapping it around extra {} brackets which is wrong.
Also you have initialized Button btnSubmit twice which is also wrong and now since you are passing the score value there is no need to create global score which is redundant and not being used anywhere.
You should modify you code as:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
int score = 0;
if (((RadioButton)findViewById(R.id.Monica)).isChecked()) {score++;}
if (((RadioButton)findViewById(R.id.h5)).isChecked()) {score++;}
if (((RadioButton)findViewById(R.id.a3)).isChecked()) {score++;}
if (((CheckBox) findViewById(R.id.Tom)).isChecked()){score++;}
if (((CheckBox) findViewById(R.id.Brad)).isChecked()){score++;}
if (((CheckBox) findViewById(R.id.Bruce)).isChecked()){score++;}
displayResult(score);
}
});}
private void displayResult(int score) {
String message = "You scored " + score;
message += " out of 6";
message += "\nWell done!";
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0 , 0);
toast.show();
}
}
Hope this solves your issues
Related
I want the EditText element print the value I have entered in the UserInputs Array. I have tried Log.v and doInBackground,but that doesn't work.
I would be happy if you can explain how do I print the needed value in the EditText in the future, because I'm new in the Adnroid development.
I can send .xml file if needed.
Also, don't mind comments inside the code...
This is the code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import java.util.*;
public class MainActivity extends AppCompatActivity {
private EditText user_input;
private EditText user_input1;
private Button Button;
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_input = findViewById(R.id.user_input);
Button = findViewById(R.id.Button);
result = findViewById(R.id.result);
user_input1 = findViewById(R.id.user_input1);
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(user_input.getText().toString().trim().equals("")&&user_input1.getText().toString().trim().equals(""))
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
else{
//creating method for randomly choosing one of the user inputs
Random rand = new Random();
EditText[] userInputs = {user_input, user_input1};
int randomAnswer = rand.nextInt(userInputs.length);
result = userInputs[randomAnswer];
Log.v("EditText", result.getText().toString());
}}
});
}
private class getResult extends AsyncTask<String, String, TextView> {
#Override
protected TextView doInBackground(String... strings) {
return result;
}
}
}
Actually, I want to print the value in ResuRrect how to do that?
can you please explain me where exactly you want to print values??
So that I can help you.
If you want to print whatever inserted by user you can use textview to display it.
for that just add two textview in xml find it by id in java and on button click perform set text on it.
for example you have two textview
TextView tv1 = findViewById(R.id.tv1);
TextView tv2 = findViewById(R.id.tv2);
and button click will be as follows
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(user_input.getText().toString().trim()) &&
TextUtils.isEmpty(user_input1.getText().toString().trim())) {
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
} else {
//creating method for randomly choosing one of the user inputs
tv1.setText(user_input.getText().toString().trim());
tv2.setText(user_input1.getText().toString().trim());
Log.e("EditText1", user_input.getText().toString().trim());
Log.e("EditText2", user_input2.getText().toString().trim());
}
}
});
Your question isn't clear but if you want to display text to the user, it is better to use TextView.
for the set text of EditText or TextView, you should use setText method.
user_input.setText("hello")
So anyway I made it work. Now when user enters two values in EditText, program will randomly choose on of the inputs and print it in the TextView.
Here is the code:
public void onClick(View v) {
if(user_input.getText().toString().trim().equals("")&&user_input1.getText().toString().trim().equals(""))
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
else{
//creating method for randomly choosing one of the user inputs
Random rand = new Random();
String[] key = {user_input1.getText().toString().trim(), user_input.getText().toString().trim()};
int randomAnswer = rand.nextInt(key.length);
result.setText(key[randomAnswer].toString().trim());
}}
The Title is the best I could explain it. I am attempting to create a validation for a number box in Java, using android studio. However, the validation, when it should instead display the message "weight must be entered!", the program collapses upon itself. Any idea what could be wrong? Thanks in advance.
package com.example.student.project8a_medicalcalculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
import java.util.EmptyStackException;
public class MainActivity extends AppCompatActivity {
double weightEntered;
double convertedWeight;
final double conversionRate = 2.2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
final EditText weight = (EditText) findViewById(R.id.Weight);
final RadioButton lbToKilo = (RadioButton) findViewById(R.id.LbToKilo);
final RadioButton kiloToLB = (RadioButton) findViewById(R.id.KiloToLb);
final TextView result = (TextView) findViewById(R.id.Results);
Button convert = (Button) findViewById(R.id.bnConvert);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String weightV;
weightV = weight.getText().toString();
if (weightV.equals(" "))Toast.makeText(MainActivity.this, "Weight must be entered! ", Toast.LENGTH_LONG).show();
weightEntered = Double.parseDouble(weight.getText().toString());
DecimalFormat tenth = new DecimalFormat("#.#");
if (lbToKilo.isChecked()){
if (weightEntered <= 500){
convertedWeight = weightEntered / conversionRate;
result.setText(tenth.format(convertedWeight) + " kilograms");
} else {
Toast.makeText(MainActivity.this, "Pounds must be less than 500", Toast.LENGTH_LONG).show();
}
}
if (kiloToLB.isChecked()){
if (weightEntered <= 225){
convertedWeight = weightEntered * conversionRate;
result.setText(tenth.format(convertedWeight) + " pounds");}
else {
Toast.makeText(MainActivity.this, "Kilos must be less than 225 ", Toast.LENGTH_LONG).show();
}
}
}
});
}
}
Double.parseDouble() will raise NumberFormatException exception and make app crash when when you try to parse an empty string.
you checked the input string, but run Double.parseDouble() even it equals empty.
You could do as below:
if (!weightV.isEmpty()){
weightEntered = Double.parseDouble(weight.getText().toString());
......
}else{
Toast.makeText(MainActivity.this, "Weight must be entered! ", Toast.LENGTH_LONG).show();
......
}
You say: the validation, when it should instead display the message "weight must be entered!", /the program collapses upon itself
So you put a space " " in the EditText and expect to see the Toast.
You would see the Toast if you change the code:
if (weightV.trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Weight must be entered! ", Toast.LENGTH_LONG).show();
return;
}
But without return the code continues to execute and Double.parseDouble(weight.getText().toString()) throws an exception because an empty EditText's text is not a valid number.
Good Morning, I tried getting the toast to show if the number of students is less than 0, or greater than 100. The app seems to work fine, except showing the toast. This assignment is due tomorrow night.
Here is my code:
package co.tekitall.classroommanager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import static co.tekitall.classroommanager.R.id.NumOfStudents;
public class Classroom extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_classroom);
Button button = (Button) findViewById(R.id.SubmitClassRoomInfoButton);
}
void ClassroomElements() {
//ArrayList
ArrayList<EditText> arrayList = new ArrayList<>();
arrayList.add((EditText) findViewById(R.id.Teacher_Name));
arrayList.add((EditText) findViewById(R.id.Room_Number));
arrayList.add((EditText) findViewById(R.id.ClassroomHelper));
arrayList.add((EditText) findViewById(R.id.NumOfStudents));
}
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
EditText numofstudents = (EditText) findViewById(R.id.NumOfStudents);
String getstucount = numofstudents.getText().toString();
int setstucount = Integer.parseInt(getstucount);
if(setstucount < 0) {
numofstudents.setText("");
Toast toast = Toast.makeText(Classroom.this, "Please try Again! Number must be greater then 0 and less than 100...", Toast.LENGTH_LONG);
toast.show();
}
if(setstucount > 100) {
numofstudents.setText("");
Toast toast = Toast.makeText(Classroom.this, "Please try Again! Number must be greater then 0 and less than 100...", Toast.LENGTH_LONG);
toast.show();
} else
numofstudents.setText("");
Toast toast = Toast.makeText(Classroom.this, "Good Job",
Toast.LENGTH_LONG);
toast.show();
}
};
}
You need to bind button and listener using
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_classroom);
Button button = (Button) findViewById(R.id.SubmitClassRoomInfoButton);
button.setOnClickListener(listener);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
Plus use if and else-if instead of multiple ifs because a number can only be either less than 0 otherwise greater than 100 or between|equals 0 or 100
if(setstucount < 0){//...code}
else if(setstucount > 100){//...code}
else {//...code}
Looks like you have a Button and an OnClickListener but you're never connecting them together. For example:
button.setOnClickListener(listener);
So i have this code which solves the quadratic equation in java (android development) and it isnt doing anything!!!! The button when i press it does not give the answer at all... i cant even check if it is doing it correctly.
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class QuadraticEquationSolver extends Activity {
public void main(String[] args){
Button calc = (Button) findViewById(R.id.Calculate);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
EditText X2 = (EditText)findViewById(R.id.X2);
EditText X = (EditText)findViewById(R.id.X);
EditText Num = (EditText)findViewById(R.id.Num);
TextView ans= (TextView) findViewById(R.id.finalans);
double x2 = Integer.parseInt(X2.getText().toString());
double x = Integer.parseInt(X.getText().toString());
double num = Integer.parseInt(Num.getText().toString());
double finalNum = ((x*-1) + (Math.sqrt((x*x)-(4*x*num))))/(2*x2);
ans.setText("answer: " + finalNum);
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quadratic_equation_solver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_quadratic_equation_solver, menu);
return true;
}
First of all, welcome to Android development. I would highly recommend as a starting point you read the App Fundamentals and related guides on the SDK documentation site, as they will help you greatly in your new endeavour.
Android does not use a single entry point (i.e. main method) so your code will not be called. You will want to move all that code into onCreate().
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quadratic_equation_solver);
Button calc = (Button) findViewById(R.id.Calculate);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
EditText X2 = (EditText)findViewById(R.id.X2);
EditText X = (EditText)findViewById(R.id.X);
EditText Num = (EditText)findViewById(R.id.Num);
TextView ans= (TextView) findViewById(R.id.finalans);
double x2 = Integer.parseInt(X2.getText().toString());
double x = Integer.parseInt(X.getText().toString());
double num = Integer.parseInt(Num.getText().toString());
double finalNum = ((x*-1) + (Math.sqrt((x*x)-(4*x*num))))/(2*x2);
ans.setText("answer: " + finalNum);
}
});
}
I don't do any android programming, but I doubt Android will ever call your main method. The content of this main method must probably be in the onCreate method.
onCreate() is your main() equivalent in Android. Your main() function will never be called. The contents of main() should go in onCreate().
I have a MainClass which one is the full app, when I click one button I go to another class (PopupValores) which one I make it looks like a popup. In this class I have a EditText where you type a integer and a button to close this class. My question is how to get that int typed in PopupClass and use it in MainClass. Heres the code for the PopupValores.
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class PopupValores extends Activity implements OnClickListener {
TextView texto;
String mensaje;
EditText editable;
Button ok;
public static int cantidad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupvalores);
ok = (Button) findViewById (R.id.Bok);
texto = (TextView) findViewById (R.id.textView1);
editable = (EditText) findViewById (R.id.editText1);
mensaje = editable.getText().toString();
ok.setOnClickListener(this);
ok.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View arg0) {
finish();
return true;
}
});
}
public void onClick(View v){
switch(v.getId()){
case R.id.Bok:
String mensaje;
mensaje = editable.getText().toString();
cantidad = Integer.parseInt(mensaje);
texto.setText("New value " + cantidad + ".");
}
}
}
Then in my MainClass I click a button and it shows the int
int id, vaas = PopupValores.cantidad;
public void onClick (View v)
{
posicion = (ImageCell) v;
seleccion = posicion.mCellNumber;
if (seleccion == -1){
....
toast (id + " " + vaas);
....
}
}
But instead of showing the value declared in PopupValores it shows 0. What I'm doing wrong here?
You need to call the popup Activity with Activity.startActivityForResult()
Once finishing the popup Activity, set the requested result via Activity.setResult() (you can save your data in the intent's bundle)
In your main Activity, override onActivityResult and retrieve the data
Its called startActivityforResult
and has been answered soo many times here on stackoverflow Here is one