SQLite异常:不存在tblPhong表,求排查Android数据库代码问题
问题排查与解决方案
核心原因:自定义Application未注册
你的Data类继承了Application,但如果没有在AndroidManifest.xml中声明这个自定义Application,系统会默认使用原生Application,导致Data.onCreate()完全不会执行——这意味着createTable()方法从未被调用,tblPhong表根本没被创建,直接执行查询自然会报错。
修复步骤
打开AndroidManifest.xml,在<application>标签中添加android:name=".Data":
<application android:name=".Data" <!-- 新增这一行 --> android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.YourAppName"> <!-- 其他组件声明 --> </application>
其他潜在问题与优化
Cursor未关闭导致资源泄漏
在countPhong()和getPhongTro()方法中,你打开了Cursor但未关闭,会造成内存泄漏。修改如下:public int countPhong(){ String sql = "SELECT * FROM tblPhong"; db = openDB(); Cursor cursor = db.rawQuery(sql,null); int count = cursor.getCount(); cursor.close(); // 关闭Cursor db.close(); return count; } public ArrayList<PhongTro> getPhongTro(){ ArrayList<PhongTro> tmp = new ArrayList<>(); String sql = "SELECT * FROM tblPhong"; db = openDB(); Cursor cursor = db.rawQuery(sql, null); while (cursor.moveToNext()){ int maPhong = cursor.getInt(0); int tang = cursor.getInt(1); int dienTich = cursor.getInt(2); int giaTien = cursor.getInt(3); String mota = cursor.getString(4); PhongTro phongtro = new PhongTro(maPhong,tang,dienTich,giaTien,mota); tmp.add(phongtro); } cursor.close(); // 关闭Cursor db.close(); return tmp; }Adapter中setText类型错误
holder.tvPhong.setText(phongtro.getMaphong());传入的是int类型,Android会将其识别为字符串资源ID,导致显示异常或崩溃,需转为字符串:holder.tvPhong.setText(String.valueOf(phongtro.getMaphong()));旧数据库缓存问题
如果之前安装过App,旧的空数据库可能已存在,CREATE TABLE IF NOT EXISTS不会重新创建表。解决方式:- 卸载App后重新安装
- 或在
createTable()中添加日志,确认表是否创建成功
验证步骤
- 完成自定义Application注册后,卸载App重新安装
- 运行App,检查
tblPhong表是否正常创建 - 观察RecyclerView是否正常显示数据
内容的提问来源于stack exchange,提问作者Shillwi2593
相关产品推荐
相关产品推荐

