need help on this!
Im trying to make toast for a empty edittext, and turns out keep getting errors with the float.
Please advise
This is the code:
calcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
**float bs = Float.parseFloat(basicSalary.getText().toString());**
float tw = Float.parseFloat(totalAllowance.getText().toString());
float mob = String spinTEXT = spinner.getSelectedItem().toString();
if (spinner.getSelectedItem().equals("Select age group")){
Toast.makeText(sghospitalbonuscalculator.this, "Test 123",
Toast.LENGTH_SHORT).show();
}
if (basicSalary.getText().toString().equals("")){
Toast.makeText(sghospitalbonuscalculator.this, "Test 321",
Toast.LENGTH_SHORT).show();
}
This is the error:
java.lang.NumberFormatException: Invalid float: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseFloat(StringToReal.java:308)
at java.lang.Float.parseFloat(Float.java:306)
at sg.self.wser.bonuscalc.bonuscalcu$4.onClick(bonuscalcu.java:96)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The bonuscalc.java:96 is referring to this line of code:
float bs = Float.parseFloat(basicSalary.getText().toString());
As for the toast, i tried to change the .equals("") to .equals(" "), .equals(null) and .isEmpty, but still it wouldnt work.
Please advise!
Thanks a million!
Edited version:
Code:
if (basicSalary.getText().toString().equals(0.0)){
Toast.makeText(sghospitalbonuscalculator.this, "Test 321",
Toast.LENGTH_SHORT).show();
}
Errors shown:
java.lang.NumberFormatException: Invalid float: ""
You want to test if your input is blank and if so assign the value 0.0
float bs = 0.0f;
if (basicSalary.getText().toString().equals("") == false){
bs = Float.parseFloat(basicSalary.getText().toString());
}
further down you test this for the Toast
if (basicSalary.getText().toString().equals("")){
Toast.makeText(sghospitalbonuscalculator.this, "Test 321",
Toast.LENGTH_SHORT).show();
}
maybe you could change it to
if (bs == 0.0f){
Toast.makeText(sghospitalbonuscalculator.this, "Test 321",
Toast.LENGTH_SHORT).show();
}
Related
public class MainActivity extends AppCompatActivity {
public void grade (View view){
final EditText varEditBox = (EditText)findViewById(R.id.editBox);
TextView varText = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);
if (varEditBox.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(), "EMPTY", Toast.LENGTH_SHORT).show();
varText.setText( "");
}
if ((Integer.parseInt(varEditBox.getText().toString() )>=101)||(Integer.parseInt(varEditBox.getText().toString() )<1) ){
Toast.makeText(getApplicationContext(), "Invalid", Toast.LENGTH_SHORT).show();
varText.setText( "");
} }
I have the above code with a condition to check if the EditText box is empty, but any time I press the button with an empty EditBox, the app crashes. I've been debugging but no success. Normally I get this error when I don't do the check, now I've done the check, it's still here. Plus the varEditBox isn't empty, because the other if statement runs as well. If I put in a number more than 100, it toasts "invalid" thus, the second condition works
LogCat error. I'm not sure if I have to post all of it, but this is the error I get
FATAL EXCEPTION: main
Process: com.listener.gradesystem, PID: 31936
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.listener.gradesystem.MainActivity.grade(MainActivity.java:24)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NumberFormatException: Invalid int: ""
One of you Integer.parseInt calls is failing. I can only assume you somehow have whitespace in your string. If your EditText only allows more than just numbers, consider doing this:
public void grade (View view){
final EditText varEditBox = (EditText)findViewById(R.id.editBox);
TextView varText = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);
// trim to remove whitespace
final String text = varEditBox.getText().toString().trim();
if (TextUtils.isEmpty(text) || !TextUtils.isDigitsOnly(text)){
Toast.makeText(getApplicationContext(), "EMPTY OR NOT NUMERIC", Toast.LENGTH_SHORT).show();
varText.setText("");
// quit early, don't need to parse this number
return;
}
// we should have already quit by now if we can't parse this number
int value = Integer.parseInt(text);
if (value >= 101 || value < 1) {
Toast.makeText(getApplicationContext(), "Invalid", Toast.LENGTH_SHORT).show();
varText.setText("");
}
}
If this still fails, at least it will highlight where your problem is.
Try this.The problem was in your if else condition.
final EditText varEditBox = (EditText)findViewById(R.id.editBox);
TextView varText = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (varEditBox.getText().toString().trim().isEmpty()){
Toast.makeText(getApplicationContext(), "EMPTY", Toast.LENGTH_SHORT).show();
varText.setText( "");
}
else{
if ((Integer.parseInt(varEditBox.getText().toString())>=101)||(Integer.parseInt(varEditBox.getText().toString() )<1) ){
Toast.makeText(getApplicationContext(), "Invalid", Toast.LENGTH_SHORT).show();
varText.setText( "");
}
}
}
});
this is my first activity, i want to pass the value to second activity to do calculation and show the result in the textview.But I dont know why when i key in all the detail at activity 1, and click the custom button it jump out from the app
public void onClick(View v){
switch (v.getId())
{
case R.id.customMarco:
if(gender.getText().toString().equals("") || age.getText().toString().equals("")||
height.getText().toString().equals("")||weight.getText().toString().equals("")||
activity.getText().toString().equals("")||goal.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(), "Please key in all your detail above !", Toast.LENGTH_LONG).show();
}
else {
String cal = finalCal_result.getText().toString();
String carb = carb_result.getText().toString();
String protein = protein_result.getText().toString();
String fat = fat_result.getText().toString();
Intent intent = new Intent(this, CustomMarco.class);
intent.putExtra("Cal", cal);
intent.putExtra("Carb", carb);
intent.putExtra("Protein", protein);
intent.putExtra("Fat", fat);
startActivity(intent);
}
break;
}
This is my second activity, to get the valur from activity 1 and do calculation and show the result in textview cp. But I dont know why when i key in all the detail at activity 1, and click the custom button it jump out from the app
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom__marco);
cal = (EditText) findViewById(R.id.field_cal);
String calNum =getIntent().getStringExtra("Cal");
cal.setText ( calNum );
cal.setOnClickListener(this);
carb = (EditText) findViewById(R.id.field_carb);
String carbNum =getIntent().getStringExtra("Carb");
carb.setText ( carbNum );
carb.setOnClickListener(this);
Button setButton = (Button) findViewById(R.id.setButton);
setButton.setOnClickListener(this);
TextView cp = (TextView) findViewById(R.id.cp);
float cal_n = Float.parseFloat(calNum);
float carb_n = Float.parseFloat(carbNum);
int carbPValue = calculateCP(cal_n,carb_n);
cp.setText(String.valueOf(carbPValue) + " %");
}
private int calculateCP(float cal_n, float carb_n){
return (int) ((carb_n/cal_n)*4*100);
}
here the log cat error
12-03 21:25:39.284
28640-28640/com.example.sam.iifym E/AndroidRuntime:
FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sam.iifym/com.example.sam.iifym.CustomMarco}: java.lang.NumberFormatException: Invalid int: "3809 cal"
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2383)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$600(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5434)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:619)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NumberFormatException: Invalid int: "3809 cal"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:375)
at java.lang.Integer.parseInt(Integer.java:366)
at java.lang.Integer.parseInt(Integer.java:332)
at com.example.sam.iifym.CustomMarco.onCreate(CustomMarco.java:59)
at android.app.Activity.performCreate(Activity.java:5224)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1151)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2347)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$600(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5434)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:619)
at dalvik.system.NativeStart.main(Native Method)
Bundle extras = getIntent().getExtras();
String carb = extras.getString("Carb");
for more info just check this answer:
https://stackoverflow.com/a/5265952/2074990
There is problem in your string.
LogCat says Invalid int: "3809 cal"
You pass Invalid data in that string.
You can just pass only Integer for convert String to Float
Example :
Valid String is "3809".
Instead of "3809 cal".
Caused by: java.lang.NumberFormatException: Invalid int: "3809 cal"
You're trying to convert the String "3809 cal" to int/float, while "3809 cal" is not a valid format of int/float.
Check your cal String in the first activity, it must be "3809" instead of "3809 cal".
So basically I have a problem. When the user presses the calculate button (I'm making a calculator) without entering a value the app crashes. I want it to display a message instead but I don't know how. (updated)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waist2height); {
//h is cm edittext
final EditText h = (EditText)findViewById(R.id.editText2);
final EditText w = (EditText)findViewById(R.id.editText3);
final EditText r = (EditText)findViewById(R.id.textView4);
});
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
float height=0;
float weight=0;
float result=0;
result = (float) (( weight / height ) + 0.005) ;
if ((h.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter your height", Toast.LENGTH_SHORT).show();
float height = Float.parseFloat(h.getText().toString());
}
if ((w.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter your weight", Toast.LENGTH_SHORT).show();
float weight = Float.parseFloat(w.getText().toString());
}
r.setText(String.valueOf(result));
}
the code below is where i have the problem
if ((h.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter your height", Toast.LENGTH_SHORT).show();
float height = Float.parseFloat(h.getText().toString());
}
if ((w.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter your weight", Toast.LENGTH_SHORT).show();
float weight = Float.parseFloat(w.getText().toString());
}
This is the best I can come up with but it doesn't work.
Here is the LogCat (Updated)
09-20 18:50:38.509: E/AndroidRuntime(29769): FATAL EXCEPTION: main
09-20 18:50:38.509: E/AndroidRuntime(29769): Process: com.NovaPlex.personalfitnessfree, PID: 29769
09-20 18:50:38.509: E/AndroidRuntime(29769): java.lang.NumberFormatException: Invalid float: ""
09-20 18:50:38.509: E/AndroidRuntime(29769): at java.lang.StringToReal.invalidReal(StringToReal.java:63)
09-20 18:50:38.509: E/AndroidRuntime(29769): at java.lang.StringToReal.parseFloat(StringToReal.java:308)
09-20 18:50:38.509: E/AndroidRuntime(29769): at java.lang.Float.parseFloat(Float.java:306)
09-20 18:50:38.509: E/AndroidRuntime(29769): at com.NovaPlex.personalfitnessfree.WH$2.onClick(WH.java:80)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.view.View.performClick(View.java:4780)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.view.View$PerformClick.run(View.java:19866)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.os.Handler.handleCallback(Handler.java:739)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.os.Handler.dispatchMessage(Handler.java:95)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.os.Looper.loop(Looper.java:135)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.app.ActivityThread.main(ActivityThread.java:5254)
09-20 18:50:38.509: E/AndroidRuntime(29769): at java.lang.reflect.Method.invoke(Native Method)
09-20 18:50:38.509: E/AndroidRuntime(29769): at java.lang.reflect.Method.invoke(Method.java:372)
09-20 18:50:38.509: E/AndroidRuntime(29769): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
09-20 18:50:38.509: E/AndroidRuntime(29769): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Don't use == null. Assuming you've done findviewbyid, it cannot be null. It doesn't check for contents.
This is a simple method how to find if EditText is empty. Parameter is the EditText you want to check and it returns true for empty / false for non-empty.
private boolean isEmpty(EditText etText) {
return etText.getText().toString().trim().length() <= 0;
}
EDIT :
by using android:id="#+id/someId in xml files, we tell Android to create new resource with chosen id (in this case someId) in our R.java class. When doing findviewbyid we assign that value to our View.
In short if OP did something like EditText EditText1 = (EditText) findViewById(R.id.myFistEditText); before and he later tries to compare it in his if like (EditText1 == null), it's not actually getting value of text in his EditText, it's just telling him that - yes, this view was found before and it's assigned.
You can just try this, to check if value is not entered in the EditText.
if ((EditText1.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value1", Toast.LENGTH_LONG).show();
}
if ((EditText2.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value2", Toast.LENGTH_LONG).show();
}
Alternatively, you can use .matches("") instead of .equals("")
UPDATE
You have to do it like this
if (!(h.getText().toString()).equals(""))
{
height= Float.parseFloat(h.getText().toString());
}
and
if (!(w.getText().toString()).equals(""))
{
weight= Float.parseFloat(w.getText().toString());
}
UPDATE
if ((EditText1.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value1", Toast.LENGTH_LONG).show();
}
if ((EditText2.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value2", Toast.LENGTH_LONG).show();
}
if (!(h.getText().toString()).equals(""))
{
height= Float.parseFloat(h.getText().toString());
}
if (!(w.getText().toString()).equals(""))
{
weight= Float.parseFloat(w.getText().toString());
}
Replace the above code instead of yours
It is already said that you'd better write a method isEmpty.
My suggestion is rather than writing isEmpty write a method called isValid which checks if the value is a desired value i.e. integer, double etc.
This way your program wont crash when a string is entered.
use
if(textView.getText().toString().isEmpty()){
Toast.makeText(this , "Enter A Number" , Toast.LENGTH_SHORT).show();
}
I am new to Android and Java programming and for some reason (I cant point out) my app wont even open.It says "Unfortunately 'app name' has crashed". It has no compile-time errors in it?
Here is the Logcat:
08-19 04:54:07.024 24170-24170/com.elie.billsplitter E/AndroidRuntime﹕FATAL EXCEPTION: main
Process: com.elie.billsplitter, PID: 24170
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.elie.billsplitter/com.elie.billsplitter.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.elie.billsplitter.MainActivity.<init>(MainActivity.java:11)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
08-19 04:54:09.781 24170-24177/com.elie.billsplitter W/art﹕ Suspending all threads took: 793.743ms
08-19 04:54:36.935 24170-24170/com.elie.billsplitter I/Process﹕ Sending signal. PID: 24170 SIG: 9
Here is the Java file:
public class MainActivity extends Activity {
public int x = Integer.parseInt("");
public int y = Integer.parseInt("");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Button
Button btn = (Button) findViewById(R.id.button);
//EditText
EditText nop = (EditText) findViewById(R.id.editText);
EditText cob = (EditText) findViewById(R.id.editText2);
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int z = x / y;
tv.setText(z);
}
});
}
}
Most probably you are parsing an empty string into the integer.
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
before getting the text from the Edittext check that whether it is empty or not. You are parsing an empty string probably.
you can make a check like this:
if(!(nop.toString().trim().equalsIgnoreCase("") && cob.toString().trim().equalsIgnoreCase(""))){
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
}
and also your are making the initilization the integers in an incorrect way:
May be these are the lines where you are getting exceptions. You cannot parse blank strings to integer.
instead of this:
public int x = Integer.parseInt("");
public int y = Integer.parseInt("");
write this:
public int x = 0;
public int y = 0;
or
public int x = Integer.parseInt("0");
public int y = Integer.parseInt("0");
Before converting to a number you can check if it is a numeric string. For some ideas read this thread on stackoverflow: How to check if a String is numeric in Java
Somewhere in your code you are converting a invalid string or a empty string into a number, which is causing the NumberFormatException.
String x = "abc";
int num = Integer.parseInt(x);
How do I solve it?
try
{
String x = "abc";
int num = Integer.parseInt(x);
}
catch(NumberFormatException ne)
{
System.out.println("Invalid Number!");
}
In your code, replace:
public int x = Integer.parseInt("");
public int y = Integer.parseInt("");
with
public int x;
public int y;
The default values of x and y will be 0. You don't have to add that.
Reason of Error: Integer.parseInt() converts the string inside it to an integer. You have tried to convert "" to an integer, which is not even a number... So NumberFormatException occurred.
I'm looking to create a running total on my MainActivity.java, this will be done through adding integers calculated in ActivityAdd.java then sending them across onClick save to a TextView in the MainActivity.java.
It's currently not opening the app due to the stack flow error stating invalid int "". Any advise on this?
AddActivity.Java
OnClickListener button02OnClickListener =
new OnClickListener(){
#Override
public void onClick(View v) {
String theText = result.getText().toString();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("calorie", theText);
startActivity(intent);
}};
MainActivity.Java
String calorie = getIntent().getStringExtra("calorie");
TextView textView1 = (TextView)findViewById(R.id.textView1);
Integer oldValue = Integer.parseInt(textView1.getText().toString());
Integer newValue = Integer.parseInt(calorie);
textView1.setText((oldValue + newValue));
StackFlow error
02-24 09:42:39.873 2535-2535/com.example.student.neillapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.student.neillapp, PID: 2535
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.student.neillapp/com.example.student.neillapp.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.example.student.neillapp.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The Error occurs due to Empty String "" in textView1.
You are not checking if the String is Blank or not.
So, I added extra 2 lines.
String calorie = getIntent().getStringExtra("calorie");
TextView textView1 = (TextView)findViewById(R.id.textView1);
String strOldValue = textView1.getText().toString();
//Integer oldValue = StringUtils.isNotBlank(myString) ? Integer.parseInt(myString) : 0;
//UPDATE: Replace above with
//Integer oldValue = (myString != null && !myString.isEmpty()) ? Integer.parseInt(myString) : 0;
//UPDATE:
Integer oldValue = 0;
try {
oldValue = Integer.parseInt(myString);
} catch(Exception e) {
//oldValue = 0;
}
Integer newValue = Integer.parseInt(calorie);
textView1.setText((oldValue + newValue));
I think this might help you.
If i understood , what you are looking for is starting an activity for result...
So to do that in your main activity you have to start the ActivityAdd for result like so..
Intent intent = new Intent(getActivity(), ActivityAdd.class);
startActivityForResult(intent,1);
Also in the main activity then you override method onActivityResult like so :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == getActivity().RESULT_OK){
//UPDATE TEXTVIEWS HERE
//DATA IS THE INTENT
}
}
Now in our add activity we must return result once we have it..
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("calorie", theText);
setResult(RESULT_OK, intent);
finish();
In you MainActivity.java
String calorie = getIntent().getStringExtra("calorie");
TextView textView1 = (TextView)findViewById(R.id.TextView1);
Integer oldValue = Integer.parseInt(textView1.getText().toString());
Integer newValue = Integer.parseInt(calorie);
//setText() needs a String to set so you can do anyone of the following
textView1.setText(""+(oldValue + newValue));
or
Integer total = oldValue + newValue;
textView1.setText(total.toString());