why editText make program stopped if didn't input anything - android

I new. I have 2 editText and 1 TextView, 1 button. I want to sum from 2 input. Its success if I input all editText. But if I didn't input, the aplication stopped.
package panda.c;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class calculate extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText input1,input2;
Button sum;
TextView total;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calcu);
input1 = (EditText) findViewById(R.id.input1);
input2 = (EditText) findViewById(R.id.input2);
total = (EditText) findViewById(R.id.total);
sum = (Button) findViewById(R.id.sum);
sum.setOnClickListener(this);
}
public void onClick(View v) {
int inputt1 = Integer.parseInt(input1.getText().toString());
int inputt2 = Integer.parseInt(input2.getText().toString());
switch (v.getId()) {
case R.id.sum:
sum.setText(Integer.toString(inputt1+inputt2));
break;
default:
break;
}}}
I didn't input anything. I just clicked sum, and then the program stopped. But if I input all editText, I clicked sum, Its work. why? I want if I do not input, and click sum, the application still run.

It's because if a field is left blank, Integer.parseInt() will fail. You should set a default value of 0 if the field is left blank so it won't force close.
Here's a simple solution to check if it's empty and use 0 as default:
int inputt1 = input1.getText().toString().equals("") ? 0 : Integer.parseInt(input1.getText().toString());
int inputt2 = input2.getText().toString().equals("") ? 0 : Integer.parseInt(input2.getText().toString());
Also, set android:inputType="number" to your EditText so you it will restrict input to numbers only.
Edit: Updated code to make it compatible to all API levels.

It's called a NullPointerException. You're trying to parse null to integer. You need to enclose the parsing statements in a try block and catch the NullPointerException and set some default value to inputt1 and inputt2 or notify the user to put some value with a Toast.
Correction
It's not a NullPointerException it's a NumberFormatException.

This is because you are using Integer.parseInt() and parsing "" inside it. This will definetly give you NumberFormat Exception.
Try this...
if(!(input1.getText().toString().trim().equals(""))){
inputt1 = Integer.parseInt(input1.getText().toString());
}
same for the other input as well..
Hope this helps,..

The code fragment in you OnClick() method could be the following:
int inputt1 = 0;
int inputt2 = 0;
try {
inputt1 = Integer.parseInt(input1.getText().toString());
inputt2 = Integer.parseInt(input2.getText().toString());
}
catch (NumberFormatException e) {
//notify the user here somehow or just leave empty
//or just return, if you don't want to sum default values
}

Related

EditText crashing simple calculator

