我是Android开发的新手。我将代码从我的MainActivity转移到了Fragment类。在我的onCreateView方法中,我调用一个viewFunds()方法来从SQLite动态显示数据。
但是,当我单击该片段的选项卡时,应用程序会在到达removeAllViews行时关闭。每次调用此方法刷新数据时,我都需要先删除AllViews。
由于我也在其他方法中调用ViewFunds(),例如删除数据时,我会调用它来刷新屏幕上的结果。
见下面的代码:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.activity_settings_tab, container, false);
super.onCreate(savedInstanceState);
myDb = new DatabaseHelper(getContext());
btnAddData = (Button) rootview.findViewById(R.id.button_add);
btnviewAll = (Button) rootview.findViewById(R.id.button_viewAll);
btnAddFund = (Button) rootview.findViewById(R.id.button_AddFund);
btnviewUpdate = (Button) rootview.findViewById(R.id.button_update);
editEmergencyFund = (EditText) rootview.findViewById(R.id.edit_EmergencyFund);
editProsperityFund = (EditText) rootview.findViewById(R.id.edit_ProsperityFund);
editRewardFund = (EditText) rootview.findViewById(R.id.edit_RewardFund);
viewAll(); //this is for a button
viewFunds();//this is executed when the fragment is called
return inflater.inflate(R.layout.activity_settings_tab, container, false);
}
public void viewFunds() {
Cursor res2 = myDb.getConfigData();
res2.moveToFirst();
final View linearLayout = getActivity().findViewById(R.id.ll_config);
((LinearLayout) linearLayout.getParent()).removeAllViews(); //clear layout first - LINE WITH ISSUE
((LinearLayout) linearLayout.getParent()).setGravity(Gravity.CENTER);
//some code follows...
}
在removeAllViews行之后编写的这组代码中的最后一行也会导致应用程序关闭:
LinearLayout llh = new LinearLayout(getActivity());
llh.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams lp_llh = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
llh.setLayoutParams(lp_llh);
((LinearLayout) linearLayout.getParent()).addView(llh); //code that causes app to close
提前感谢您的帮助。
答案 0 :(得分:0)
我认为((LinearLayout) linearLayout.getParent()).removeAllViews()
也会移除linearLayout
。试着这样做:
...
ViewParent parent = linearLayout.getParent();
parent.removeAllViews();
parent.setGravity(Gravity.CENTER);
...
parent.addView(llh);
...
答案 1 :(得分:0)
在此处,您返回刚刚在View
末尾创建的新onCreateView
:
return inflater.inflate(R.layout.activity_settings_tab, container, false);
由于您返回的View
非Views
,因此您找到了有效参考,这会导致NPE。将其更改为:
return rootView;