1 error wont let my code compile - java

I am new to android programming and I am trying to make an app that splits a bill between people. But something about my integers are wrong. I know this because in my logcat it says "Caused by: java.lang.NumberFormatException: Invalid int: ""
Here is my MainActivity.java
public class MainActivity extends Activity {
public double x;
public double y;
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);
//Getting the strings
try{
x = Double.valueOf(nop.getText().toString());
} catch (NumberFormatException) {
x = 0;
}
try{
y = Double.valueOf(cob.getText().toString());
} catch (NumberFormatException) {
y = 0;
}
String textX = nop.getText().toString();
// if variable contains valid number:
if (textX != null && textX.length() > 0)
x = Double.valueOf(); // exception thrown by method
else
x = 0;
//TextView
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double z = x / y;
tv.setText((int) z);
}
});
}
}
Here is the logcat:
08-19 07:30:28.452 16070-16070/com.elie.billsplitter E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.elie.billsplitter, PID: 16070
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.elie.billsplitter/com.elie.billsplitter.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
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.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            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)

Looking to your exception:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.elie.billsplitter/com.elie.billsplitter.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
The error is in this piece of code
//Getting the strings
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
Why? nop.getText().toString().equals("") or cob.getText().toString().equals("").
How to avoid? You must be sure you get a valid String from this EditText because if them are empty or does not contain an equivaloent double String you will have a NumberFormatException.
Solution?Best ways will be:
adding a validation to EditText to get only valid Strings.
Convert the value if NumberFormatException is thrown.
try{
x = Double.valueOf(nop.getText().toString());
} catch (NumberFormatException e) {
x = 0;
}
try{
y = Double.valueOf(cop.getText().toString());
} catch (NumberFormatException e) {
y = 1; // division / 0 will throw NaN
}
ADD-ON:
Why I dont use Integer.parseInt()??
If you create doubles you cannot parse ints because you will lose accuracy, and, for example in java (int) 1 / (int) 3 = 0 or (int) 10 / (int) 3 = 3 so use Double::valueOf()
x = Double.valueOf(nop.getText().toString());
y = Double.valueOf(cob.getText().toString());

Related

EditText crash when empty

so I have an EditText field,and when the user tap a number,its start counting down.
The problem starts when the are not entering a number the app crash.
this is what I tried to do:
Thanks for the help.
public class MainActivity extends AppCompatActivity {
EditText mEnterNumber;
TextView mTest;
int timerIsRunning = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void StartRemainder(View view){
mTest = findViewById(R.id.mTest);
mEnterNumber = findViewById(R.id.mEnterNumber);
int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
if(userNumb < 0 || mEnterNumber.toString().isEmpty()){
Toast.makeText(MainActivity.this, "Please enter correct number", Toast.LENGTH_SHORT).show();
}
else{
CountDownTimer userTimer = new CountDownTimer(userNumb,1000) {
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
//Convert milliseconds into hour,minute and seconds
String hms = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
mTest.setVisibility(View.VISIBLE);
mTest.setText(hms);
timerIsRunning = 1;
}
#Override
public void onFinish() {
}
}.start();
}
}
----------------------This is the error I get when the app crash:--------------------------------
2020-09-04 04:09:15.024 27096-27096/com.example.drinkme E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.drinkme, PID: 27096
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
Caused by: java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:620)
at java.lang.Integer.parseInt(Integer.java:643)
at com.example.drinkme.MainActivity.StartRemainder(MainActivity.java:40)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
at android.view.View.performClick(View.java:6256) 
at android.view.View$PerformClick.run(View.java:24701) 
at android.os.Handler.handleCallback(Handler.java:789) 
at android.os.Handler.dispatchMessage(Handler.java:98) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 
line of error:
int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
I'm guessing the issue is with this line:
int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
And it is because, an empty string("") cannot be converted to a number unlike strings like "1" or "2"
To fix this:
We Provide a try-catch block for the NumberFormatException
int userNumb = 0;
try {
if (mEnterNumber != null && !TextUtils.isEmpty(mEnterNumber.getText().toString())) {
userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
}
}
catch (NumberFormatException ex) {}
You're not getting the text from the edittext before checking weather it's empty or not. Try this :
if(userNumb < 0 && mEnterNumber.`getText()`.toString().isEmpty()){
Toast.makeText(MainActivity.this, "Please enter correct number",
Toast.LENGTH_SHORT).show();
int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
}
As you can see I've put the integer conversion in the if block as it might also be the reason for it.
Like Felix Favour said it's because you're trying to parse a non-numeric item into a string. This line:
mEnterNumber = findViewById(R.id.mEnterNumber);
Will most likely resolve to Null if nothing is entered. You can try setting it to a numeric value:
mEnterNumber = findViewById(R.id.mEnterNumber);
if mEnterNumber.getText().toString().equals("")
{
int userNumb = 0; // or whatever value you want to set as a starting default
}
else
{
int userNumb = Integer.parseInt(mEnterNumber.getText().toString()) * 60000;
}
This invariably could need more improvement for checking or preventing other non-numeric entries ofcourse.
Alternatively, you can also set it in the XML like this:
<EditText
android:id="#+id/mEnterNumber"
...
android:text="0" />
I use something like this -
if (mEnterNumber.getText().toString().matches("")){
Toast.makeText(this, "Please Enter any number", Toast.LENGTH_SHORT).show();
return;
}
I hope this will prevent the crash.

