Brian Brian - 5 months ago 18
Java Question

I have a Method invocation 'simpleEditText.getText()' may produce 'java.lang.NullPointerException' error and would like it removed

Very new to Android Studio. Working on first app. I would like to fix the line of code below so I don't get the error: I have a Method invocation 'simpleEditText.getText()' may produce 'java.lang.NullPointerException' error and would like it removed. Any suggestions would be great. I think this means I need to check if simpleEditText has a null value before I getText?

/*
* Retrieve Edit Text Values
*/
EditText simpleEditText = (EditText) findViewById(R.id.editLat);
String strValue = simpleEditText.getText().toString();


This is the XML resource associated with editLat:

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:singleLine="true"
android:lines="1"
android:textSize="15dp"
android:hint="@string/lat_hint"
android:id="@+id/editLat"
android:layout_below="@+id/textAsset"
android:layout_toEndOf="@+id/textView3" />

Answer

You can add a safety check whenever you initialize something and are unsure whether it'll be null:

String strValue;
EditText simpleEditText = (EditText) findViewById(R.id.editLat);
if(simpleEditText != null && !TextUtils.isEmpty(simpleEditText.getText())){
    strValue = simpleEditText.getText().toString();
}