user3124306 user3124306 - 1 year ago 63
Android Question

Null pointer exception with values on text change listener android

I have code to simply calculate compound interest. The calculation will change when the user edits the value in an EditText view.

public class CompoundInterest extends AppCompatActivity {

TextView mCompBalance;
TextView mBalance;
EditText mYears;
Integer balance;
Integer years;
Double compbalance;
Double interest;
boolean isNumber;

protected void onCreate(Bundle savedInstanceState) {

interest = 0.025;

mBalance = (TextView) findViewById(;
mCompBalance = (TextView) findViewById(;
mYears = (EditText) findViewById(;

Resources res = getResources();
balance = Integer.valueOf(res.getString(R.string.savings_balance));
mBalance.setText("£"+ balance);

mYears.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {


public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (mYears.getText().toString().matches("\\d+(?:\\.\\d+)?")){
years = Integer.valueOf(mYears.getText().toString());
isNumber =true;
} else {
isNumber =false;

if (isNumber){
compbalance = balance*Math.pow(1+interest, years);
mCompBalance.setText("£"+String.format("%.2f", compbalance));


public void afterTextChanged(Editable editable) {



When I try to edit the EditText view that sets the number of years for the calculation - I get this error and the app crashes:

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
at android.widget.TextView.sendOnTextChanged(
at android.widget.TextView.handleTextChanged(
at android.widget.TextView$ChangeWatcher.onTextChanged(
at android.text.SpannableStringBuilder.sendTextChanged(
at android.text.SpannableStringBuilder.replace(
at android.text.SpannableStringBuilder.delete(
at android.text.SpannableStringBuilder.delete(
at android.view.inputmethod.BaseInputConnection.deleteSurroundingText(
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(
at java.lang.reflect.Method.invoke(Native Method)

I'm not sure what's going on.

Answer Source

Use charSequence.toString() instead of mYears.getText().toString() in onTextChanged function. Hope it helps or specify exactly where NullPointerException is occurring?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download