I'm trying to build basic calculator, but when I put a number at first edittext and hit add button, it gets crashed.
It is fine when I add two number in both editTexts. There was no problem in that. But the problem happened when I put only one number and hit add.
It is throwing NumberFormatException: Invalid int: "".
here is my basic code.
public class MainActivity extends AppCompatActivity {
EditText num1;
EditText num2;
Button add,sub,multi,div;
TextView MyResults;
String Number1 ;//;
String Number2 ;//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText)findViewById(R.id.num1);
num2 = (EditText)findViewById(R.id.num2);
add = (Button)findViewById(R.id.Add);
sub = (Button)findViewById(R.id.Sub);
multi = (Button)findViewById(R.id.Multiple);
div = (Button)findViewById(R.id.Divide);
MyResults = (TextView)findViewById(R.id.results);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Number1 =num1.getText().toString();
Number2 =num2.getText().toString();
int mAdd1 = Integer.valueOf(Number1);
int mAdd2 = Integer.valueOf(Number2);
int myAdd = mAdd1+mAdd2;
MyResults.setText(String.valueOf(myAdd));
Toast.makeText(getApplicationContext(), "Added: "+ myAdd, Toast.LENGTH_LONG).show();
}
});
}//end OnCreate.
When you leave an EditText empty
int mAdd2 = Integer.valueOf(Number2);
Will crash because a empty String is not a valid Integer (hence the NumberFormatException).
You could put it in a try/catch like this:
try {
Number1 =num1.getText().toString();
Number2 =num2.getText().toString();
int mAdd1 = Integer.valueOf(Number1);
int mAdd2 = Integer.valueOf(Number2);
MyResults.setText(String.valueOf(myAdd));
Toast.makeText(getApplicationContext(), "Added: "+ myAdd, Toast.LENGTH_LONG).show();
catch (NumberFormatException e) {
//Give a toast saying the user did not enter two correct values
}
Or alternatively, check the value beforehand and check if nothing was entered:
number1 =num1.getText().toString();
number2 =num2.getText().toString();
if (number1.equals("") || number2.equals("")) {
//Show error or set numbers to a different value
}
However, for this to work you must assume the user did not enter anything that isn't a valid Integer like a letter, for example by setting the EditText's input type to numbers.
android:inputType="number"
You should do validation checking for a blank edit text and not do the calculation in this case.
Instead you might take advantage of EditText's setError(CharSequence) method where you can show a message to the user why the input is not valid.

How to change a value to an Activity after pressing a button in android?

(Edited to be able to compare string)
I have 1 TextView, and 2 buttons, one button is "Month" the other button "Week".
Im trying to change the Textview accordingly to the button pressed e.g Month,Week
When i start the activity for the first time it displays the "Month" as expected.
After when i press "Week" button always displays the "Week" in the TextView, even if i click on "Month" button still shows Week view.
debugging says that when i press "Month" , "Month"= "true", then onCreate the value is still "True", but in the 1st If statement
if (extras != null){ // <-------here is still true
month = extras.getString(month); // <-------here is false
}
that value suddenly goes to "false"
I know i could settext in the buttons, but later on i will add graphs to display data, so i would like to be done onCreate. Every times it creates the view, will check which view is selected(by comparing the string) and display the message and graphs. first time run to display the Month view.
What am i doing wrong?
Heres the code
package com.isma.report;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class report1 extends Activity{
TextView viewtime;
String month = "true";
Intent starterIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.report);
starterIntent = getIntent();
Bundle extras = getIntent().getExtras();
if (extras != null) {
month = extras.getString("month");
}
// Set the text
viewtime = (TextView) findViewById(R.id.StudentReportText);
if (month.equals("true")){
viewtime.setText("Monthly View");
}
if{month.equals("false")){
viewtime.setText("Weekly View");
}
//Month View Button
Button bMonth = (Button) findViewById(R.id.monthincome);
bMonth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
starterIntent.putExtra(month, "true");
startActivity(starterIntent);
finish();
}
});
//Week View Button
Button bWeek = (Button) findViewById(R.id.weekincome);
bWeek.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
starterIntent.putExtra(month, "false");
startActivity(starterIntent);
finish();
}
});
}
}
if (month == "true")
You can't compare strings in Java using ==. Use equals(...) - example...
if (month.equals("true"))
Finally i managed to fix it!
First thanks to all u helped me.
Now the fix is very simple.
I moved the initialization of the String month to inside of onCreate method with no value.
i also extended the if statement to assign the value true if was the firs time running or not pressing any button.
String month = "";
Bundle extras = getIntent().getExtras();
if (extras != null) {
month = extras.getString(month);
}
else{
month = "true";
}
I also initialized with no values the month variable in the onClick methods
String month = "";
very simple but it took me 2 days to figure out! ;p
thanks again guys

Cannot get variables to display values in edittext form

