我有一个应用程序可以在我的手机上加载来自sql database
的项目,我的工作是从onResume()
方法加载项目,但是查看它不是最有效的方法,我可以当我查看其他应用程序(例如whatsApp
或contacts
应用程序甚至看不到加载的项目时,总会看到加载的项目。使用我目前的加载方式,我的应用程序不仅速度慢,而且还进行不必要的处理,是否有更好的方式,任何人都知道我可以实现?非常感谢你。
我的Sql数据库类概述:
public class Database extends SQLiteOpenHelper {
//My list that holds my database items(which in my case is receipts)
private ArrayList<Receipt> allReceipts = new ArrayList<>();
public ArrayList<Receipt> getAllReceipts() {
try {
allReceipts.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + Constants.RECEIPT_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if(cursor != null)
if (cursor.moveToFirst()) {
do {
Receipt receipt = new Receipt();
receipt.setId(Integer.parseInt(cursor.getString(0)));
receipt.setMerchantName(cursor.getString(1));
receipt.setPrice(cursor.getString(2));
// Adding contact to list
allReceipts.add(receipt);
} while (cursor.moveToNext());
}
if(cursor != null)
cursor.close();
db.close();
return allReceipts;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_receipts", "" + e);
}
return allReceipts;
}
我的片段收到收据
private void initRecycler()
{
Action<List<ParentListItem>> action = new Action<List<ParentListItem>>() {
@NonNull
@Override
public String id() {
// Return a unique ID.
return "load all receipts";
}
@Nullable
@Override
protected List<ParentListItem> run() throws InterruptedException {
receiptArrayList = database.getAllReceipts();
return getReceipts();
}
@Override
protected void done(@Nullable final List<ParentListItem> receipts) {
progress.stop();
assert receipts != null;
if(receipts.isEmpty()) {
}else {
childAdapterListeners();
adapter = new ReceiptExpandableAdapter(getContext(), receipts, onItemClickListenerCheckBtn, onItemClickListenerDeleteBtn, mOntemClickListenerViewBtn);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
// recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
recyclerView.setAdapter(adapter);
}
}
};
action.execute();
}
@Override
public void onResume()
{
initRecycler();
super.onResume();
}
答案 0 :(得分:0)
您是否尝试过扩展CursorLoader?这是使用数据库数据填充列表的最有效和最正确的方法。