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;
}
Related
I am trying to convert a value that has been passed through from another fragment. The convert method is inside an onClickListener which when clicked will make the conversion of the value passed through the fragment.
The values are currently being placed into TextViews on my second fragment. However when I try to make an if statement it won't enter the loop
Text Name is what my textView has been set to.
The code is here
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (textName.equals("Miles") && textName2.equals("Kilometers")) {
String str1 = editText1.getText().toString();
double unittoConvert = Double.parseDouble(str1);
double convertedUnit = unittoConvert * 1.6;
String result = Double.toString(convertedUnit);
textName3.setText(result);
}
}
});
This is the code for the methods that are setting the unit selected in scroller and passing it through to the text view which is then displaying the selected unit. When i try to extract these values it wont work
PageViewModel.getName().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textName.setText(s);
}
});
PageViewModel2.getName2().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textName2.setText(s);
}
});
Use getText to extract text from TextView and then compare
textName.getText().equals("Miles") && textName2.getText().equals("Kilometers")
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());
I have an activity, called AddItem, which contains a couple fields that the user fills out and I am now trying to pass them to another activity. I was able to get the first two fields by doing this:
String messageText = ((EditText) findViewById(R.id.inputName)).getText().toString();
String discriptionText = ((EditText) findViewById(R.id.description)).getText().toString();
The above code worked fun, but then I tried to get another value which I then cast to a double like so:
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
It's kind of long and complicated but I'm basically doing the same thing with the exception of parsing the String and converting it to a double value. I determined that this is the problem code because when I comment it out the rest of the app runs fine.
Here is my Activity:
public class AddItem extends AppCompatActivity {
EditText inputedTask, inputedDescription, inputedLatitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
inputedTask = (EditText) findViewById(R.id.inputName);
inputedDescription = (EditText) findViewById(R.id.description);
inputedLatitude = (EditText) findViewById(R.id.Latitude);
}
public void onSaveItemButton(View view) {
String messageText = ((EditText) findViewById(R.id.inputName)).getText().toString();
String discriptionText = ((EditText) findViewById(R.id.description)).getText().toString();
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
if (messageText.equals(""));
else {
Intent intent = new Intent();
intent.putExtra(Intent_Constant.INTENT_MESSAGE_FIELD, messageText);
setResult(Intent_Constant.INTENT_RESULT_CODE, intent);
finish();
}
}
}
You need to make a public method for the onClick, from the documentation:
Within the Activity that hosts this layout, the following method
handles the click event:
/** Called when the user touches the button */
public void sendMessage(View view) {
// Do something in response to button click
}
The method you declare in the android:onClick attribute must have a
signature exactly as shown above. Specifically, the method must:
Be public
Return void
Define a View as its only parameter (this will
be the View that was clicked)
So you need to change the method to public:
public void onSaveItemButton(View view) {
...
}
UPDATE:
As the error log says:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at cs4720.cs.virginia.edu.duysalahandroidminiproject02.AddItem.onSaveItemButton(AddItem.java:33)
You need to catch for empty string in the following code:
double Latitude = Double.parseDouble(((EditText) findViewById(R.id.Latitude)).getText().toString());
so, check it first:
String val = ((EditText) findViewById(R.id.Latitude)).getText().toString();
if(!val.equals("") {
double Latitude = Double.parseDouble(val);
}
You are calling onSaveItemButton method from a view that is not initialized. You must initialize btnChangeDate in the onCreate from the activity.
Check this answer
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))
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.