I'm working on an app that's main layout consists of a row of buttons on top of a LinearLayout which hold a form made up of edittexts. I've created a Form object to hold all the values to be displayed in the edittexts for each form. Each button is clicked to change the form's data to show the values held in each Form object. I have the Form objects kept in a List so that I can access each one when the corresponding button is pressed.
EDIT: I've realized I didn't quite explain myself properly. When I click one of the buttons, I want the EditText values to change to a different set of values which correspond to that button. But when I click these buttons, the previously entered values do not show up. I referred to the column of EditTexts a form, but it's just a column of EditTexts.
When I click Next Drink, it dynamically creates a button as well as a Form object, and clears the EditTexts so that it looks like a new form has been created for the new button. I should then be able to add strings to the EditTexts, and the strings should be stored in the Form object so that if I click that button again, the Form object will fill the EditTexts with the strings stored in that object.
So, if I click button 3 after having clicked button 2, it should set the text of each EditText to the values contained in the the third Form object, which contains strings for Name, Volume, Percentage, Price, and Quantity.
My problem is the values do not show up in the EditTexts after clicking a button. So if I click Button 3, the values from Form 3 don't show up. I've been at this for a long time and cannot figure out why, so I'd really appreciate any help. Here is the activity:
package com.example.DrinkApp;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.util.ArrayList;
import java.util.List;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
//view variables
final Button newDrink[] = new Button[100];
LinearLayout drinkSelectionContainer;
EditText name;
EditText vol;
EditText perc;
EditText pri;
AutoCompleteTextView quant;
//counters
int numOfDrinks = 0;
int selectedForm = 0;
//array to hold all Form objects.
List<Form> formList = new ArrayList<Form>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get views
drinkSelectionContainer = (LinearLayout) findViewById(R.id.drinkSelectContainer);
name = (EditText) findViewById(R.id.etName);
vol = (EditText) findViewById(R.id.etVol);
perc = (EditText) findViewById(R.id.etPerc);
pri = (EditText) findViewById(R.id.etPrice);
quant = (AutoCompleteTextView) findViewById(R.id.etQuantity);
Button saveDrink = (Button) findViewById(R.id.bSaveForm);
Button nextDrink = (Button) findViewById(R.id.bNextDrink);
Button crunkOut = (Button) findViewById(R.id.bCalc);
///////////////////////// next drink method
addNewDrinkButton();
name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
formAdd();
}
#Override
public void afterTextChanged(Editable editable) {
// mNames.add(selectedForm, name.getText().toString());
// newDrink[selectedForm].setText(name.getText().toString());
}
});
nextDrink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewDrinkButton();
}
});
}
//listener for drink select buttons. when button is clicked, it finds out which one it was,
//and then displays the correct values.
public View.OnClickListener drinkSelectListener = new View.OnClickListener() {
public void onClick(View v) {
selectedForm = v.getId();
Form form = formList.get(selectedForm);
Button v1 = (Button) findViewById(selectedForm);
v1.setText(" " + selectedForm);
// Do something depending on the value of the tag
Log.v("My Logs:", "Select Drink " + selectedForm + " button pressed.");
Log.v("My Logs:", "Drink " + selectedForm + " name: " + form.getName());
formDisplay(form);
}
};
private void addNewDrinkButton() {
formClear();
formAdd();
numOfDrinks++;
selectedForm = numOfDrinks;
Log.v("My Logs:", "Next Drink button pressed.");
newDrink[numOfDrinks] = new Button(getBaseContext());
newDrink[numOfDrinks].setOnClickListener(drinkSelectListener);
newDrink[numOfDrinks].setId(numOfDrinks);
newDrink[numOfDrinks].setText("" + selectedForm);
newDrink[numOfDrinks].setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
// name.setText("Drink " + (numOfDrinks+1));
drinkSelectionContainer.addView(newDrink[numOfDrinks]);
//TODO: save form values, clear edit texts, and create new variables for edittexts.    
}
void formAdd(){
Form tempForm = new Form();
tempForm.setId(selectedForm);
tempForm.setName(name.getText().toString());
tempForm.setVolume(vol.getText().toString());
tempForm.setPercentage(perc.getText().toString());
tempForm.setPrice(pri.getText().toString());
tempForm.setQuantity(quant.getText().toString());
formList.add(selectedForm, tempForm);
}
void formDisplay(Form form){
name.setText(form.getName());
vol.setText(form.getVolume());
perc.setText(form.getPercentage());
pri.setText(form.getPrice());
quant.setText(form.getQuantity());
}
void formClear(){
name.setText("");
vol.setText("");
perc.setText("");
pri.setText("");
quant.setText("");
}
}
!Here's the main layout. So if I click button 4, I want to have the EditTexts display the values
I'd entered the last time I'd clicked on it. It's really very simple, I'm having trouble explaining myself today.
The code provided doesn't seem to coincide with your question. You want to put values into an EditText view and then hit a button that takes the values from that EditText view and places it inside of a "form"? If so, then inside of onCreate() and after you have setContentView() try:
EditText name = (EditText) findViewById(R.id."edit_text_id"); // where "edit_text_id" is your your EditText view id set in your xml
String text = name.getText().toSting();
TextView textView = (TextView) findViewById(R.id."forms_text_field"); // where "forms_text_field" is your TextView id set in your form's xml
textView.setText(text);
Repeat this for each of your EditText views (setting a corresponding TextView in your form to the desired EditText field value). This should work just fine.

OnCheckedChangeListener & OnClickListener in android -- Button half-works on first click, finishes on second click?

