我有一个类,我通过标准的 get/set 方法分配字符串值。设置值后,它按预期返回它们。当我在另一个片段中调用类值时,它们返回 null。我似乎无法弄清楚。
我如何设置课程并设置值。
public class BasicInfo_Assets_Fragment extends Fragment {
View view
public static Store_Model store_model = null;
...
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_basic_info, container, false);
...
zipCode = zip.getText().toString();
// set info
store_model = new Store_Model();
store_model.setZip(zipCode);
Log.v("STORE" , "Zip: " + store_model.getZip());
...
Log.v 完全按照预期打印出:“Zip: 47564”。但是,当我像这样在另一个片段中调用该类时,它会给我一个错误。
public class Options_ListFragment extends ListFragment {
View view;
public static Store_Model store_model = BasicInfo_Assets_Fragment.store_model;
....
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_options, container, false);
Log.v("STORE", "Zip: " + store_model.getZip()); <!--- ERROR
如代码中所述,尝试提取该值会给我一个空指针异常。我不明白这个类是如何失去它的价值的。也许我只需要另一双眼睛。我在这里先向您的帮助表示感谢
编辑
谢谢@Juan Jose Fidalgo 和@SJuan76。我想通了,我在 Options_ListFragment 中将代码更改为以下内容:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_options, container, false);
if (BasicInfo_Assets_Fragment.store_model != null) {
LinearLayout ll = (LinearLayout) view
.findViewById(R.id.assets_store_info);
ll.setVisibility(View.VISIBLE);
store = (TextView) view.findViewById(R.id.store);
phone = (TextView) view.findViewById(R.id.phone);
address = (TextView) view.findViewById(R.id.address);
city = (TextView) view.findViewById(R.id.city);
zip = (TextView) view.findViewById(R.id.zip);
state = (TextView) view.findViewById(R.id.state);
getStoreInfo();
}
public void getStoreInfo() {
String mStore = BasicInfo_Assets_Fragment.store_model.getStoreNum();
String mPhone = BasicInfo_Assets_Fragment.store_model.getPhoneNum();
String mAddress = BasicInfo_Assets_Fragment.store_model.getAddress();
String mCity = BasicInfo_Assets_Fragment.store_model.getCity();
String mZip = BasicInfo_Assets_Fragment.store_model.getZip();
String mState = BasicInfo_Assets_Fragment.store_model.getState();
store.setText("Store #: " + mStore);
phone.setText("Phone #: " + mPhone);
address.setText("Address: " + mAddress);
city.setText("City: " + mCity);
zip.setText("Zip: " + mZip);
state.setText("State: " + mState);
}