Reputation: 305
So I'm currently learning Android and things are going well. However, after attempting to build a fragment, I am running into a Null Pointer Exception. I declared my Views in OnCreateView and that did nothing. Posted below is my code.
private String TotalMoney;
private BigDecimal BigDecimalTotalMoney;
private SharedPreferences settings;
private SharedPreferences.Editor prefEditor;
@SuppressLint("SimpleDateFormat")
private SimpleDateFormat ft = new SimpleDateFormat ("E MM.dd.yyyy 'at' hh:mm a");
private TextView totalMoneyTextView;
private EditText Submission;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.wallettracker, container, false);
TextView totalMoneyTextView = (TextView) v.findViewById(R.id.TotalMoneyTextView);
EditText Submission = (EditText) v.findViewById(R.id.editTextMoney);
Button submitButton = (Button) v.findViewById(R.id.submitButton);
TextView dateTextView = (TextView) v.findViewById(R.id.dateTextView);
Button subtractButton = (Button) v.findViewById(R.id.subtractButton);
return v;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = this.getActivity().getSharedPreferences("Money Data", 0);
TotalMoney = settings.getString("TotalMoney", "0.00");
totalMoneyTextView.setText(DecimalFormat.getCurrencyInstance().format(Double.parseDouble(TotalMoney)).toString());
The final line, while long and very unsightly, is where the error is thrown. This code worked quite well when it was a standalone activity and I'm getting frustrated.
Upvotes: 2
Views: 126
Reputation: 5411
In a fragment based application, onCreate is called before onCreateView. So totalMoneyTextView does not yet refer to anything when your long line is used.
Take a look at the fragment lifecycle diagram.
You should set the text for totalMoneyTextView only after you have defined the TextView, as shown below:
TextView totalMoneyTextView = (TextView) v.findViewById(R.id.TotalMoneyTextView);
totalMoneyTextView.setText(DecimalFormat.getCurrencyInstance().format(Double.parseDouble(TotalMoney)).toString());
Upvotes: 1
Reputation: 1093
totalMoneyTextView is null. You should reference [Fragment Lifecycle] (http://developer.android.com/guide/components/fragments.html#Creating) onCreate() -> onCreateView() .... Therefore you should handle totalMoneyTextView after onCreateView().
Upvotes: 1