【发布时间】:2020-04-06 09:53:35
【问题描述】:
我在应用程序启动时填充的 Fragment 中有一个 ListView。 我在我的 newInstance 方法中将 ParcelableArrayList 放在了一个 Bundle 中,然后在我的 Activity 的 newInstance 方法中传递了 ArrayList(这是从 SQLite 数据库中读取的数据)后,我将它返回到我的 OnCreateView 中。
这部分有效,因为我在 Fragment 中正确显示了我的数据。
我实现了一个从表中删除所有数据的按钮,现在我想在清理表后更新我的视图。 删除所有按钮在我的主要活动中处理,我调用我的数据库处理程序来清空表。
最好的方法是什么?以下是与我相关的代码部分:
我的片段类:
public class MainFragment extends Fragment {
public static final String RECETTES_KEY = "recettes_key";
private List<Recette> mRecettes;
private ListView mListView;
public MainFragment() {
// Required empty public constructor
}
public static MainFragment newInstance(List<Recette> r) {
MainFragment fragment = new MainFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(RECETTES_KEY, (ArrayList<? extends Parcelable>) r);
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRecettes = getArguments().getParcelableArrayList(RECETTES_KEY);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
configureListView();
}
// Configure ListView
private void configureListView(){
this.mListView = getView().findViewById(R.id.activity_main_list_view);
RecetteAdapter adapter = new RecetteAdapter(getContext(), mRecettes);
mListView.setAdapter(adapter);
}
}
我的主要活动中的相关部分: 这是在我的 OnCreate 方法中:
mDatabaseHandler = new DatabaseHandler(this);
mRecettes = mDatabaseHandler.readRecettes();
mDatabaseHandler.close();
这是我用来显示片段的方法:
if (this.mMainFragment == null) this.mMainFragment = MainFragment.newInstance(mRecettes);
this.startTransactionFragment(this.mMainFragment);
如果我应该添加更多代码,请告诉我,这是我第一次发布 :) 露西尔
【问题讨论】:
-
你是说有一个按钮可以删除所有数据,你也想从 UI 中删除这些数据,对吧?
-
我希望我的 UI 能够更新,并且在我清空数据库后什么也不显示。如果我添加一个元素或只是从我的数据库中删除一个元素,它也应该可以工作。我希望 UI 始终与我的数据库内容保持一致
-
更改适配器内部的数据后,在适配器上调用 notifydatasetChanged()
标签: java android android-fragments android-activity android-sqlite