how to take default value of an edittext as 0? - java

I am trying to make a simple android app in which 2 text fields are there.input range is 0 to 15. If the number is in range than addition is performed.
i have implemented input varification so now if the edit text is empty it shows empty field warning. but calculation is not done. what i want is if the field is empty is should show the error but also do the addition by take default value as 0.
here is my code
public class MainActivity extends AppCompatActivity {
private EditText check,check2;
private TextView textView;
private TextInputLayout checkLay,checkLay2;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeWidgets();
initializeListeners();
}
private void initializeWidgets(){
check=findViewById(R.id.check);
check2=findViewById(R.id.check2);
checkLay2=findViewById(R.id.checkLay2);
checkLay=findViewById(R.id.checkLay);
button=findViewById(R.id.button);
textView=findViewById(R.id.textView);
}
private void initializeListeners() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signUp();
}
});
}
private void signUp(){
boolean isVailed=true;
int a1,a2;
String one=check.getText().toString();
String two=check2.getText().toString();
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
isVailed=false;
}
else {
if (one.length() > 0)
{
a1=Integer.parseInt(one);
if(a1> 15){
checkLay.setError("quiz marks must be less than 15");
isVailed=false;
}
else if(a1 <=15)
{
checkLay.setErrorEnabled(false);
isVailed=true;
}
}
}
if(two.isEmpty()){
checkLay2.setError("You need to enter something");
isVailed=false;
}
else{
if (two.length() > 0)
{
a2=Integer.parseInt(two);
if(a2 > 15)
{ checkLay2.setError("quiz marks must be less than 15");
isVailed=false;
}
else
if(a2 <=15)
{
checkLay2.setErrorEnabled(false);
isVailed=true;
}
}
if(isVailed)
{
int total;
a1=Integer.parseInt(one);
a2=Integer.parseInt(two);
total=a1+a2;
textView.setText(String.valueOf(total));
}
}

I would do it differently but for your specific question
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
isVailed=false;
}
Change to
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
a1=0;
}
Same for the two.isEmpty()

If a field is empty you set isVailed to false and thus say not to add the numbers. Instead you want to set the corresponding number to zero and let isVailed be true:
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
a1 = 0;
}
and
if(two.isEmpty()){
checkLay2.setError("You need to enter something");
a2 = 0;
}
Also throw off the lines
a1=Integer.parseInt(one);
a2=Integer.parseInt(two);
You already convert inputs to a1 and a2 earlier.
A piece of advice: you have doubled code. It's better to use functions for such pieces of codes.

add this line in your initializeWidgets function
yourEditText.setText(0);
follow link for more help: duplicate

You can create a convenience method to get value from your edittext. The following code will return 0 if edittext is empty else the value from the edittext
private int getIntFromEditText(EditText editText) {
return editText.getText().length()>0 ? Integer.parseInt(editText.getText().toString()):0;
}
Call it by passing EditText as a parameter, e-g
a1=getIntFromEditText(check)

Related

How to validate decimal input not allowing alone "." and empty field?

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

Dot in calculator android studio

I have been trying to build a simple calculator in android studio. Everything is fine but i have a problem, when i run the calculator and i press the dot button, it shows in the textview "." instead "0."
Also, i need to check the existence of two decimal points in a single numeric value.
here is an image:
it shows "."
and i want:
how can i change this??, here is my code:
private int cont=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display=(TextView)findViewById(R.id.display);
text="";
}
public void numero1(View view){ /*when i press a number, this method executes*/
Button button = (Button) view;
text += button.getText().toString();
display.setText(text);
}
public void dot(View view){ /*This is not finished*/
display.setText{"0."}
}
I was thinking in creating another method for the dot button, but the content of the text value disappears when i press another button, how to fix this?
try this
public void numero1(View view){ /*when i press a number, this method executes*/
Button button = (Button) view;
text += button.getText().toString();
if(text.substring(0,1).equals("."))
text="0"+text;
display.setText(text);
}
try this way
public void dot(View view){ /*This is not finished*/
String str=display.getText().toString().trim();
if(str.length()>0){
display.seText(str+".")
}else{
display.setText("0.")
}
}
Use a string builder and append all the text entered to already existing string. Before display, just use the toString() method on the string builder.
Create a class that represents your character sequence to be displayed and process the incoming characters.
For example:
class Display {
boolean hasPoint = false;
StringBuilder mSequence;
public Display() {
mSequence = new StringBuilder();
mSequence.append('0');
}
public void add(char pChar) {
// avoiding multiple floating points
if(pChar == '.'){
if(hasPoint){
return;
}else {
hasPoint = true;
}
}
// avoiding multiple starting zeros
if(!hasPoint && mSequence.charAt(0) == '0' && pChar == '0'){
return;
}
// adding character to the sequence
mSequence.append(pChar);
}
// Return the sequence as a string
// Integer numbers get trailing dot
public String toShow(){
if(!hasPoint)
return mSequence.toString() + ".";
else
return mSequence.toString();
}
}
Set such a click listener to your numeric and "point/dot" buttons:
class ClickListener implements View.OnClickListener{
#Override
public void onClick(View view) {
// getting char by name of a button
char aChar = ((Button) view).getText().charAt(0);
// trying to add the char
mDisplay.add(aChar);
// displaying the result in the TextView
tvDisplay.setText(mDisplay.toShow());
}
}
Initialize the display in onCreate() of your activity:
mDisplay = new Display();
tvDisplay.setText(mDisplay.toShow());

Compare the result of two TextViews Java/Android

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

Can't get my if statement to work?

