Casting String to Integer not working, throwing NumberFormatException - java

The value of walletBalance is a string, eg "150.0".
I am trying to display an error message in form of a toast in another activity(SuccessActivity) is the amount to be withdrawn from the user is less than the wallet balance. I keep getting NumberFormatException error for the value of i, so i decided to use a try catch block but it still doesnt work. Here is the method below.
private void checkWalletBalance(int amount, Context context){
String walletBalance = Preferences.getBalance(context);
try {
int i = Integer.parseInt(walletBalance.trim());
if(amount < i){
Intent intent = new Intent(getBaseContext(), SuccessActivity.class);
startActivity(intent);
Toast. makeText(ActivityHome.this,"Insufficient Wallet Balance",Toast. LENGTH_LONG).show();
}
}
catch (NumberFormatException nfe){
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
Alos, I want to display a toast in the success Activity, If the condition i true. here is the code in success activity to display the toast message.
private void insufficientError(){
Intent intent = getIntent();
intent.getExtras();
Toast.makeText(SuccessActivity.this,"Insufficient Balance",Toast.LENGTH_LONG).show();
}

Like #Blackbelt commented, you are trying to parse a double string and not an integer.
Therefore, you need to do the following:
double amount = Double.parseDouble(walletBalance.trim());

You could use either of the following-
Double.valueOf(walletBalance.trim());
Double.parseDouble(walletBalance.trim());
And then if you want to convert them to Integer/int like this -
Integer i = Double.valueOf(walletBalance.trim()).intValue();
int i = (int) Double.parseDouble(walletBalance.trim());

NumberFormatException - Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Don't
int i = Integer.parseInt(walletBalance.trim()); //walletBalance.trim() ==150.0
Do
int i = (int) Double.parseDouble(walletBalance.trim());

Related

Java cast a string as a double [duplicate]

This question already has answers here:
Convert String to double in Java
(14 answers)
Closed 1 year ago.
Im creating a basic GUI that takes the amount entered by a user and subtracts it with a pre existing amount. However it will not let me to run the one below as I get an error of String cannot be converted to double. Using the parseInt method won't work here as im using the getText Method.
String message = txtaMessage.getText();
String transaction1 = txtfAmountTransfer.getText();
String reciever = txtfTransferTo.getText();
lblOutputTransferInfo.setText("Your Amount of "+transaction1+" has been sent to "+reciever+" .");
lblOutputTransferMsg.setText("With a Message: "+ message);
double balance = 5123.84;
String newBalance = balance - transaction1;//this will not work but the concept I need
lblSavingsBalance.setText(newBalance);
It won't work because here transcation1 is a string and whereas balance is double. In java, we don't have a method to subtract string from double. So, First, you need to convert transaction1 into double. I suggest you to
Double newBalance = balance - Double.parseDouble(transcation1);
then lblSavingsBalance.setText(newBalance.toString()); to convert newBalance double value to string
Hope it works fine...
If getText returns String below code will work.
String message = txtaMessage.getText();
String transaction1 = txtfAmountTransfer.getText();
String reciever = txtfTransferTo.getText();
lblOutputTransferInfo.setText("Your Amount of "+transaction1+" has been sent to "+reciever+" .");
lblOutputTransferMsg.setText("With a Message: "+ message);
double balance = 5123.84;
balance = balance - Double.parseDouble(transaction1);//this will not work but the concept I need
lblSavingsBalance.setText(String.valueOf(balance));
If you are using android,
(Assuming txtaMessage, transaction1, reciever are either TextView objects or EditText objects)
txtaMessage.getText(); //This won't return a String. This will return a CharSequence.
You have to convert it to string. So the correct method is,
String message = txtaMessage.getText().toString();
Do this for all EditTexts and TextViews.
Then transaction1 shoud be converted as Double
Double.parseDouble(transaction1);
After that you can substract transtraction1 from balance and assign it to the original balance.
balance = balance - Double.parseDouble(transaction1)
The full version of android code is below.
String message = txtaMessage.getText().toString();
String transaction1 = txtfAmountTransfer.getText().toString();
String reciever = txtfTransferTo.getText().toString();
lblOutputTransferInfo.setText("Your Amount of "+transaction1+" has been sent to "+reciever+" .");
lblOutputTransferMsg.setText("With a Message: "+ message);
double balance = 5123.84;
balance = (balance - Double.parseDouble(transaction1));//this will not work but the concept I need
lblSavingsBalance.setText(String.valueOf(balance));
If the transaction1 value is not a number, An Exception will occur. So wrapping it with try/ catch is a good idea.
try {
balance = (balance - Double.parseDouble(transaction1));//this will not work but the concept I need
lblSavingsBalance.setText(String.valueOf(balance));
} catch (NumberFormatException e) {
//Send error message like showing a toast
e.printStackTrace();
}

putExtra ("int", value) but getIntent wrong

Please help with this code
I have a button in the first activite I want when I press it to send text and number to another activity
But I want to display the text in TextView 1 and the number in TextView2
I succeeded in sending the text to its specified location but I have a problem sending the number
I experimented with many of the codes and the failures persisted.
This is the last code you used to successfully send the text but failed to send the number
The code from the first activity:
Intent intent = new Intent( this, Order.class );
String keyIdentifer = null;
intent.putExtra( "String", text );
intent.putExtra( "Int", price );
startActivity( intent );
The code from the second Activity:
TextView userName = (TextView)findViewById(R.id.the_order);
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String j =(String) b.get("String");
userName.setText(j);
}
TextView userName1 = (TextView)findViewById(R.id.price);
Intent ii= getIntent();
Bundle bb = ii.getExtras();
if(bb!=null)
{
int jj =(int) bb.get("Int");
userName1.setText(jj);
}
get the int as:
int jj = yourintent.getIntExtra("Int");
You don't need to get the bundle first, this way is a wrap around the thing that you are doing and gives you the same value
One other error is that you are setting an int value inside the setText method.
This method accepts int but it expects the int value to be a resource identifier. Since you are passing a value which is not a resource id, it will crash saying resource not found.
try
userName1.setText(String.valueOf(jj));
Basically if you want to set the TextView value as an int, never forget to convert it to string. The error thrown is horrendously worded and doesn't remotely indicate that this is the actual issue.
Intent intent = new Intent(this, Activity.class);
intent.putExtra("Int", 4);
startActivity(intent);
In the activity its going to...
Intent intent = getIntent;
int getInt = intent.getIntExtra("Int");
System.out.println(getInt);
set a testview:
textView.setText(String.valueOf(getInt);
Your issue is you are setting an Int value in editText:
int jj =(int) bb.get("Int");
userName1.setText(jj);
Just do this when setting int value:
int jj =(int) bb.get("Int");
userName1.setText(jj+"");
just change
bb.get("Int");
to
bb.getInt("Int");

Format exeption errors

I have 2 activities. Activity A sends a Number to activity B and activity recieves and uses the Number. The problem is that activity B produces FormatExeption errors.
Activty A code:
EditText set_limit = findViewById(R.id.editText2);
Bundle set_limit_basic = new Bundle();
set_limit_basic.putString("limit_basic", String.valueOf(set_limit));
Intent Aintent = new Intent(A.this, B.class);
Aintent.putExtras(set_limit_basic);
startActivity(Aintent);
Activity B code:
Bundle set_limit_basic = getIntent().getExtras();
if (set_limit_basic != null) {
String B_string = set_limit_basic.getString("limit_basic");
if ( B_string .trim().length() == 0){
limit_number = Integer.parseInt(B_string);
Several points:
You shouldn't be converting set_limit to a string; set_limit is an EditText widget. Instead, you should be putting the contents of the view (the text it is displaying).
There's no reason to explicitly construct your own extras bundle. Just use one of the putExtra methods defined in the Intent class.
The error checking is probably better handled in activity A instead of activity B.
You seem to have a logic error in activity B, in that you are only attempting to parse the limit number when the trimmed text is empty. That seems backwards.
Putting all this together, I'd rewrite your code as follows:
Activity A:
EditText set_limit = findViewById(R.id.editText2);
CharSequence text = set_limit.getText();
if (TextUtils.isEmpty(text)) {
// handle case of no text
} else {
try {
int limit_number = Integer.parseInt(text.toString());
Intent intent = new Intent(A.this, B.class);
intent.putExtra("limit_basic", limit_number);
startActivity(intent);
} catch (NumberFormatException e) {
// handle case of improperly formatted text
}
}
Activity B:
limit_number = getIntExtra("limit_basic", -1 /* or other default value */);
// or, if you want to explicitly check for presence of the extra:
if (hasExtra("limit_basic")) {
limit_number = getIntExtra("limit_basic", -1);
}
In 1st Activity you are trying to use String.valueOf(edittext);
( set_limit is a variable of type EditText so the string value will be #djfjckckc78 something like this...which is surely not a number)
try
String.valueOf(set_limit.getText().toString());
i.e,
set_limit_basic.putString("limit_basic",String.valueOf(set_limit.getText().toString()));
and also in Activity B,
if ( B_string .trim().length() > 0){
}
If you try to convert String.valueOf(variable) to a number it will throw a NumberFormatException at runtime because that string aint a number !!

Creating a Search Button (Double cannot converted to String)

private void searchProduct()
{
try {
Product p = new Product();
//Read data
p.setId(Double.parseDouble(textID.getText()));
//Display data
textDescription.setText(String.valueOf(p.getDescription()));
textPrice.setText(String.valueOf(p.getUnitPrice()));
textUOM.setText(String.valueOf(p.getUnitOfMeasurement()));
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(this.frame, "ID must be number", "Error",JOptionPane.ERROR_MESSAGE);
}
}
Hello recently I tried to put a button "Search" to find a product than equals to ID, but I don't know how to parse the ID than comes from the product class, I have a error.
Does the textID.getText() actually is a parseable double string? For instance "10.1" do but "10.1 " no.
Always I did this kind of conversion I use trim() to remove this extra white spaces as follow:
String stringValue = textID.getText();
if(stringValue != null) {
stringValue = stringValue.trim();
}
double doubleValue = Double.parseDouble(stringValue);
Se here http://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#valueOf-java.lang.String- how to avoid NumberFormatException using a regular expression to text you string before try to convert it to double.

Convert from Double to String in Android

I am trying to convert a value from Double to String in an Android Activity.I can get this to work with my first example here below (working in the sense of no squigly error from Eclipse). However I am curious as to why the second example is not working.
First example
balance = (TextView) findViewById(R.id.textViewCardBalance);
Intent intent = getIntent();
if (intent.getExtras() != null) {
balance.setText(String.valueOf((long)intent.getDoubleExtra("balance", 0.00)));
}
Second example below not working (Error: "Cannot cast from Double to Long"
balance = (TextView) findViewById(R.id.textViewCardBalance);
Double cardBalance;
Intent intent = getIntent();
if (intent.getExtras() != null) {
cardBalance = intent.getDoubleExtra("balance", 0.00);
balance.setText(String.valueOf((long)cardBalance);
}
Would anyone know how I can get the second example to work as I need to log the value retrieved from the intent before passing it to the TextView.
Thanks
Why can't you do this?
balance.setText(cardBalance + "");
String yourDoubleString = String.valueOf(yourDouble);
in your case:
String yourDoubleString = String.valueOf(intent.getDoubleExtra("balance", 0.00));
using String v = ""+String.valueOf((long)cardBalance) not work?

Categories

Resources