package pdatabase.rakesh.phobia.pdatabase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

class MyDatabase {

    public static final String DB_NAME = "Tasks.db";
    public static final int DB_VER = 2;
    public static final String DB_TABLE = "Info";
    public static final String C_TASK = "task";
    public static final String C_DESC = "desc";
    public static final String Q_CREATE = "CREATE TABLE "+ DB_TABLE + " (C_TASK TEXT, C_DESC TEXT)";
    Context context;
    SQLiteDatabase database;

    public MyDatabase(Context c) {
        context = c;
    }

    public MyDatabase open() {
        DBHelper dbh = new DBHelper(context);
        database = dbh.getWritableDatabase();
        return this;
    }

    public void write(String task, String desc) {
        ContentValues cv = new ContentValues();
        cv.put(C_TASK, task);
        cv.put(C_DESC, desc);
        database.insert( DB_TABLE,null, cv);
    }

    public void close() {
        database.close();
    }

    public String read() {
        String result = "";

        String[] colms = {C_TASK,C_DESC};
        Cursor cur = database.query(DB_TABLE, colms,null,null,null,null,null);

        int iTask=cur.getColumnIndex(C_TASK);
        int iDesc=cur.getColumnIndex(C_DESC);

        for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()){
            result = result + cur.getString(iTask) + "\t" + cur.getString(iDesc) + "\n";
        }
        return result;
    }

    private class DBHelper extends SQLiteOpenHelper{

        public DBHelper(Context context) {
            super(context, DB_NAME,null, DB_VER);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(Q_CREATE);

        }

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

        }
    }
}


在上面的代码中,我既不能读写C_DESC。我在android studio中收到此帖子主题所写的错误。这是我的数据库类,负责所有数据库操作。当且仅当存在C_TASK时,它才能写入和读取。如果两者都存在,则无法正常工作。该应用程序的目的是保存任务和说明并进行查看。

最佳答案

您已经创建了一个具有实际列名C_DESC的表,而不是使用该变量的内容。请注意,顺便说一句,desc是SQL中的保留字,因此,如果您绝对必须将其用作列名,则应使用双引号(")对其进行转义:

public static final String Q_CREATE =
    "CREATE TABLE "+ DB_TABLE + " (" +
    "\"" + C_TASK + "\" TEXT, " +
    "\"" + C_DESC + "\" TEXT)";

07-24 20:58