#
xutils3很好用,刚接触用它写了个操作sqlite的demo,不过一开始只要运行便会崩溃,因为utils的dbManerger只有在执行save或saveOrUpdate以及saveBindingId方法时才会创建表,所以以为是表不存在故而报错。后来在javabean添加了onCreate注解,save时报错“表已存在”。经过调试分析,原来是因为没有数据时返回的list为null,所以adapter抛出异常
附上EntityDao,及activity修改处
xutils3 github地址:https://github.com/wyouflf/xUtils3
EtityDao:
private static EntityDao INSTANCE;
public static EntityDao getInstance() {
if (INSTANCE == null)
INSTANCE = new EntityDao();
return INSTANCE;
}
public EntityDao() {
dbManager = DBHelper.getInstance().getDbManager();
}
/**
* @param c 查找的类型
* @return 所有记录
* @throws DbException
*/
public List<?> findAll(Class<?> c) throws DbException {
return dbManager.findAll(c);
}
Activity:
private List<DemoEntity> data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lv_list);
try {
if (EntityDao.getInstance().findAll(DemoEntity.class) != null)
data = (List<DemoEntity>) EntityDao.getInstance().findAll(DemoEntity.class);
} catch (DbException e) {
e.printStackTrace();
} finally {
adapter = new MyAdapter(this, R.layout.layout_item, data, this);
listView.setAdapter(adapter);
}
}