Well... here's a problem it looks like I'm not the first to experience looking through other questions, however I can't find one that's Android-specific (others are C++ or straight java with different scenarios).
I have a calculator that determines your fuel mileage needs with given user inputs. The thing I'm adding now is a "burnoff" aspect where you can calculate the weight lost over the course of the race. Before adding the weight/burnoff element, everything worked fine.
Now, everything calculates normally except the weight on the first click.
On the second click (and subsequent clicks) it calculates properly. I suspect it has something to do with the switch statement and its location, but I could be wrong.... and even if I'm not, I'm not sure how to change it.
Looking for help on getting it all functioning properly on the first click. Thanks!
EDIT: The non-exception Toast text I put in as a debugger to determine if it was a math issue or what in the code. It pops up with "0.0" on the first click, then either "6.2" or "6.6" on subsequent clicks.
package com.tomcat.performance;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class Fuelsimple extends Activity implements OnCheckedChangeListener{
double fuelweight;
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId){
case R.id.rbMethanol:
fuelweight = 6.6;
break;
case R.id.rbGasoline:
fuelweight = 6.2;
break;}
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.fuelsimple);
RadioGroup rgFuelType = ((RadioGroup) findViewById (R.id.rgFuelType));
rgFuelType.setOnCheckedChangeListener(this);
RadioButton rbMethanol = ((RadioButton) findViewById(R.id.rbMethanol));
RadioButton rbGasoline = ((RadioButton) findViewById(R.id.rbGasoline));
Button gen = ((Button) findViewById(R.id.submit));
gen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
EditText fuelUsed, pracLaps, featureLaps;
pracLaps = ((EditText) findViewById(R.id.pracLaps));
fuelUsed = ((EditText) findViewById(R.id.fuelUsed));
featureLaps = ((EditText) findViewById(R.id.featureLaps));
TextView textLPGValue, textFuelNeededValue, textBurnoffValue;
try{
double pracLapsVar = Double.parseDouble(pracLaps.getText().toString());
double fuelUsedVar = Double.parseDouble(fuelUsed.getText().toString());
double featureLapsVar = Double.parseDouble(featureLaps.getText().toString());
double efficiency = (pracLapsVar / fuelUsedVar);
double fuelNeeded = (featureLapsVar / efficiency);
double burnoff = (1.05 * (fuelNeeded * fuelweight));
Toast andJelly = Toast.makeText(Fuelsimple.this, String.valueOf(fuelweight), Toast.LENGTH_LONG);
andJelly.show();
textLPGValue = ((TextView) findViewById(R.id.textLPGValue));
textFuelNeededValue = ((TextView) findViewById(R.id.textFuelNeededValue));
textBurnoffValue = ((TextView) findViewById(R.id.textBurnoffValue));
textLPGValue.setText(String.valueOf(String.format("%.3f", efficiency)) + " laps per gallon");
textFuelNeededValue.setText(String.valueOf(String.format("%.3f", fuelNeeded)) + " gallons");
textBurnoffValue.setText(String.valueOf(String.format("%.2f", burnoff)) + " pounds");
} catch (NumberFormatException e) {Toast andEggs = Toast.makeText(Fuelsimple.this, "Please complete all fields and enter your fuel & lap info in decimals or whole numbers.", Toast.LENGTH_LONG); andEggs.show();}
catch (NullPointerException n) {Toast andEggs = Toast.makeText(Fuelsimple.this, "Please enter ALL lap and fuel data.", Toast.LENGTH_LONG);
andEggs.show();}
}}
);
}
public void onClick(View v) {
}
}
As far as I can tell, your variable fuelWeight is never initialized until a radio button is pressed. The simplest way to fix this would be to call setChecked(true) on either rbmethanol or rbGasoline after setting the listener, maybe right below where you initialize those variables. Doing it after setting the listener is important, because you want the switch statement to be resolved. Right now, before you press a radio button, fuelWeight, as with all numeric primitive data types, will be initialized to 0. This is probably the reason your first calculations are wrong.
You can also have a look at CheckChangeListener.It is called whenever the check state changes.
cbSave.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int visibility = isChecked ? View.VISIBLE : View.GONE;
findViewById(R.id.nameInstructions).setVisibility(visibility);
findViewById(R.id.name).setVisibility(visibility);
}

show the text of an EditText into a TextView

Describing the functionality of my application: I have put in a Relative Layout a TextView, an EditText and a button. All I am trying to do is: when the user writes something in the EditText and push the button, then the content of the EditText is appeared in the TextView(just like a chat-virtual chat). Everything works perfectly, but when the EditText is empty,and the button get pushed, an empty line is appeared in the TextView(and i don't want to..). Although I've tried to solve it using an if the empty line is still appearing in the TextView. I would be really greatfull, if you could help!!! Than you in advance!
Here is my code:
package teiath.android.appliacation;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class M_chat extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/**Code for the scroll bars in the TextView. */
final TextView tv = (TextView)findViewById(R.id.TEXT_VIEW);
tv.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars
/** Code for the scroll bars in the EditText. */
final EditText wr = (EditText)findViewById(R.id.EDIT_TEXT);
wr.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars
final Button button = (Button) findViewById(R.id.btn1);//find the button by id in main.xml
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String wrcontent = wr.getText().toString();//gets the text of the EditText and put it in "tvcontent" variable.
String tvcontent = tv.getText().toString();//gets the text of the textView and put it in "tvcontent" variable.
if (wrcontent!="")//if the EditText is not empty
{
//check if the TextView is empty or not
if (tvcontent!="")//If it is not empty...
{
tv.setText(tvcontent + "\n" + wrcontent);//add its current(TextView's text) text, new line and the text of the EditText as the new text of TextView.
//tv.setVisibility(0);//makes visible the textView with the cloud1.png background
wr.setText("");//set the text of the Edit Text as empty
//wrcontent = "";
}
else//if the TextView is empty...
{
tv.setText(wrcontent);//add the text of the editText as the new text of the TextView
wr.setText("");
}
}
/**if (wrcontent=="")
{
}*/
//finish();
}
});
}
}
Don't use !="" for String comparison. To check for empty text, use something like
if ( wrcontent != null && wrcontent.trim().length() == 0 ) {
Better yet, include Guava libraries in your code.

Categories

Resources