I know this has got to be simple. But for the life of me i don't know why i can't get this right.
Ok so I want to go from a listview page (got that) then click a switch to make it go to the next page (also got that.) Then I want a int to tell me which position I am on form the last page (might be working?) now i can't get the If Else statement to work in the page.
public class NightmareParts extends Activity
{
public int current_AN_Number = NightmareList.AN_position_num;
private TextView edit_title;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.part_layout);
// isn't working here. Why?
// test_edit = (TextView)findViewById(R.id.directions_tv);
// test_edit.setText(R.string.directions_text_two);
// works without this being in here.
setDoneButtonListener();
}
//Set up the Done button to initialize intent and finish
private void setDoneButtonListener()
{
Button doneButton = (Button) findViewById(R.id.back_button);
doneButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v)
{
finish();
}
});
}
private void editTitle()
{
if (current_AN_Number = 1)
{
edit_title = (TextView)findViewById(R.id.part_title);
edit_title.setText(R.string.AN_title_1);
}
}
}
The current_AN_number is coming from the last page.
Your if statement is incorrect:
if (current_AN_Number = 1)
You've used the assignment operator, when you wanted to compare it with the == operator:
if (current_AN_Number == 1)
if (current_AN_Number = 1)
Should be
if (current_AN_Number == 1)
You're not setting current_AN_Number to be 1, you are comparing if it is equal to 1. So use ==.
test_edit = (TextView)findViewById(R.id.directions_tv);
is not working because test_edit is never declared.

Why cant i get these calculations to display on a textview?

Im trying to make an app that converts distance/area/volume using spinners as a unit selection method. Calculations are meant be done and then the output sent to a textview based on what is entered into the EditText. But the output is only ever 0.0 and nothing else. Can anybody help with this ?
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
switch(pos){
case 0:
option1.setAdapter(length);
option2.setAdapter(length);
return;
case 1:
option1.setAdapter(area);
option2.setAdapter(area);
return;
default:
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
option1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(pos>=0) {
stringInput = edittext1.getText().toString();
if(stringInput == null || stringInput.isEmpty()) {
doubleInput = 0.0;
}
else {
doubleInput = Double.parseDouble(edittext1.getText().toString());
}
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
option2.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
switch(pos) {
case 0:
miles = doubleInput * 1;
textview1.setText("" + String.valueOf(miles));
return;
case 1:
km = doubleInput * 1.609344;
textview1.setText("" + String.valueOf(km));
return;
default:
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
});
At the risk of sounding like a really old man, this looks like your college homework... Is it?
Your code has changed since asking the question, which makes it pretty difficult to answer! Luckily I managed to scrape your code into Eclipse before you changed it... Anyway, in your original code your performing all your operations in the create method, at which point you haven't entered a value for edittext1 (unless it's set to some sensible default, which I presume would be 0, hence always getting zero as your answer?)
// Whilst setting up a view the create method will not have a
// reasonable value for edittext1 - or it will be your default
String stringInput = (edittext1.getText().toString());
if (stringInput.isEmpty()) {
doubleInput = 0.0; // Will always enter this line
} else {
doubleInput = Double.parseDouble(edittext1.getText().toString());
}
You've duplicated the code...
output1 = (TextView) findViewById(R.id.output1);
Actually output1 through to output10 (ie all ten lines) are duplicated.
As to your updated code, is it still giving you a problem? Are you sure that stringInput has a value? I mean have you typed something in? You could check by debugging your program..
The following is also error prone as FloatingCoder suggests, and is likely to break...
doubleInput = Double.parseDouble(edittext1.getText().toString());
A better way to do this (because it catches the exception that Java might throw) is
doubleInput = 0.0;
String inputStr = question.getText().toString();
try {
doubleInput = Double.parseDouble(inputStr);
} catch (NumberFormatException e) {
// This should probably do something more useful? i.e. tell
// the user what they've done wrong...
Log.e("Android",
"Double throws a NumberFormatException if you enter text that is not a number");
}
Oh and Android has some helper utilities for checking strings, see TextUtils, or just my example...
if (!TextUtils.isEmpty(inputStr)) { // checks for "" and null (see documentation)
doubleInput = Double.parseDouble(inputStr);
}
I'd REALLY recommend writing a simple test case for a calculation that looks incorrect, because two text boxes and a button really aren't hard to throw together and are seriously easy to debug without the need for all the spinners getting in the way... Anyway hope this helped, oh and my complete example with two edittexts and a button, I'll just post that here... Hope it helps...
private Button btnCalc;
private EditText question, answer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
answer = (EditText) findViewById(R.id.answer);
question = (EditText) findViewById(R.id.question);
btnCalc = (Button) findViewById(R.id.btnCalc);
// The OnClickListener here will be executed outside the "Create",
// i.e., when you actually click on the button, which will give you
// a chance to enter some values in the question edittext...
btnCalc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
double in = 0.0;
try {
String inputStr = question.getText().toString();
// if you want to check it use
if (!TextUtils.isEmpty(inputStr)) {
in = Double.parseDouble(inputStr);
}
} catch (NumberFormatException e) {
// This should probably do something more useful? i.e. tell
// the user what they've done wrong...
Log.e("Android",
"Double throws a NumberFormatException if you enter text that is not a number");
}
double miles = in * 1.6;
answer.setText(String.valueOf(miles));
}
});
}
It's a little hard to tell from the code you posted, but my guess is that you are setting doubleInput when option 1 is selected. If you are entering the number after you select option 1, it will always be 0.0, as the number was not in the text area when the spinner was changed.
Use a debugger to step through the code and see if you are ever reaching the line
doubleInput = Double.parseDouble(edittext1.getText().toString());
and to check that the number is getting set properly at that point.

Categories

Resources