I'm making a simple very simple android math game. But I cant manage to compare two TextViews to let the user know if they calculated correct or not???
Im not comparing them correctly as my if/else statement is only giving me the else output??
public class PlayActivity extends AppCompatActivity {
EditText number1;
EditText number2;
TextView result;
Button addNumbers;
TextView equalW;
TextView equalL;
TextView generate;
double num1,num2,sum;
Random r = new Random();
public View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
generate = (TextView)findViewById(R.id.textViewGenerate);
int generated = r.nextInt(101);
generate.setText(Integer.toString(generated));
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
number1 = (EditText)findViewById(R.id.editTextNumber1);
number2 = (EditText)findViewById(R.id.editTextNumber2);
result = (TextView)findViewById(R.id.textViewSum);
addNumbers = (Button)findViewById(R.id.buttonAdd);
equalL = (TextView)findViewById(R.id.textViewLose);
equalW = (TextView)findViewById(R.id.textViewWin);
Button buttonGenerate = (Button)findViewById(R.id.buttonGenerate);
buttonGenerate.setOnClickListener(listener);
addNumbers.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
num1 = Double.parseDouble(number1.getText().toString());
num2 = Double.parseDouble(number2.getText().toString());
sum = num1 + num2;
result.setText(Double.toString(sum));
if (generate.getText().toString().equals(result))
{
equalW.setText("Answer is correct");
}
else {
equalL.setText("lose");
}
}
});
}
You have one obvious problem and another lurking problem.
The obvious one: You have to compare a String with a String and not with a TextView. Hence replace if (generate.getText().toString().equals(result)) with if (generate.getText().toString().equals(result.getText().toString())).
The lurking one: If you see closely, sum is set as String in result and generated is set as String in generate. sum is of data type double and generate is of data type int. Comparing both will cause problem. This is like comparing "10".equals("10.0"). This is error prone. You need to set both these fields to a common data type.
Change if condition as:
if (generate.getText().toString().equals(result.getText().toString()))
{
}
Because result is view so call getText method for comparing String values.
result is textview so you have to write
if (generate.getText().toString().equals(result.getText().toString))
Related
I have a problem with my simple android app. When I launch it, the questions seems to be a step ahead of the answers I enter as input. For example If the question was to be 3x3 = ?, It will only accept the correct answer for the next question. So any answer I give in the current question will always be wrong. I tested this by continuously entering the same same answer.
Any pointers would be much appreciated. I hope this make sense!
public class MainActivity extends AppCompatActivity {
int value3;
int answer;
EditText answer_field;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView leftNumber = findViewById(R.id.left_number);
final ImageView rightNumber = findViewById(R.id.right_number);
Button myButton = findViewById(R.id.answer_button);
final int[] numberArray = new int[]{
R.drawable.number_0,
R.drawable.number1,
R.drawable.number2,
R.drawable.number3,
R.drawable.number4,
R.drawable.number5,
R.drawable.number6,
R.drawable.number7,
R.drawable.number8,
R.drawable.number9,
};
leftNumber.setImageResource(numberArray[0]);
rightNumber.setImageResource(numberArray[0]);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create a random number generator
Random randomNumberGenerator = new Random();
int value1 = randomNumberGenerator.nextInt(10);
leftNumber.setImageResource(numberArray[value1]);
// Create a new random number
int value2 = randomNumberGenerator.nextInt(10);
// Set the right dice image using an image from the diceArray.
rightNumber.setImageResource(numberArray[value2]);
answer_field = findViewById(R.id.answer_field);
answer = valueOf(answer_field.getText().toString());
value3 = value1 * value2;
if(value3 == answer) {
showToast("Correct");
}
}
});
}
public void showToast(String text){
Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();
}
}
Thank you!
You are generating the values at the onClick of your answer button wich means that the values to multiply will be set (or reset) randomly every time the user hit the answer button; put the logic to generate the values outside the onclick, so when the user clicks on it only the comparison will be made, somewhat like this:
[...]
leftNumber.setImageResource(numberArray[0]);
rightNumber.setImageResource(numberArray[0]);
// Create a random number generator
Random randomNumberGenerator = new Random();
int value1 = randomNumberGenerator.nextInt(10);
leftNumber.setImageResource(numberArray[value1]);
// Create a new random number
int value2 = randomNumberGenerator.nextInt(10);
// Set the right dice image using an image from the diceArray.
rightNumber.setImageResource(numberArray[value2]);
answer_field = findViewById(R.id.answer_field);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
answer = valueOf(answer_field.getText().toString());
value3 = value1 * value2;
if(value3 == answer) {
showToast("Correct");
}
}
});
[...]
I'm writing a calculator on Android Studio, in Java, and the app crashes if the user call the result with a dot "." alone or let the EditText field in blank.
I'm looking for a solution for not allowing these two conditions happening, together or individualy, in each of the three fields.
I've already tried TextWatcher and if/else but without success.
The .xml file where the editText field are designed is already set for decimalNumber.
I've already tried this:
if(myfieldhere.getText().toString().equals(".")){myfieldhere.setText("0");}
For each "valor line" and else for the "finalresult" line if everything is fine. Both inside the setOnClickListener block. This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.peso_layout);
result = findViewById(R.id.layresult);
conc = findViewById(R.id.layconc);
dose = findViewById(R.id.laydose);
peso = findViewById(R.id.laypeso);
calc = findViewById(R.id.laycalcpeso);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
});
}
The ideal output should be the app not crashing if these two conditions happen and sending an error message to the user that input is invalid.
What i'm receiving is the app crashing.
Thank you very much. I'm very beginner in Java and I'm few days struggling with this.
Dear Friend, Your directly trying to convert string input into float and then after your check value but do your code like Below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText edt1,edt2;
TextView txtans;
Button btnsum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt1=findViewById(R.id.edt1);
edt2=findViewById(R.id.edt2);
txtans=findViewById(R.id.txtans);
btnsum=findViewById(R.id.btnsum);
btnsum.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.btnsum){
float n1,n2;
String value1=edt1.getText().toString();
String value2=edt2.getText().toString();
if(value1.equals("") || value1.equals(".")){
n1=0;
}else {
n1= Float.parseFloat(value1);
}
if(value2.equals("")|| value2.equals(".")){
n2=0;
}else{
n2= Float.parseFloat(value2);
}
float ans=n1+n2;
txtans.setText(ans+"");
}
}
}
See In above code, First get value from edittext and then check wheather it contain null or "." inside it. if it contains then store 0.0 value in some variable. then after make sum and display in textbox.
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String myvalor = myfieldhere.getText().toString();
if(myvalor.equals(".") || myvalor.isEmpty())
{
// toast error : incorrect value
return;
}
try
{
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
catch(Exception exp){// toast with exp.toString() as message}
}
});
use TextUtils for check empty String its better
if(TextUtils.isEmpty(peso.getText().toString())||
TextUtils.isEmpty(conc.getText().toString())||
TextUtils.isEmpty(dose.getText().toString())){
return;
}
I am working through a Udemy course and we're building a basic "Higher or Lower" app. My app essentially works, however the random number it chooses for us to guess is always the same no matter how many times I destroy and relaunch the activity.
My MainActivity.java:
//mad import statements here
public class MainActivity extends AppCompatActivity {
int correctNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int correctNumber = generateNum();
}
protected int generateNum(){
Random rand = new Random();
int randNum = rand.nextInt(100);
return randNum;
}
protected void numberEval(View view) {
EditText enteredNumber = (EditText) findViewById(R.id.numberEntry);
String numberString = enteredNumber.getText().toString();
Button pressMe = (Button) findViewById(R.id.button);
int numToEval = Integer.parseInt(numberString);
String result;
TextView showWinLose = (TextView) findViewById(R.id.winLoseText);
if (numToEval > correctNumber) {
result = "Too high!";
} else if (numToEval < correctNumber) {
result = "Too Low!";
}else {
result = "You guessed it!";
}
showWinLose.setText(result);
}
}
Super super basic, yes? Originally, my numberEval() method called generateNum(), but then I realized it was generating a new number to guess every time I pressed the button. So I set it the way it was here, where onCreate() generates correctNumber only once and correctNumber is now a class variable. Now it doesn't generate a new number every button click, but it won't seem to generate a new number at all. It's stuck at 0 no matter how any times I launch, close, relaunch, etc. the app.
How can I fix this? Thanks in advance.
public class MainActivity extends AppCompatActivity {
int correctNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int correctNumber = generateNum();
}
// ...
}
The last line in onCreate() declares a local variable named correctNumber. This hides the class field with the same name and is only available inside onCreate(). To fix the problem, remove int from this line so that you use the class field instead.
I am building an android application where I am creating dynamic EdittextView. I need to display the sum of integer enter in it by the user. Below is my code to create Dynamic EdittextView:
for (int i = 1; i < ZipRunApplication.ConfigLeg; i++){
LayoutInflater inflater = null;
inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView = inflater.inflate(R.layout.drop_money, null);
TextView droxTextView = (TextView) mLinearView.findViewById(R.id.dropTextView);
final TextView position = (TextView) mLinearView.findViewById(R.id.position);
final TextView Amount = (TextView) mLinearView.findViewById(R.id.Amount);
final EditText dropEditTextView = (EditText) mLinearView.findViewById(R.id.dropEditext);
dropEditTextView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
Amount.setText(dropEditTextView.getText().toString()); //
}
});
droxTextView.setText("Amount to be pick From Drop " + String.valueOf(i));
position.setText(String.valueOf(i));
droxTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
container.addView(mLinearView);
}
Could any one help me getting the sum of the all the EdittextView created Dynamicly.
Answer for:
Could any one help me getting the sum of the all the EdittextView
created Dynamically.
You can maintain an ArrayList of EditText and then can iterate through them and get the text entered in each of them and find the sum.
As an example I have the following snippet:
LinearLayout layout;
List<EditText> concernedEditTexts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout)findViewById(R.id.base_layout); // Base layout defined in xml
concernedEditTexts = new ArrayList<EditText>();
// Creating five EditTexts
for(int i= 0; i< 5; i++){
EditText text = new EditText(getApplicationContext());
layout.addView(text);
concernedEditTexts.add(text); // Adding dynamically created EditText in the ArrayList
}
Button button = new Button(getApplicationContext());
button.setText("Get Sum");
layout.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int sum = 0;
// Iterate through the List and find the sum
for(EditText editText : concernedEditTexts){
sum+= Integer.parseInt(editText.getText().toString());
}
Log.d("SUM","Sum is "+sum);
}
});
}
Note: This code is kind of raw and needs a lot more validations, but should be enough to explain the concept.
In your example you will need to store every dropEditTextView in the List and then iterate through the list as shown in my example will give you the desired result.
you can use
Integer.parseInt(dropEditTextView.getText().toString())
setTag() to each EditText as i variable and take an arrarylist of size ZipRunApplication. when you write in edittext then in textchnage listener get tag value and convert to int. This value will tell you for which position in arraylist you are writing . then in that position of arraylist set Integer.parseInt(editTextString).
Four tips:
1 - Here we get the childs by the parent:
for (int i = 0; i < mLinearLayout.getChildCount(); i++) {
if (mLinearLayout.getChildAt(i) instanceof LinearLayout) {
LinearLayout ll = (LinearLayout) mLinearLayout.getChildAt(i);
for (int j = 0; j < ll.getChildCount(); j++) {
if (ll.getChildAt(j) instanceof EditText) {
ll.getChildAt(j).setOnFocusChangeListener(this);
}
}
}
}
2 - Don't forget to parse the data you try to receive:
Integer.parseInt(mFocusedEditText.getText().toString());
3 - note:
view.setTag() <-> View.getTag()
4 - And last but not least: In terms of readability, maintainability and performance you will get to a point soon, where a ListView- or RecyclerView will fit your needs MUCH better (so keep in mind: the above coding isn't a proper solution, even if it works).
ListView and
RecyclerView
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to nicely format floating types to String?
How can I list the number with up to two decimal places? I tried this method: http://developer.android.com/reference/java/text/NumberFormat.html but no luck. Below code. Maybe someone can help me.
package karcio.fuel.economy;
public class FuelEconomy extends Activity
{
private EditText editText1;
private EditText editText2;
private TextView textView4;
private TextView textView6;
private Button button1;
private double miles;
private double liters;
private double result;
private double convertMilesToKm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initParams();
}
private void initParams()
{
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.editText2);
textView4 = (TextView)findViewById(R.id.textView4);
textView6 = (TextView)findViewById(R.id.textView6);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new Button.OnClickListener()
{
public void onClick (View v)
{
calculate();
}
});
}
private void calculate()
{
miles = Double.parseDouble(editText1.getText().toString());
liters = Double.parseDouble(editText2.getText().toString());
convertMilesToKm = miles * 1.61;
result = 100 * liters / convertMilesToKm;
textView6.setText(Double.toString(convertMilesToKm));
textView4.setText(Double.toString(result));
}
}
You can do something like this:
String str = String.format("%.2f", 3.99999);
textView.setText(str);
Well you can try to manually do it.
//This is just an example
double number = result; //result is YOUR variable (ex. result = 23.1231231241920312)
int tmp = number * 100; //2312.31231241920312
number = (double)tmp / 100; //23.12
Hope this helps.
Note: You can skip the step where i declare an INT if you do it on the other line.
Update: The advantage of using this method is that you do not need to create an Object which is faster, but of course there are many ways.