How can i fix a numberformatexception

I am new to android and java programming and I know this error is caused by a number format exception but i don't know how to fix it. But i'm new so i'm sorry that its such a low level question.
public class MainActivity extends Activity {
public double x = 0;
public double y = 0;
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 = Double.parseDouble(nop.getText().toString());
y = Double.parseDouble(cob.getText().toString());
try{
x = Double.valueOf(nop.getText().toString());
} catch (NumberFormatException e) {
x = 0;
}
try{
y = Double.valueOf(cob.getText().toString());
} catch (NumberFormatException e) {
y = 1;
}
//TextView
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Double z = x / y;
tv.setText("Result:" + Double.toString(z));
}
});
}
}
Here is the Logcat:
08-20 01:03:42.951 18608-18608/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
08-20 01:03:43.215 18608-18608/com.elie.billsplitter D/AndroidRuntime﹕ Shutting down VM
08-20 01:03:43.258 18608-18608/com.elie.billsplitter E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.elie.billsplitter, PID: 18608
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.elie.billsplitter/com.elie.billsplitter.MainActivity}: java.lang.NumberFormatException: Invalid double: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
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 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 com.elie.billsplitter.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            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-20 01:03:46.732 18608-18608/com.elie.billsplitter I/Process﹕ Sending signal. PID: 18608 SIG:
9
It happenes because you are trying to get the value of edittext and convert it to double. Problem is that you are trying to fetch empty editext value and convert it to double so it gives you error that invalid double "".
If you want to solve your problem then get the edittext value when you needed and check it for empty.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!nop.getText().toString().isEmpty() && !cob.getText().toString().isEmpty())
{
x = Double.parseDouble(nop.getText().toString()); //Assign value to x here not after the EditText declaration
y = Double.parseDouble(cob.getText().toString()); // Assign value to y here not after the EditText declaration
Double z = x / y;
tv.setText("Result:" + Double.toString(z));
}
else
{
// Show appropriate message for enter the value
}
}
});
x = Double.parseDouble(nop.getText().toString());
y = Double.parseDouble(cob.getText().toString());
You don't need these two lines outside the try block. You already have them in the try block. Keeping them outside makes it prone to throw an exception.
Button btn = (Button) findViewById(R.id.button);
//EditText
EditText nop = (EditText) findViewById(R.id.editText);
EditText cob = (EditText) findViewById(R.id.editText2);
double x = 0;
double y = 1;
try{
x = Double.valueOf(nop.getText().toString());
} catch (NumberFormatException e) {
}
try{
y = Double.valueOf(cob.getText().toString());
} catch (NumberFormatException e) {
}
You have wrap the parsing codes with the try-catch block also.
try{
x = Double.parseDouble(nop.getText().toString());
x = Double.valueOf(nop.getText().toString());
} catch (NumberFormatException e) {
x = 0;
}
try{
y = Double.parseDouble(cob.getText().toString());
y = Double.valueOf(cob.getText().toString());
} catch (NumberFormatException e) {
y = 1;
}
Also I am not sure why you need both of these lines.
y = Double.parseDouble(cob.getText().toString());
y = Double.valueOf(cob.getText().toString());
(in the case of x also). As #Uma kanth said you can remove one of them

