所以我目前正在学习Android,事情进展顺利。但是,在尝试构建片段之后,我遇到了一个Null Pointer Exception。我在OnCreateView中声明了我的视图,但没有做任何事情。以下是我的代码。
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());
最后一行虽然很长很难看,却是引发错误的地方。当这是一项独立的活动并且我感到沮丧时,这段代码运作良好。
答案 0 :(得分:1)
在基于片段的应用程序中,onCreate在onCreateView之前调用。因此,当使用长行时,totalMoneyTextView尚未引用任何内容。
查看片段lifecycle diagram。
只有在定义TextView后才应设置totalMoneyTextView的文本,如下所示:
TextView totalMoneyTextView = (TextView) v.findViewById(R.id.TotalMoneyTextView);
totalMoneyTextView.setText(DecimalFormat.getCurrencyInstance().format(Double.parseDouble(TotalMoney)).toString());
答案 1 :(得分:1)
totalMoneyTextView为空。你应该参考[Fragment Lifecycle](http://developer.android.com/guide/components/fragments.html#Creating) onCreate() - > onCreateView().... 因此,您应该在onCreateView()之后处理totalMoneyTextView。