I am trying to display the float value “degrees” as a string in a TextView on my layout, but receive a NullPointerException on tv.setText(mydegrees); I have tried numerous methods to convert the float to a usable string value, but can’t seem to get the TextView to display the float value. Any help would be greatly appreciated!
Note: The degrees is manipulated by an onTouchEvent
TextView from XML:
<TextView
android:id="@+id/current_degrees"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical|center"
android:text="@string/app_name"
android:textColor="#FFFF00" />
Java Code:
float degrees = (float) -65;
String mydegrees = String.format("%.2f", degrees) ;
//...
public void pushClick(View pushClick) {
switch (pushClick.getId()) {
case R.id.btn_push:
TextView tv = (TextView) findViewById(R.id.current_degrees);
tv.setText(mydegrees);
Edit: As
@Jake Kingnoted, in my previous answer I was not paying attention to the details (that yourmydegreemember is aStringinstance.This way the only reason for you to get a
NPEis that yourtv TextViewis null.Please check your layout xml file you use for the activity / renderer / view, and make sure you have there a
TextViewor any extension of it with@+id/current_degrees.Also, your title is very misleading: If you have your
floatdeclared and initialized as above, then there cannot be anyNullPointerException.