NullPoint error when trying to call a function of another class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am trying to call a function registerGCM(); from my reg.java class into the MainActivity.java class.
When I use the function from inside the reg.java activity the app works just fine but whenever I call it from inside the MainActivity I get this error
07-28 13:38:38.540 24434-24434/com.example.kmi_dev.fbloginsample E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.kmi_dev.fbloginsample, PID: 24434
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kmi_dev.fbloginsample/com.example.kmi_dev.fbloginsample.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.kmi_dev.fbloginsample.reg.registerGCM()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
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.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.kmi_dev.fbloginsample.reg.registerGCM()' on a null object reference
at com.example.kmi_dev.fbloginsample.MainActivity.onCreate(MainActivity.java:158)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            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)
Content of the MainActivity where call is being made
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static final String MYPREFERENCES = "myPref";
private CallbackManager callbackManager;
private LoginButton fbLoginButton;
private Button login;
.
.
.
.
GPSTracker gps;
reg GCM_REG;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
SessionManager session;
.
.
String gcmId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get global variable class
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
gcmId = GCM_REG.registerGCM();
Content of registerGCM()
public String registerGCM() {
gcm = GoogleCloudMessaging.getInstance(this);
regId = getRegistrationId(context);
if (TextUtils.isEmpty(regId)) {
registerInBackground();
Log.d("MainActivity",
"registerGCM - successfully registered with GCM server - regId: "
+ regId);
} else {
Toast.makeText(getApplicationContext(),
"RegId already available. RegId: " + regId,
Toast.LENGTH_LONG).show();
}
final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
globalVariable.setGcmRegId(regId);
return regId;
}
public String getRegistrationId(Context context) {
final SharedPreferences prefs = getSharedPreferences(reg.class.getSimpleName(), Context.MODE_PRIVATE);
String registrationId = prefs.getString(REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
Any Idea why I am unable to call this function???
You never initialize GCM_REG. That's why you get a NullPointerException.

java.lang.NumberFormatException: Invalid int: "android.support.v7.internal.widget.TintEditText

I have code to add the two numbers from the 2 text boxes together.
public void sumNumbers(View v){
EditText input1 = (EditText) findViewById(R.id.input1);
int calc1 = Integer.parseInt(String.valueOf(input1));
EditText input2 = (EditText) findViewById(R.id.input2);
int calc2 = Integer.parseInt(String.valueOf(input2));
int total = calc1 + calc2;
String result = String.valueOf(total);
EditText output1 = (EditText)findViewById(R.id.output);
output1.setText(result);
}
However when I launch the app and press the button, I crash with this:
Caused by: java.lang.NumberFormatException: Invalid int: "android.support.v7.internal.widget.TintEditText{b412b358 VFED..CL ........ 292,60-392,100 #7f080041 app:id/input1}"
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.eren.addingmachine.MainActivity.sumNumbers(MainActivity.java:22)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at android.view.View$1.onClick(View.java:3628)
            at android.view.View.performClick(View.java:4240)
            at android.view.View$PerformClick.run(View.java:17721)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            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:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
Help?
Please paste the below working code. I have just run and checked it.
public void sumNumbers(View v){
EditText input1 = (EditText) findViewById(R.id.input1);
int calc1 = Integer.parseInt(String.valueOf(input1.getText()));
EditText input2 = (EditText) findViewById(R.id.input2);
int calc2 = Integer.parseInt(String.valueOf(input2.getText()));
int total = calc1 + calc2;
String result = String.valueOf(total);
EditText output1 = (EditText)findViewById(R.id.output);
output1.setText(result);
}
To get the text that the user enters into an EditText, you do not call String.valueOf(), passing in the EditText, as your code has. Instead, call getText().toString() on the EditText. You may still get exceptions, as the user may not have entered a valid Integer, but you will at least be closer.
Try this
public void sumNumbers(View v){
try{
EditText input1 = (EditText) findViewById(R.id.input1);
input1.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL|InputType.TYPE_NUMBER_FLAG_SIGNED);
int calc1 = Integer.parseInt(input1.getText().toString());
EditText input2 = (EditText) findViewById(R.id.input2);
input2.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL|InputType.TYPE_NUMBER_FLAG_SIGNED);
int calc2 = Integer.parseInt(input2.getText().toString());
int total = calc1 + calc2;
String result = String.valueOf(total);
EditText output1 = (EditText)findViewById(R.id.output);
output1.setText(result);
}
catch(NumberFormatException e){
Log.e("NumberFormatException" , e.getMessage().toString());
}
}
in this way you can get values from edittext.
Instead of getting refrence to EditText in onClick event do this in onCreate() method of Activity.

