我正在尝试添加消息说没有数据和从光标获取数据的recycleview为空
我尝试了许多解决方案,但没有任何效果
这是MainActivity:
public class MainActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int INVENTORY_LOADER_ID = 0;
private CursorAdapter mAdapter;
RecyclerView mRecyclerView;
TextView emptyList;
Cursor inventoryData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.inventories);
emptyList = (TextView) findViewById(R.id.empty_list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new CursorAdapter(this, this, this);
mRecyclerView.setAdapter(mAdapter);
getSupportLoaderManager().initLoader(INVENTORY_LOADER_ID, null, this);
}
@Override
protected void onResume() {
super.onResume();
getSupportLoaderManager().restartLoader(INVENTORY_LOADER_ID, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, final Bundle loaderArgs) {
return new AsyncTaskLoader<Cursor>(this) {
Cursor inventoryData = null;
@Override
protected void onStartLoading() {
if (inventoryData != null) {
emptyList.setVisibility(View.GONE);
deliverResult(inventoryData);
} else {
forceLoad();
}
}
@Override
public Cursor loadInBackground() {
try {
return getContentResolver().query(InventoryContract.InventoryEntry.CONTENT_URI,
null,
null,
null,
InventoryContract.InventoryEntry.COLUMN_ID);
} catch (Exception e) {
Log.e(TAG, "Failed to asynchronously load data.");
e.printStackTrace();
return null;
}
}
public void deliverResult(Cursor data) {
inventoryData = data;
super.deliverResult(data);
}
};
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}
我在oncreate方法中尝试过此方法:
mRecyclerView.setEmptyView(emptyList);
但似乎不适用于recycleview,所以我尝试了:
if (inventoryData.isEmpty()) {
mRecyclerView.setVisibility(View.GONE);
emptyList.setVisibility(View.VISIBLE);
}
else {
mRecyclerView.setVisibility(View.VISIBLE);
emptyList.setVisibility(View.GONE);
}
但我无法解决isEmpty()方法
我在加载程序的onStartLoading()中尝试了以下代码:
@Override
protected void onStartLoading() {
if (inventoryData != null) {
emptyList.setVisibility(View.GONE);
deliverResult(inventoryData);
} else {
forceLoad();
}
}
当recycleview为空且不为空时,emptylist textview已消失,但在所有语句中均已消失
我在上面的代码中尝试了其他方法:
emptyList.setVisibility(View.VISIBLE);
但不起作用
我也试过这个:
if (mAdapter.getItemCount() == 0) {
emptyList.setVisibility(View.VISIBLE);
} else {
emptyList.setVisibility(View.GONE);
}
在oncreate方法中,但应用程序崩溃了
最佳答案
检查游标是否“有效”的方法是
((cursor != null) && (cursor.getCount() > 0))