我有代码来简单计算复利。当用户在EditText视图中编辑值时,计算将更改。
public class CompoundInterest extends AppCompatActivity {
TextView mCompBalance;
TextView mBalance;
EditText mYears;
Integer balance;
Integer years;
Double compbalance;
Double interest;
boolean isNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_compound_interest);
interest = 0.025;
mBalance = (TextView) findViewById(R.id.tv_savingsbalance);
mCompBalance = (TextView) findViewById(R.id.tv_interestbalance);
mYears = (EditText) findViewById(R.id.et_years);
System.out.println(mYears.getText().toString());
Resources res = getResources();
balance = Integer.valueOf(res.getString(R.string.savings_balance));
mBalance.setText("£"+ balance);
mYears.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (mYears.getText().toString().matches("\\d+(?:\\.\\d+)?")){
years = Integer.valueOf(mYears.getText().toString());
System.out.println(years);
isNumber =true;
} else {
isNumber =false;
}
if (isNumber){
compbalance = balance*Math.pow(1+interest, years);
mCompBalance.setText("£"+String.format("%.2f", compbalance));
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
}
当我尝试编辑设置计算年数的EditText视图时 - 我收到此错误并且应用程序崩溃:
java.lang.NullPointerException:尝试调用虚方法' int java.lang.Integer.intValue()'在null对象引用上 at com。###。android.citiapp.CompoundInterest $ 1.onTextChanged(CompoundInterest.java:63) 在android.widget.TextView.sendOnTextChanged(TextView.java:8187) 在android.widget.TextView.handleTextChanged(TextView.java:8249) 在android.widget.TextView $ ChangeWatcher.onTextChanged(TextView.java:10371) 在android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1208) 在android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:578) 在android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:230) 在android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:229) 在android.view.inputmethod.BaseInputConnection.deleteSurroundingText(BaseInputConnection.java:251) at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:459) at com.android.internal.view.IInputConnectionWrapper $ MyHandler.handleMessage(IInputConnectionWrapper.java:93) 在android.os.Handler.dispatchMessage(Handler.java:102) 在android.os.Looper.loop(Looper.java:154) 在android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
我不确定发生了什么。
答案 0 :(得分:1)
在charSequence.toString()
功能中使用mYears.getText().toString()
代替onTextChanged
。希望它能帮助或准确指出NullPointerException
的确切位置?