I know how to get a String from a TextView with toString(), but i would like to understand why if i cast the TextView's text to String by parentheses, it leads Android to crash at runtime ?
e.g "String text = (String)((TextView)findViewById(R.id.myTextViewId)).getText();"
This is because getText() returns CharSequence (which you can cast to Spannable or Editable in some cases) which you cannot cast to string directly.
Using toString() gives you a conversion to string class.
From android developer documentation:
public CharSequence getText ()
Return the text the TextView is displaying. If setText() was called with an argument of BufferType.SPANNABLE or BufferType.EDITABLE, you can cast the return value from this method to Spannable or Editable, respectively. Note: The content of the return value should not be modified. If you want a modifiable one, you should make your own copy first.
Source: http://developer.android.com/reference/android/widget/TextView.html
When you use the “toString()” you’re actually doing a conversion. You’re calling the objects toString() method who understands what the object is and how to convert it to a string which “makes sense”.
When you use the “(String)” syntax you’re using a cast which doe NO conversion. It just says take the object and, with no changes at all, treat it as though it were a String. Since the object is not a String, you can get errors calling methods which do not apply on what the object actually is.
try this...
String text = ((TextView)findViewById(R.id.myTextViewId)).getText().toString();
because getText() returns CharSequence object
Related
I am trying to retrieve a field from a JsonObject as String. This field "agentid" sometimes come as long and sometimes as String. When it comes as a long, I get an exception
java.lang.ClassCastException: java.lang.Double cannot be cast to
java.lang.CharSequence
Following is the statement which hits this exception:
// get agent ID
String agentID = parameterJson.getString("agentid");
How to safely get the content of this field "agentid" and store it as String in Java?
Depnding on which JsonObject class you are using, I'm assuming it has a get() or getObject() method that returns an Object. You can call that method followed by .toString().
For example:
String agentID = parameterJson.getObject("agentid").toString();
There are different things you can do:
For the first you can do Double.toString(...) because the Exception tells you why the error appears.
Also you can do String.valueOf(Object) that can also handle every object you pass in there or you just use the toString method when you get an Object from the JSON.
You also are able to just use the getDouble instead of getString and use the type double.
you can use this to convert it to string.
String agentID = String.valueOf(parameterJson.getString("agentid"));
txtRate.setText(emp.getRate());
I cant display the data from the csv file in the textbox because it keeps on saying
double cannot be converted to java.lang.String.
My method is public Double getRate()
If i try to make is public String it would work but i cant use the value for calculation because it already has been set
to String
The class you are working on contains method with signature setText(String value) but there's no method with signature setText(Double value).
When you call a method compiler checks the parameter type and tries to recognize what method should be in use for this case.
As you are using Double type for the parameter, the compiler is unable to find a method with signature setText(Double value) and you get the error you have reported in your question.
To overcome this issue, convert your parameter from Double to String type before passing it to setText method.
txtRate.setText(String.valueOf(emp.getRate()));
or
txtRate.setText(emp.getRate().toString());
But the second approach may throw NullPointerException if emp.getRate() returns null, so the first approach is safer.
In case you want to format your numbers in a fancy way, consider this tutorial: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Displaying data on the textbox require variable to be string, But calculation require variable to be double the answer is when displaying cast to string and when calculation don't
I'm trying to extract an int from an Intent I created, but the second one throws up an error "Cannot convert java.lang.String to int", while the first one does not. Why does this happen?
Thanks
to get an int value you need to use
getIntent().getIntExtra("x", 0)
or
getIntent().getExtras().getInt("x")
The first one is:
(Integer)getIntent().getExtras().get(x)
This retrieves an Object based on the key x and attempts to cast that to be an Integer. If get() returns something else, you crash at runtime with a ClassCastException.
The second one is:
(Integer)getIntent().getStringExtra(x)
This retrieves a String based on the key x and attempts to cast that as an Integer. It is possible that an Object might be an Integer, which is why the first one compiles but might fail at runtime. It is not possible that a String is an Integer. Hence, this fails at compile time.
The right answer, as Mr. Oleg notes, is to call getIntExtra() on the Intent or getInt() on the Bundle returned by getExtras().
It's all about casting.
getIntent().getExtras().get(x) returns an Object type.
While (Integer)getIntent().getStringExtra(x) returns an String type Object.
If you recall(or just learning), every Java Class extends Object by default and thos get it's mehtods such as toString().
This is why you can try to cast Object to ANY class. try - but if it fails you will know it only at run-time.
On the other hand, a String is a class that already extends Object and has nothing to do with Integer and it's own values and properties.
So, when you try to cast from a String to a Integer you get an error.
The best solution was already published.
I'll just add that you can still do this:
getInteger(getIntent().getStringExtra(x));
We know that in Java when a method returns a value we have to store that value in a variable of that type.
For example the getString() returns String and we store that value in a String variable.
In J2ME I was trying to create radio-buttons i.e. using the ChoiceGroup class.
ChoiceGroup radio;
radio=new ChoiceGroup("Select your Color",Choice.EXCLUSIVE);
radio.append("Red",null);
radio.append("White",null);
radio.append("Green",null);
In book the signature of append() method is
int append(String string, Image img)
I want to ask that even though I am not storing the integer value returned from the append() method my code runs perfectly.
I am using Wireless toolkit 2.5.2
Note the book has not given any reasons for this and that's why I asked here.
We know that in Java when a method returns a value we have to store that value in a variable of that type.
Every part of that sentence is false.
You should get a better book.
ChoiceGroup append method returns the assigned index of the element. If you don't intend to use it, it's OK to ignore returned value.
Method signature - return value and parameters have meaning clearly defined in API documentation:
public int append(String stringPart,
Image imagePart)
Appends an element to the ChoiceGroup.
Specified by:
append in interface Choice
Parameters:
stringPart - the string part of the element to be added
imagePart - the image part of the element to be added,
or null if there is no image part
Returns:
the assigned index of the element
Throws:
NullPointerException - if stringPart is null
If you want to use the return value then you store in a variable or object.If you dont want then leave it .Its not a mistake in java
I appear to have a fundamental gap in my understanding of an EditText object. I have an Activity+Layout with a single EditText object. After I type a few characters into the EditText object and hit the Enter key, I retrieve the text in my onKey() listener. When I use the toString() method to retrieve the text I get back a weird string like:
android.widget.EditText#43749ff0
Despite the fact the EditText.mText property does show the string I entered, "123" during my tests. Why is toString() returning a different result and what appears to be some kind of "uninitalize" value? How do I get the desired string currently in the mText property and what is that strange value?
-- roschler
Passing glance at the API suggests you should use the getText() method. toString() is a general method that applies to Object and all its subclasses (i.e., everything that isn't a primitive, to my knowledge). It's often overridden to supply more useful strings, but by default, it reports something just like what you posted - a sparse description and the object's hashcode. To be clear, the API defines toString() as:
getClass().getName() + '#' + Integer.toHexString(hashCode())
You can't use the 'toString'-method on this, use 'getText().toString()' in stead.
You are calling toString() on a View Object, which probably does not have a toString() defined.
I believe you want to call this:
editText.getText().toString()
Try EditText.getText().toString()
Take a moment to read the java API: http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#toString%28%29
toString
public String toString() Returns a string representation of the object.
In general, the toString method
returns a string that "textually
represents" this object. The result
should be a concise but informative
representation that is easy for a
person to read. It is recommended that
all subclasses override this method.
The toString method for class Object
returns a string consisting of the
name of the class of which the object
is an instance, the at-sign character
`#', and the unsigned hexadecimal
representation of the hash code of the
object. In other words, this method
returns a string equal to the value
of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Returns: a string representation of
the object.