Convert from Double to String in Android - java

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?

Related

Casting String to Integer not working, throwing NumberFormatException

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());

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 !!

How to compare input text with string array in android studio? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am new to app development and I have a problem with coding in android studio. I want to compare an input text with a string in the string array. For some reason it won't work. When i try the java code in eclipse it works.
I already run the debugger and the inputmessage is "Banana". The debugger also shows that message = "Banana" when it is in CheckAnswer(message). But for some reason the function isn't returning "Right". It returns "wrong"
I hope somebody can help me.
Here is my code:
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
String message2 = CheckAnswer(message);
intent.putExtra(CORRECT_MESSAGE, message2);
startActivity(intent);
}
public static String CheckAnswer(String string) {
String rightanswer[] = {"Apple", "Banana", "Coconut"};
String answer = null;
for (int i = 0; i <= rightanswer.length-1; i++) {
if (string == rightanswer[i]) {
answer = "Right!!";
break;
}
else answer = "Wrong.";
}
return answer;
}
The correct way of comparing two strings is with equals() function not ==
So Change :
if (string == rightanswer[i]) {
answer = "Right!!";
break;
}
to:
if (string.equals(rightanswer[i])) {
answer = "Right!!";
break;
}
When you are comparing Strings in Java, it is best to use the String's equals()method which looks like this:
if(someValue.equals(somethingElse){}
I hope this helps!

passing GPS coordinates to activity

I am trying to pass longitude and latitude variables into another activity for the Google maps fragment. So far I have managed to do this
Intent i = new Intent(Main.this, Main2.class);
i.putExtra(Double.toString(gettextLong), xLocation.getLongitude());
i.putExtra(Double.toString(gettextLat), xLocation.getLatitude());'
How do I receive it in the other activity?
Give relevant key like
Intent i = new Intent(Main.this, Main2.class);
i.putExtra("longitude", xLocation.getLongitude());
i.putExtra("latitude", xLocation.getLatitude());
and in Main2 Activity
Bundle extras = getIntent().getExtras();
if(extras !=null && extras.getDouble("latitude") != null && extras.getDouble("longitude") != null) {
double lat = extras.getDouble("latitude");
double lng = extras.getDouble("longitude");
}
Try:
Intent i = new Intent(Main.this, Main2.class);
i.putExtra("lon", xLocation.getLongitude());
i.putExtra("lat", xLocation.getLatitude());
Like this:
int lat = getIntent().getExtras().getDouble("lat");
int lon = getIntent().getExtras().getDouble("lon");
Use getIntent() and getDoubleExtra() in yours second activity. But pass it in different way. First argument in putExtra should be some String but you have to know him, it is needed to use later in second activity. Like:
public static final String FIRST = "firstArgument";
i.putExtra(FIRST, xLocation.getLongitude());
And in Main2:
double i = getIntent().getDoubleExtra(Main.FIRST, 0);

Categories

Resources