在ViewPager Fragment中,光标加载器只能工作一次,而在活动中,它会随着数据库中的数据更改显示数据。
在StackOverflow上也有很多答案,表明这可能是支持库的问题,但我已经为所有库导入了v4库。 我的片段代码如下所示:
public class Scenes extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int SCENE_LOADER = 0;
ListView listView;
FloatingActionButton fabScenes;
private SceneAdapter mAdapter;
EditText sceneNameText, hours, minutes;
String sceneText;
int hrs, minuts, duration=0;
public Scenes() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().getSupportLoaderManager().initLoader(SCENE_LOADER, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_scenes, container, false);
fabScenes = view.findViewById(R.id.fabScene);
listView = view.findViewById(R.id.listScenes);
mAdapter = new SceneAdapter(getActivity(), null);
listView.setAdapter(mAdapter);
fabScenes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
insertScene();
}
});
return view;
}
/**
* Helper method to insert hardcoded pet data into the database. For debugging purposes only.
*/
private void insertScene() {
ContentValues values = new ContentValues();
values.put(ProgramContract.SceneEntry.COLUMN_NAME, "Kitchen");
values.put(ProgramContract.SceneEntry.COLUMN_DURATION, "40");
Uri newUri = getActivity().getContentResolver().insert(ProgramContract.SceneEntry.CONTENT_URI, values);
}
@NonNull
@Override
public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) {
String[] projection = {
ProgramContract.SceneEntry._ID,
ProgramContract.SceneEntry.COLUMN_NAME,
ProgramContract.SceneEntry.COLUMN_DURATION};
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(getActivity(), // Parent activity context
ProgramContract.SceneEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null);
} // Default sort order}
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}