Android Form Validation - How do I prevent a null field from crashing my application on button press?

I have a form which lets the user add entries into a raffle. However if the user leaves one of these fields blank and presses the submit button the app crashes. I tried to get around this by creating an if statement - if any of the fields are null, do nothing. Else, run the intent. However this still does not fix my problem. Pressing the button still causes a crash.
Here is my code:
public void addEntrySubmitButtonClick(View view) {
Intent addEntryIntent = getIntent();
int currentRaffleID = addEntryIntent.getIntExtra("raffleIndexInList", 0);
Raffle currentRaffle = Raffle.raffleArrayList.get(currentRaffleID);
String newEntryForename = String.valueOf(addEntryForename.getText());
String newEntrySurname = String.valueOf(addEntrySurname.getText());
int newEntryTelephoneNo = Integer.parseInt(String.valueOf(addEntryTelephoneNo.getText()));
int newEntryTicketCount = Integer.parseInt(String.valueOf(addEntryTicketCount.getText()));
int newEntryRaffleId = currentRaffle.getId();
if ((newEntryForename.equals(null)) || (newEntrySurname.equals(null)) || (String.valueOf(addEntryTelephoneNo).equals(null)) || (String.valueOf(addEntryTicketCount).equals(null))){
Intent failIntent = new Intent();
} else {
Entry newEntry = new Entry(newEntryForename, newEntrySurname, newEntryTelephoneNo, newEntryTicketCount, newEntryRaffleId);
// Get the list of raffles
for(Raffle currentEntryRaffle : Raffle.raffleArrayList) {
if((currentEntryRaffle.getId() == newEntryRaffleId) && ((currentEntryRaffle.getEntryArrayList().size()) < (currentEntryRaffle.getMaxTickets()))) {
int counter=0;
do {
currentEntryRaffle.getEntryArrayList().add(newEntry);
counter++;
} while(counter < newEntryTicketCount);
}
}
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
}
Here is the logcat:
10-24 10:48:42.599 19481-19481/com.example.rafflemanager E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3628)
at android.view.View.performClick(View.java:4128)
at android.view.View$PerformClick.run(View.java:17142)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:4787)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3623)
            at android.view.View.performClick(View.java:4128)
            at android.view.View$PerformClick.run(View.java:17142)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:213)
            at android.app.ActivityThread.main(ActivityThread.java:4787)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:359)
at java.lang.Integer.parseInt(Integer.java:332)
at com.example.rafflemanager.AddEntry.addEntrySubmitButtonClick(AddEntry.java:48)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at android.view.View$1.onClick(View.java:3623)
            at android.view.View.performClick(View.java:4128)
            at android.view.View$PerformClick.run(View.java:17142)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:213)
            at android.app.ActivityThread.main(ActivityThread.java:4787)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
            at dalvik.system.NativeStart.main(Native Method)
