You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中SQLite联动Spinner无数据显示问题求助

联动Spinner无数据问题排查与修复

以下是导致所有Spinner无内容的核心问题及对应修复方案:

1. 数据库打开错误(最直接原因)

你在fillSpinner方法中调用OpenDatabase时传入了表名registered_plantation.db,但实际数据库名是SmartSawit.db,导致打开了不存在的数据库,自然查不到数据。

修复代码:
修改fillSpinner中的数据库打开语句:

// 原错误代码
// SQLiteDatabase db = Database.OpenDatabase("registered_plantation.db");
// 修复后
SQLiteDatabase db = Database.OpenDatabase("SmartSawit.db");

2. SQL语句语法错误

拼接SQL时,table与where子句之间缺少空格,导致生成的SQL语句语法非法(例如from registered_plantationwhere prefix='xxx'),查询返回空游标。

修复代码:
在rawQuery的SQL字符串中,table与where之间添加空格:

// 原错误代码
// Cursor cursor = db.rawQuery("Select distinct "+column+" from "+table+""+where, null);
// 修复后
Cursor cursor = db.rawQuery("Select distinct "+column+" from "+table+" "+where, null);

3. 数据库路径不统一导致数据不同步

你的DatabaseHelper中,CheckDB和CopyDatabase操作的是context.getFilesDir() + "/database/"路径下的数据库,但getWritableDatabase()/getReadableDatabase()默认操作的是/data/data/包名/databases/路径下的数据库,导致两处数据库无关联,即使调用addLadang添加数据,也不会同步到你打开的数据库中。

修复方案:
放弃自定义的OpenDatabase方法,直接使用SQLiteOpenHelper提供的方法打开数据库,确保路径统一:

// 修改fillSpinner中的数据库打开语句为:
SQLiteDatabase db = Database.getReadableDatabase();

同时可以移除OpenDatabase方法,避免混淆。

4. 字段类型不匹配导致查询失败

lotno字段定义为INTEGER类型,但你在查询时用单引号包裹了lotnoValue(字符串格式),导致SQL查询条件不匹配,无法返回数据。

修复代码:
修改spinnerLotno的onItemSelected方法中,fillSpinner的where参数:

// 原错误代码
// fillSpinner(context,spinnerPlantation_name,"registered_plantation","plantation_name","where prefix = '"+prefixValue+"' and lotno ='"+lotnoValue+"'");
// 修复后(去掉lotno的单引号)
fillSpinner(context,spinnerPlantation_name,"registered_plantation","plantation_name","where prefix = '"+prefixValue+"' and lotno = "+lotnoValue);

5. 空游标与异常处理缺失

如果查询返回空游标(或cursor为null),mArray会是空集合,Spinner自然无内容。建议添加游标有效性判断:

// 在fillSpinner中,获取cursor后添加判断
if (cursor != null && cursor.moveToFirst()) {
    do {
        mArray.add(cursor.getString(cursor.getColumnIndex(column)));
    } while (cursor.moveToNext());
}

额外验证步骤

  • 确认SmartSawit.db中registered_plantation表已有数据:可以调用addLadang添加测试数据,或通过Android Studio的Device File Explorer查看数据库内容。
  • 检查Logcat是否有SQL相关错误:过滤SQLite或Exception关键词,排查是否有其他语法或权限问题。

内容的提问来源于stack exchange,提问作者aiman adli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:50:19