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

如何从含main_categories表的SQLite数据库读取数据并显示在ListView中

从SQLite数据库读取分类数据并展示在ListView中

我来帮你完善代码,实现从main_categories表读取数据并在ListView里展示的功能。首先我们先把你的DataAdapter补充完整,添加数据库操作和数据查询的方法,然后再在Activity里完成ListView的绑定。

第一步:完善DataAdapter类

你已经有了构造方法和创建数据库的逻辑,现在需要添加打开/关闭数据库的方法,以及获取所有分类的查询方法:

public class DataAdapter {
    private static final String TAG = "DataAdapter";
    private Context mContext;
    private DataBaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    // 你的已有构造方法
    public DataAdapter(Context context) {
        this.mContext = context;
        mDbHelper = new DataBaseHelper(mContext);
    }

    // 补全你的创建数据库方法的异常提示
    public DataAdapter createDatabase() throws SQLException {
        try {
            mDbHelper.createDataBase();
        } catch (IOException mIOException) {
            Log.e(TAG, "创建数据库失败: " + mIOException.toString());
            throw new Error("无法创建数据库,请检查资源文件");
        }
        return this;
    }

    // 添加:打开数据库连接
    public DataAdapter open() throws SQLException {
        try {
            mDbHelper.openDataBase();
            mDb = mDbHelper.getReadableDatabase();
        } catch (SQLException mSQLException) {
            Log.e(TAG, "打开数据库失败: " + mSQLException.toString());
            throw mSQLException;
        }
        return this;
    }

    // 添加:关闭数据库
    public void close() {
        mDbHelper.close();
    }

    // 添加:查询所有分类数据
    public List<String> getAllCategories() {
        List<String> categoryList = new ArrayList<>();
        // 查询main_categories表的所有category_name字段
        Cursor cursor = mDb.query(
                "main_categories",
                new String[]{"category_name"},
                null,
                null,
                null,
                null,
                null
        );

        // 遍历游标获取数据
        if (cursor.moveToFirst()) {
            do {
                // 安全获取字段值,避免索引错误
                String categoryName = cursor.getString(
                        cursor.getColumnIndexOrThrow("category_name")
                );
                categoryList.add(categoryName);
            } while (cursor.moveToNext());
        }
        // 一定要关闭游标,避免资源泄漏
        cursor.close();
        return categoryList;
    }
}

第二步:在Activity中绑定数据到ListView

接下来在你的Activity里,初始化ListView,调用DataAdapter获取数据,并用ArrayAdapter完成绑定:

public class CategoryActivity extends AppCompatActivity {
    private ListView mCategoryListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);

        mCategoryListView = findViewById(R.id.list_view_categories);

        try {
            // 初始化DataAdapter并准备数据库
            DataAdapter dataAdapter = new DataAdapter(this);
            dataAdapter.createDatabase().open();
            
            // 获取所有分类数据
            List<String> categoryList = dataAdapter.getAllCategories();
            
            // 关闭数据库连接
            dataAdapter.close();

            // 使用系统默认的列表项布局创建适配器
            ArrayAdapter<String> listAdapter = new ArrayAdapter<>(
                    this,
                    android.R.layout.simple_list_item_1,
                    categoryList
            );
            
            // 绑定适配器到ListView
            mCategoryListView.setAdapter(listAdapter);

            // 可选:添加列表项点击事件
            mCategoryListView.setOnItemClickListener((parent, view, position, id) -> {
                String selectedCategory = categoryList.get(position);
                Toast.makeText(this, "你选中了:" + selectedCategory, Toast.LENGTH_SHORT).show();
            });

        } catch (SQLException e) {
            e.printStackTrace();
            Toast.makeText(this, "数据库操作出错,请检查", Toast.LENGTH_SHORT).show();
        }
    }
}

一些注意事项

  • 确保你的DataBaseHelper类正确实现了createDataBase()和openDataBase()方法,如果是预打包的数据库,要保证它被正确复制到应用的数据库目录。
  • 操作完数据库后一定要调用close()方法释放资源,避免内存泄漏。
  • 使用getColumnIndexOrThrow()而不是直接用索引0,这样如果字段名拼写错误会直接抛出异常,方便你排查问题。
  • 如果需要自定义列表项样式,可以创建自己的布局文件,替换android.R.layout.simple_list_item_1。

内容的提问来源于stack exchange,提问作者M.Khaled

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:36:05