安卓SQLite常见错误
Posted 南尘
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了安卓SQLite常见错误相关的知识,希望对你有一定的参考价值。
利用闲时写了一个简单的Sql语句操作SQLite数据库,在用SimpleCursorAdapter时出了一个异常好久都没解决
Process: com.example.chunchuner.usesqltest405, PID: 31206
java.lang.IllegalArgumentException: column \'_id\' does not exist
通过一系列查找资料才发现
//使用SimpleCursorAdapter封装Cursor时候Cursor要求底层数据库的主键列的列名必须为_id
//否则会出现java.lang.IllegalArgumentException异常
代码如下:
package com.example.nanchen.usesqltest405; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class MainActivity extends AppCompatActivity { private Button insert; private EditText textView_title,textView_content; private SQLiteDatabase db; private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //创建或者打开数据库(此处需要使用绝对路径) db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/my.db3",null); insert = (Button) findViewById(R.id.insert); listView = (ListView) findViewById(R.id.listView); textView_title = (EditText) findViewById(R.id.title_text); textView_content = (EditText) findViewById(R.id.content); insert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String title = textView_title.getText().toString(); String content = textView_content.getText().toString(); try { insertData(db, title, content); }catch (SQLiteException e){ //执行创建数据库表 db.execSQL("create table news_inf(_id integer primary key autoincrement, " + "news_title varchar2,news_content varchar2)"); insertData(db, title, content); } Cursor cursor = db.rawQuery("select * from news_inf", null); inflateList(cursor); } }); } private void insertData(SQLiteDatabase db,String title,String content){ db.execSQL("insert into news_inf values(null,?,?)", new String[]{title, content}); } private void inflateList(Cursor cursor){ //填充SimpleCursorAdapter //使用SimpleCursorAdapter封装Cursor时候Cursor要求底层数据库的主键列的列名必须为_id //否则会出现java.lang.IllegalArgumentException异常 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,cursor, new String[]{"news_title","news_content"}, new int[]{R.id.title_text,R.id.content}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); //显示数据 listView.setAdapter(adapter); } @Override protected void onDestroy() { super.onDestroy(); //退出程序时关闭SQLiteDataBase if (db != null && db.isOpen()){ db.close(); } } }
以上是关于安卓SQLite常见错误的主要内容,如果未能解决你的问题,请参考以下文章
java.lang.NullPointerException: Attempt to invoke virtual method ‘int android.database.sqlite异常(代码片段
如何使用列表视图在选项卡式活动的片段中呈现 SQLite 表数据 [重复]