I'm new to Android development and I'm trying to convert a string to a double, then round it off to 2 decimal places, then convert it back to string to display in a ListView. Here is my code:
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent){
String expenseCategory = getItem(position).getExpenseCategory();
String expenseAmount = getItem(position).getExpenseAmount();
String expenseEntryDate = getItem(position).getExpenseTodayEntry();
Double eA = Double.parseDouble(expenseAmount);
String eAnew = String.format("%.2f",eA);
Expenses ex = new Expenses(eAnew, expenseCategory, expenseEntryDate);
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
TextView expenseCategoryTextView = (TextView) convertView.findViewById(R.id.CategoryHistoryTV);
TextView expenseDateEntryTextView = (TextView) convertView.findViewById(R.id.DateHistoryTV);
TextView expenseAmountTextView = (TextView) convertView.findViewById(R.id.AmountHistoryTV);
expenseCategoryTextView.setText(expenseCategory);
expenseDateEntryTextView.setText(expenseEntryDate);
expenseAmountTextView.setText(eAnew);
expenseCategoryTextView.setTextColor(Color.RED);
expenseDateEntryTextView.setTextColor(Color.RED);
expenseAmountTextView.setTextColor(Color.RED);
return convertView;
}
And here is the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
it runs properly without:
Double eA = Double.parseDouble(expenseAmount);
String eAnew = String.format("%.2f",eA);
But instead it gives me an output like
1000.0000
I understand that it may be bad design, however declaring the expenseAmount as double does not work in other areas of my code for various reasons.
I've tried to use a condition to "catch" the null value as the error says but so far nothing works.