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

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.

Related

What data type is

i've created a function and set it to onClick, so every time i hit the button this function is called. It is called, but the value of 4 other functions i can't get them in setMessage() function(when we create a dialog box). So the logic is like, after hitting the button first we check which radioId1 is equal to which id, and call the appropriate fucntion(video,cons,news,pict).These 4 funct. return some string. Then i want to add these strings to some text in my dialog box, like ....SetMessage(checkMyId() + "Some text").SetPositiveButton(...)...
but the problem is my function checkMyId is set to onClick, so it recieves an argument View v, and when i call it "mannualy" in SetMessage() it shows error, because i don't know what to put inside that parenthesis. So the question is, what type of data(or whatever) is that View ? i saw some documentation and didn't understood much or at least how to implement that in my problem.
public void checkMyId(View v) {
int radioId1 = radioGroup.getCheckedRadioButtonId();
if (radioId1 == R.id.radio_one) {
video();
} else if (radioId1 == R.id.radio_two) {
pict();
} else if (radioId1 == R.id.radio_three) {
cons();
} else news();
}
EDITED
Picture of the error
sir you have 2 way
first try this ( HINT : Don't forget to implement ONCLICK in activity )
public void checkMyId(View v) {
switch (v.getId()) {
case R.id.radio_one:
video();
break;
case R.id.radio_two:
pict();
break;
case R.id.radio_three:
cons();
break;
default:
news();
break;
}
}
sec you can use it in OnCreate ( HINT : this on radio group ) HERE
(findViewById(R.id.radio_one)).setOnCheckedChangeListener(new
OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
}
});
____ READ This also for single RB

Edit text parsing integer android

I am making android app and I have edit text surrounded by two buttons for increase and decrease
and when I click the button increase or decrease for the first time it did not work but it start working from the second time
e.g if the number in edit text field is 50 when I press increase it still 50 when I press increase again it change to 51 and again it change to 52 and so on
here is my java code for the two buttons
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (quantityEdit.getText().toString().equals("") || quantityEdit.getText().toString() == null) {
quantityEdit.setText("0");
} else {
int a = Integer.parseInt(quantityEdit.getText().toString());
int b = a + 1;
quantityEdit.setText(String.valueOf(b));
}
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int a = Integer.parseInt(quantityEdit.getText().toString());
if (a >= 1) {
int b = a - 1;
quantityEdit.setText(String.valueOf(b));
} else {
quantityEdit.setText("0");
}
}
});
It looks like you are checking for empty string or null in "add", but not in "sub". As Michael Krause said, you should use TextUtils.isEmpty(), and set a default value before performing add or sub operations.
If you are setting a default value elsewhere, please show your code.
Consider refactoring your code like so
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quantityEdit.setText(String.valueOf(getIntVal(quantityEdit) + 1));
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int value = getIntVal(quantityEdit);
if (value > 0) {
value--;
}
quantityEdit.setText(String.valueOf(value));
}
});
// helper method to get the integer value of a TextView
private int getIntVal(TextView textView) {
CharSequence rawValue = textView.getText();
int value;
if (!TextUtils.isEmpty(rawValue)) {
try {
value = Integer.parseInt(rawValue.toString());
} catch (NumberFormatException e) {
value = 0;
// TODO log / notify user
}
} else {
value = 0;
}
}
This way your initialization is handled in one place and it's more clear.
In any event, your first condition is wrong. You do a null check after trying to access the object (it's backwards). Have you checked your logs? This could throw an exception for a null value and "lose" the first click.

how to take default value of an edittext as 0?

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)

Textwatchers afterTextChanged() keeps crashing

I've figured out that afterTextChanged() is called the everytime the EditText text changes (and thats why it crashes) but I don't know how to solve the problem. Can anyone please help me!
setting the edit text and adding addTextChangedListener
editText= (EditText) findViewById(R.id.editText);
editText.setInputType(InputType.TYPE_NULL);
editText.addTextChangedListener(textWatcher);
textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//editText.removeTextChangedListener(textWatcher); //this doesn't help
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
// Toast.makeText(mainAct, "OK",Toast.LENGTH_SHORT).show();
String user_answer =editText.getText().toString();
user_ans_int = Integer.parseInt(user_answer);
This should check if the text in the EditText is correct and this is also where the app crashes (without this part it runs perfectly)
if (user_ans_int == answer){
Toast.makeText(mainAct, "True", Toast.LENGTH_SHORT).show();
editText.setText("");
}
else {
Toast.makeText(mainAct, "Naaw - try again haha", Toast.LENGTH_SHORT).show();
editText.setText("");//delete text after checking
tru = false;
}
}
};
}
You will get a NumberFormatException here: user_ans_int = Integer.parseInt(user_answer); It's because you sign a None Number value to your editText and cause its afterTextChanged() being called.
I think you can change your code as following:
user_ans_int = Integer.parseInt(user_answer);
to:
try{
user_ans_int = Integer.parseInt(user_answer);
}catch(NumberFormatException e){
// A none number value is signed to your edittext, do something here.
return;
}
You need to disable the TextWatcher when you update the text in the if..else statement where you check for the correct answer. What you do right now is that you check if the answer is correct and then set the text back to "". That triggers again the text watcher because the text has changed. Then you try to parse to int an empty string. So change your if..else to this:
if (user_ans_int == answer){
editText.removeTextChangedListener(textWatcher);
Toast.makeText(mainAct, "True", Toast.LENGTH_SHORT).show();
editText.setText("");
editText.addTextChangedListener(textWatcher);
} else {
editText.removeTextChangedListener(textWatcher);
Toast.makeText(mainAct, "Naaw - try again haha", Toast.LENGTH_SHORT).show();
editText.setText("");//delete text after checking
tru = false;
editText.addTextChangedListener(textWatcher);
}
Practically, you could also place a try..catch statement where you parse the content of the editText to an int to catch the exception but in this case you will call the textWatcher without needing to do so. I believe that disabling and re-enabling the textWatcher is much more efficient.
// Write down few code inside a afterTextChanged method
if(!s.equal("")){
try {
String user_answer = s.getText().toString();
user_ans_int = Integer.parseInt(user_answer);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}else{
Toast.makeText(mainAct, "Please Enter Text",Toast.LENGTH_SHORT).show();
}

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.

Categories

Resources