android - 将外部Sqlite与SimpleCursorAdapter一起使用时应用崩溃

标签 android sqlite simplecursoradapter crash

在学习了很多教程之后,我现在正在创建一个应用程序

该应用程序包含一个外部sqlite数据库..现在,当我尝试显示我的应用程序崩溃时,我正尝试在列表 View 中显示第一列。.当我 checkin logcat时,它只是说列'_id'不存在但是在我的数据库中我没有像column_id plz这样的列,这是下面的代码

我在SqliteManager中的创建语句

CREATE TABLE "Ayervedic" ("Item No" NUMERIC NOT NULL , "Title" VARCHAR NOT NULL , "Subcategory" VARCHAR NOT NULL , "Details" VARCHAR NOT NULL , "Images" VARCHAR NOT NULL , PRIMARY KEY ("Item No", "Title", "Subcategory", "Details", "Images"))

数据库类
public class SqlLiteDbHelper extends SQLiteOpenHelper {

// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "Ayervedic.sqlite";
private static final String DB_PATH_SUFFIX = "/databases/";
static Context ctx;

public SqlLiteDbHelper(Context context) {

    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    ctx = context;
}
public void CopyDataBaseFromAsset() throws IOException {

    InputStream myInput = ctx.getAssets().open(DATABASE_NAME);

    // Path to the just created empty db
    String outFileName = getDatabasePath();

    // if the path doesn't exist first, create it
    File f = new File(ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX);
    if (!f.exists())
        f.mkdir();

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);


    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);

    }
    // Close the streams

    myOutput.flush();
    myOutput.close();
    myInput.close();

}

private static String getDatabasePath() {

    return ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX + DATABASE_NAME;

}

public SQLiteDatabase openDataBase() throws SQLException {

    File dbFile = ctx.getDatabasePath(DATABASE_NAME);
    if (!dbFile.exists()) {
        try {
            CopyDataBaseFromAsset();

            System.out.println("Copying sucess from Assets folder");

        } catch (IOException e) {

            throw new RuntimeException("Error creating source database", e);

        }

    }
    return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);

}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
public Cursor gettitles(SQLiteDatabase db)
{
    db = this.getReadableDatabase();

    Cursor cursor;

    cursor = db.query(true, "Ayervedic", new String[]{"Title"}, null, null, null, null, null, null);
    return cursor;
}

主要 Activity
public class MainActivity extends AppCompatActivity {

ListView listView;
String title;
SqlLiteDbHelper dbHelper;

SQLiteDatabase sqLiteDatabase;
Cursor cursor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   listView= (ListView) findViewById(R.id.listView);
    dbHelper = new SqlLiteDbHelper(this);
    try {
        dbHelper.openDataBase();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    sqLiteDatabase=dbHelper.getReadableDatabase();
    cursor=dbHelper.gettitles(sqLiteDatabase);
    String[] from = new String[] { "Title" };
    int[] to = new int[] {R.id.textView };
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.row_title,cursor,from,to);
    adapter.notifyDataSetChanged();
    listView.setAdapter(adapter);
}

Logcat:
Process: com.example.ky.tamil, PID: 6286
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ky.tamil/com.example.aeiltech.tamil.MainActivity}: java.lang.IllegalArgumentException: column '_id' does not exist
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2436)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2498)
        at android.app.ActivityThread.access$900(ActivityThread.java:179)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5641)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1288)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1104)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalArgumentException: column '_id' does not exist

最佳答案

SimpleCursorAdapter是CursorAdapter的子类。文档states:

The Cursor must include a column named "_id" or this class will not work.



在您的情况下,您可以将主键Item No重命名为_id
编辑:即使没有映射到 View ,您也需要在光标中选择此列。
cursor = db.query(true, "Ayervedic", new String[]{"Title", "_id"}, null, null, null, null, null, null);

关于android - 将外部Sqlite与SimpleCursorAdapter一起使用时应用崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33146717/

相关文章:

Android fragment popBackStack 和替换不删除 View

Android,日文字 rune 件名比较问题

sql - 如何在QDB库中添加用户定义的函数?

sqlite - 谷歌浏览器 : How to find out the name of Transition from its id in History sql-lite db

android - 如何设置 View 或 Activity 来处理以前的列表 Activity ?例如 "see full detail page"

android - 如何制作自己的广告 android SDK?

c# - 在程序启动时同步文件系统和缓存数据

android - 在 ListView 中显示结果集(不是游标)

android - 带有 ImageView 和 TextView 的 SimpleCursorAdapter

Android:如何使 View 的背景不可见?