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
Related
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.
I would like to make it so that when the editText fields are empty, no result is shown instead of the app crashing.
I read over this result here: How to break out or exit a method in Java?
as well as some other results based on whether the number was negative or positive. I've been working in this for about an hour and I'm throwing in the towel. I'm new to this, and I think I must just not be putting the if statement in the correct location?
Here's the code. Any pointers in the right direction would be helpful. Thanks.
public class incomePage extends AppCompatActivity {
EditText perYearAmount;
EditText perMonthAmount;
EditText perWeekAmount;
Button totalButton;
TextView addResult;
double year, month, week, sum;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_income_page);
perYearAmount = (EditText) findViewById(R.id.perYearAmount);
perMonthAmount = (EditText) findViewById(R.id.perMonthAmount);
perWeekAmount = (EditText) findViewById(R.id.perWeekAmount);
totalButton = (Button) findViewById(R.id.totalButton);
addResult = (TextView) findViewById(R.id.totalMonthlyIncome);
totalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
year = Double.parseDouble(perYearAmount.getText().toString());
month = Double.parseDouble(perMonthAmount.getText().toString());
week = Double.parseDouble(perWeekAmount.getText().toString());
sum = year + month + week;
addResult.setText(Double.toString(sum));
if (perYearAmount.getText().toString().equals("")) {
return;
}
if (perMonthAmount.getText().toString().equals("")) {
return;
}
if (perWeekAmount.getText().toString().equals("")) {
return;
}
if (totalButton.getText().toString().equals("")) {
return;
}
if (addResult.getText().toString().equals("")) {
return;
}
}
});
}
}
Here's the logCat error. You guys are fast!!
08-24 15:49:31.799 15154-16038/com.example.android.budgeit10 D/OpenGLRenderer: Enabling debug mode 0
08-24 15:49:35.123 15154-16038/com.example.android.budgeit10 D/OpenGLRenderer: endAllStagingAnimators on 0xb8937048 (RippleDrawable) with handle 0xb897a910
08-24 15:49:36.645 15154-16038/com.example.android.budgeit10 D/OpenGLRenderer: endAllStagingAnimators on 0xb89e95a0 (RippleDrawable) with handle 0xb89ebac8
08-24 15:49:50.694 15154-15154/com.example.android.budgeit10 D/AndroidRuntime: Shutting down VM
08-24 15:49:50.695 15154-15154/com.example.android.budgeit10 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.budgeit10, PID: 15154
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.example.android.budgeit10.incomePage$1.onClick(incomePage.java:34)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19884)
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:5343)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
You need to check if the EditText has text in it before trying to parse the (possibly) non-existing text as a numeric value. For example
String yearString = perYearAmount.getText().toString();
if (!"".equals(yearString)) {
year = Double.parseDouble(yearString);
}
Note that I create a temporary variable yearString in order to avoid typing and executing perYearAmount.getText().toString() twice.
Use TextUtils.
totalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(perYearAmount.getText().toString())||
TextUtils.isEmpty(perMonthAmount.getText().toString())||
TextUtils.isEmpty(perWeekAmount.getText().toString())) {
addResult.setText(""); // if any of the fields is empty, add nothing to textview
} else {
year = Double.parseDouble(perYearAmount.getText().toString());
month = Double.parseDouble(perMonthAmount.getText().toString());
week = Double.parseDouble(perWeekAmount.getText().toString());
sum = year + month + week;
addResult.setText(Double.toString(sum));
}
}
});
The crash is caused by a NumberFormatException, which is thrown by the Double.parseDouble() method when the argument is not a parsable double. In your error log, this appears as an empty String:
java.lang.NumberFormatException: Invalid double: ""
To get around this, you could surround any Double.parseDouble() calls in a try/catch block:
try {
Double.parseDouble(anEditText.getText().toString());
} catch (NumberFormatException nfe) {
//anEditText does not contain a parsable Double
}
Edit:
To create an example using your code:
double year = 0;
double month = 0;
try {
year = Double.parseDouble(perYearAmount.getText().toString());
month = Double.parseDouble(perMonthAmount.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(this, "Please enter a valid number and try again", Toast.LENGTH_SHORT).show();
return;
}
double sum = year + month;
//etc...
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());
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.
I am getting a NullPointerException when my code tries to access the value in a key/value pair created by onSaveInstanceState method of Activity class.
I set break points and I know for fact my Bundle is not null and it contains references to my key/values. I dont understand why I am getting this runtime error. Here are my codes for onSaveInstanceState
#Override
protected void onSaveInstanceState(Bundle outState) {
int mPoints = winCount;
int hPoints = loseCount;
String reTextView = resultsTextView.getText().toString();
String pTextView = pointsTextView.getText().toString();
String roTextView = rollTextView.getText().toString();
outState.putInt("MY_POINTS", mPoints);
outState.putInt("HOUSE_POINTS", hPoints);
outState.putString("RESULTS", reTextView);
outState.putString("POINTS", pTextView);
outState.putString("ROLL", roTextView);
super.onSaveInstanceState(outState);
}
and here is my code to restore the state on the onCreate method
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(String.valueOf(savedInstanceState.getString("RESULTS")));
pointsTextView.setText(String.valueOf(savedInstanceState.getString("POINTS")));
rollTextView.setText(String.valueOf(savedInstanceState.getString("ROLL")));
}
I get the runtime error on line that starts with resultsTextView.setText... and here is contents of the savedInstanceState Bundle retrieved from break points in debug mode
Bundle[{RESULTS=Roll Again, MY_POINTS=2, POINTS=Your Point is 8,
HOUSE_POINTS=2,
android:viewHierarchyState=Bundle[{android:Panels=android.util.SparseArray#421c5560,
android:views=android.util.SparseArray#421c5358,
android:ActionBar=android.util.SparseArray#421c57f8}], ROLL=You Rolled
Easy Four}]
as you can see all my strings have a value, the interesting thing is that I dont get the NullPointerException runtime error on int variables (winCount and loseCount) but I am getting it at string values. I appreciate any help.
Update: here is the whole error log from log cat, I have resultsTextView.setText... at line 68 (within the else block on onCreat())
W/dalvikvm(27797): threadid=1: thread exiting with uncaught exception (group=0x418b6700)
E/AndroidRuntime(27797): FATAL EXCEPTION: main
E/AndroidRuntime(27797): java.lang.RuntimeException: Unable to start activity ComponentInfo{…}: java.lang.NullPointerException
E/AndroidRuntime(27797): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime(27797): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime(27797): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3740)
E/AndroidRuntime(27797): at android.app.ActivityThread.access$700(ActivityThread.java:141)
E/AndroidRuntime(27797): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
E/AndroidRuntime(27797): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(27797): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(27797): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(27797): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(27797): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(27797): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(27797): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(27797): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(27797): Caused by: java.lang.NullPointerException
E/AndroidRuntime(27797): at app.package.onCreate(AppName.java:68)
E/AndroidRuntime(27797): at android.app.Activity.performCreate(Activity.java:5133)
E/AndroidRuntime(27797): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(27797): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
E/AndroidRuntime(27797): ... 12 more
here is my whole onCreate method, since many commentators requested to see the whole method. Hope it helps!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(savedInstanceState.getString("RESULTS"));
pointsTextView.setText(savedInstanceState.getString("POINTS"));
rollTextView.setText(savedInstanceState.getString("ROLL"));
}
die1 = (ImageView) findViewById(R.id.imageView1);
die2 = (ImageView) findViewById(R.id.imageView2);
dealButton = (Button) findViewById(R.id.dealButton);
resetButton = (Button) findViewById(R.id.resetButton);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
myPointsTextView = (TextView) findViewById(R.id.myPointstTextView);
housePointsTextView = (TextView) findViewById(R.id.housePointsTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView1);
rollTextView = (TextView) findViewById(R.id.rollTextView);
dealButton.setOnClickListener(dealButtonListener);
resetButton.setOnClickListener(resetButtonLinstener);
//on shake event
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector(new OnShakeListener() {
#Override
public void onShake() {
game(rollDice());
}
});
resultsTextView.setTextColor(Color.BLACK);
myPointsTextView.setText(String.format("%s", winCount));
housePointsTextView.setText(String.format("%s", loseCount));
}
You should initialize your TextViews before calling setText method. So onCreate should be like this:
setContentView(R.layout.activity);
die1 = (ImageView) findViewById(R.id.imageView1);
die2 = (ImageView) findViewById(R.id.imageView2);
dealButton = (Button) findViewById(R.id.dealButton);
resetButton = (Button) findViewById(R.id.resetButton);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
myPointsTextView = (TextView) findViewById(R.id.myPointstTextView);
housePointsTextView = (TextView) findViewById(R.id.housePointsTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView1);
rollTextView = (TextView) findViewById(R.id.rollTextView);
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(savedInstanceState.getString("RESULTS"));
pointsTextView.setText(savedInstanceState.getString("POINTS"));
rollTextView.setText(savedInstanceState.getString("ROLL"));
}
...