Android Caused by: java.lang.IllegalArgumentException: column '_id' does not exist

在Android开发中遇到错误:Caused by: java.lang.IllegalArgumentException: column '_id' does not exist。问题源于查询代码缺少'_id'列。修正方法包括:1) 在query方法中明确指定查询包含_id列;2) 如果不需要特定列,使用null查询所有列。SQLite数据库的_id列是必需的,通常作为主键。在ListView适配器中,_id列也用于数据绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

出错原因:在查询整个sqlite数据库时,没有查询到 "_id" 这一列。

原来的代码是:mSQLiteDatabase.query(table_name, new String[] {_title}, null, null, null, null, null);

修改后的代码为:mSQLiteDatabase.query(table_name, null, null, null, null, null, null);

        这里的 new String[] {MyEvent._title} 是一个查询条件,数组里的内容是要查询表的列名,这里是限定你要查询的列。参数值为 null 表示查询所有列(包含有 “_id” 这一列) 。如里这样改也是可以 的:mSQLiteDatabase.query(table_name, new String[] {_id, _title}, null, null, null, null, null); 目的就是要你查询的结果中含有“_id” 这一列。

        另外,关于sqlite数据库中的 "_id" 这一列,在sqlite数据库中是必须有的,而且列名还必须是 “_id” 一般为主键。而用以下代码在一个ListView中显示时,也需要用到 “_id” 这一列。

public void updataAdapter() {
        if (mCursor != null && !mCursor.isClosed())
            mCursor.close();
        
        mCursor = m_MyDataBaseAdapter.fetchAllData();
        mCursor.moveToFirst();
        
        if (mCursor != null && mCursor.getCount() > 0) {
            ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, mCursor, new String[] { _title }, new int[] { android.R.id.text1 });
            listView.setAdapter(adapter);
        }
 }

        这里的 SimpleCursorAdapter 在显示时会根据"_id"进行显示,“_id” 是必须有的。
### Java中文件或目录不存在导致的`IllegalArgumentException`异常解决方案 当尝试操作一个不存在的文件或目录时,可能会抛出`java.lang.IllegalArgumentException`异常。为了处理这种情况,应该先验证目标路径是否存在以及是否具有预期属性。 对于文件或目录的操作前应当做如下检查: - 使用`Files.exists()`方法来判断给定路径下的资源是否存在。 - 对于文件而言,还需确认其确实是一个文件而非其他类型的节点;可借助`Files.isRegularFile()`实现这一目的。 - 若目标为目录,则应通过`Files.isDirectory()`来进行校验。 下面给出一段示范代码用于安全创建新文件并写入内容,如果指定位置已经存在同名项则不会覆盖而是提示用户[^1]。 ```java import java.io.IOException; import java.nio.file.*; public class SafeFileCreator { public static void main(String[] args) throws IOException { Path path = Paths.get("example.txt"); try{ if (!Files.exists(path)) { // Check existence of the file. Files.createFile(path); // Create a new empty file at given location. System.out.println("Created " + path.toString()); // Writing content into newly created file. String textToWrite = "This is an example."; Files.write(path, textToWrite.getBytes(), StandardOpenOption.WRITE); } else { System.out.println("The specified file already exists."); } } catch (InvalidPathException e){ System.err.format("Invalid path format: %s%n", e.getMessage()); } } } ``` 针对目录的情况也类似,只不过需要调用不同的API函数如`Files.createDirectories()`来确保整个路径都被正确建立起来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值