newEntryForename.equals(null)
The above expression will either evaluate to false or throw a NullPointerException. It is impossible to call a method on a null reference.
String.valueOf(addEntryTelephoneNo).equals(null)
The above expression will always evaluate to false. From String.valueOf javadoc:
Returns: if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
What you want instead is simply
addEntryTelephoneNo == null
and similar for other cases.
Furthermore note that you are trying to parse the value before you have null-checked it:
int newEntryTelephoneNo = Integer.parseInt(String.valueOf(addEntryTelephoneNo.getText()));
Move that code to after the null check.
I'm writing this from a smartphone so I won't include any codesamples with this answer.
Anyway... First of all remove all String.valueOf() calls - they are redundant. Second, to see if a value is null, check for value == null, not value.equals(null). If value is null, it doesn't have the method equals(), and will thus lead to a NullReferenceException.
Also, don't call Integer.parseInt(value) before you have made sure that value isn't null.
Disabling the send button when the EditText is empty when using imeOption= actionSend
message.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
public void afterTextChanged(Editable s) {
if (s == null || s.length() == 0) {
send.setEnabled(false);
message.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
}
else {
send.setEnabled(true);
message.setImeOptions( /* whatever you previously had */ );
}
}
To check if a string is empty (null or length 0) use TextUtils.isEmpty(). Here's an example:
int newEntryTelephoneNo;
if (TextUtils.isEmpty(addEntryTelephoneNo.getText())) {
newEntryTelephoneNo = 0;
} else {
newEntryTelephoneNo = Integer.parseInt(addEntryTelephoneNo.getText());
}
The problem in your logcat is this :
Caused by: java.lang.NumberFormatException: Invalid int: ""
Without line numbers, I deduct that the problem comes from one line like this one :
int newEntryTelephoneNo = Integer.parseInt(String.valueOf(addEntryTelephoneNo.getText()));
Reading the following docs give us a hint : http://developer.android.com/reference/java/lang/Integer.html#parseInt(java.lang.String)
Throws
NumberFormatException if string cannot be parsed as an integer value.
The Integer.parseInt() seems not able to parse an empty String to an int (and it's normal, because a int can't be null).
So I think you should make something like that :
int newEntryTelephoneNo = 0;
if (!TextUtils.isEmpty(addEntryTelephoneNo.getText())) {
newEntryTelephoneNo = Integer.parseInt(addEntryTelephoneNo.getText());
}
Not about the main question
Also, as other answers and comment said, you have to use this to check the "nullity" of an object :
myObject == null
instead of
myObject.equals(null)
because you can't even call equals() or any other methods on a null instance.
The logcat clearly shows the exception occurs when the call to Integer.parseInt throws a NumberFormatException. This occurs when the string cannot be converted to an int. If you check the line numbers you will see exactly which conversion generated the exception.
Depending on your needs you probably want to both test for acceptable invalid entries like empty string and catch NumberFormatException due to invalid input so that you can inform the user of the invalid entry.
Here is the code you need:
public void addEntrySubmitButtonClick(View view) {
Intent addEntryIntent = getIntent();
int currentRaffleID = addEntryIntent.getIntExtra("raffleIndexInList", 0);
Raffle currentRaffle = Raffle.raffleArrayList.get(currentRaffleID);
String newEntryForename = String.valueOf(addEntryForename.getText());
String newEntrySurname = String.valueOf(addEntrySurname.getText());
int newEntryTelephoneNo = Integer.parseInt(String.valueOf(addEntryTelephoneNo.getText()));
int newEntryTicketCount = Integer.parseInt(String.valueOf(addEntryTicketCount.getText()));
int newEntryRaffleId = currentRaffle.getId();
if (newEntryForename==null || newEntrySurname == null || String.valueOf(addEntryTelephoneNo) == null || String.valueOf(addEntryTicketCount) == null){
Intent failIntent = new Intent();
} else {
Entry newEntry = new Entry(newEntryForename, newEntrySurname, newEntryTelephoneNo, newEntryTicketCount, newEntryRaffleId);
// Get the list of raffles
for(Raffle currentEntryRaffle : Raffle.raffleArrayList) {
if((currentEntryRaffle.getId() == newEntryRaffleId) && ((currentEntryRaffle.getEntryArrayList().size()) < (currentEntryRaffle.getMaxTickets()))) {
int counter=0;
do {
currentEntryRaffle.getEntryArrayList().add(newEntry);
counter++;
} while(counter < newEntryTicketCount);
}
}
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
}
You have to replace .equals(null) with == null since calling a method on a null pointer will crash your app.

Categories

Resources