Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android SQLiteDatabase无法插入或查询_Android_Database_Insert - Fatal编程技术网

Android SQLiteDatabase无法插入或查询

Android SQLiteDatabase无法插入或查询,android,database,insert,Android,Database,Insert,我有一个使用多个数据库的应用程序。目前,我只有一个问题。它在数据库中存储日历的事件。其SQLiteOpenHelper如下所示: public class PlanSQLiteHelper extends SQLiteOpenHelper { //The database version. public static final int VERSION = 1; //The String keys of the database name and columns. public static

我有一个使用多个数据库的应用程序。目前,我只有一个问题。它在数据库中存储日历的事件。其SQLiteOpenHelper如下所示:

public class PlanSQLiteHelper extends SQLiteOpenHelper {

//The database version.
public static final int VERSION = 1;

//The String keys of the database name and columns.
public static final String DB_NAME = "plans_db.sqlite";
public static final String PLANS_TABLE = "plans";
public static final String PLAN_ID = "id";
public static final String PLAN_NAME = "name";
public static final String PLAN_YEAR = "year";
public static final String PLAN_MONTH = "month";
public static final String PLAN_DAY = "day";
public static final String PLAN_PRIORITY = "priority";
public static final String PLAN_TIME = "time";
public static final String PLAN_END = "end";
public static final String SET_APPT = "set_appt";
public static final String PLAN_ALARM = "alarm";


public PlanSQLiteHelper(Context context) {
    super(context, DB_NAME, null, VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    createTable(db);
}

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

private void createTable(SQLiteDatabase db) {

    db.execSQL(
            "create table " + PLANS_TABLE + " ( " +
            PLAN_ID + " integer primary key autoincrement not null, " +
            PLAN_NAME + " text, " +
            PLAN_YEAR + " integer, " +
            PLAN_MONTH + " integer, " +
            PLAN_DAY + " integer, " +
            PLAN_PRIORITY + " integer, " +
            PLAN_TIME + " integer, " +
            PLAN_END + " integer, " +
            SET_APPT + " integer, " +
            PLAN_ALARM + " integer );" );
}
}
这是一个过程: 用户转到屏幕以创建新的日历项(称为计划项)。它有特定的选项,用户选择所需的选项,然后点击“ok”。PlanItem将生成并传递给应用程序的应用程序类中的一个方法,如下所示:

/**
 * Called to save a PlanItem to the SQLiteDatabase.
 * @param item = the item to save to the database.
 * @param newItem = true if the item is new, false if it exists but was edited.
 * @return true if successful, false otherwise.
 */
public boolean savePlanItem(PlanItem item, boolean newItem) {

    try {

        //Create the ContentValues.
        ContentValues values = new ContentValues();

        //Put the values in.
        values.put(PLAN_NAME, item.getName());
        values.put(PLAN_YEAR, item.getYear());
        values.put(PLAN_MONTH, item.getMonth());
        values.put(PLAN_DAY, item.getDay());
        values.put(PLAN_TIME, item.getTime());
        values.put(PLAN_END, item.getEnd());
        values.put(SET_APPT, item.isSetAppt() ? 1 : 0);
        values.put(PLAN_PRIORITY, item.getPriorityInt());
        values.put(PLAN_ALARM, item.isAlarm() ? 1 : 0);

        if (newItem) {

            //Put into the database.
            long id = plansDatabase.insert(PLANS_TABLE, null, values);

            if (id == -1) {
                return false;
            }
        }
        else {

            //Update the database.
            String where = String.format("%s = ?", PLAN_ID);
            plansDatabase.update(PLANS_TABLE, values, where, new String[] { item.getId() + "" });
        }

    }
    catch (Exception e) {
        return false;
    }

    //Since it succeeded, return true.
    return true;
}
/**
 * Called to get the agenda items for a particular day.
 * @param date = the date to get agenda items for.
 * @return the ArrayList of PlanItems for the day.
 */
public ArrayList<PlanItem> getDailyAgenda(Date d) {

    //Make a new date.
    Date date = new Date(d.getDay(), d.getMonth(), d.getYear());

    //Create the ArrayList.
    ArrayList<PlanItem> items = new ArrayList<PlanItem>();

    //Set up a query.
    Cursor cursor = plansDatabase.query(PLANS_TABLE, new String[] {PLAN_ID, PLAN_NAME, PLAN_YEAR,
            PLAN_MONTH, PLAN_DAY, PLAN_PRIORITY, PLAN_TIME, PLAN_END, SET_APPT, PLAN_ALARM},
            String.format(" %s = ? AND %s = ? AND %s = ? ", PLAN_YEAR, PLAN_MONTH, PLAN_DAY),
            new String[] {String.valueOf(date.getYear()), String.valueOf(date.getMonth()),
            String.valueOf(date.getDay())}, null, null, null);

    //Move the cursor to the first position.
    cursor.moveToFirst();

    //If there are items...
    if (!cursor.isAfterLast()) {

        //Initialize variables.
        long id;
        String name;
        int year, month, day, time, end, priority;
        boolean setAppt, alarm;
        PlanItem item;


        //Go through the database and get everything.
        do {

            //Get the values.
            id = cursor.getLong(0);
            name = cursor.getString(1);
            year = cursor.getInt(2);
            month = cursor.getInt(3);
            day = cursor.getInt(4);
            priority = cursor.getInt(5);
            time = cursor.getInt(6);
            end = cursor.getInt(7);
            setAppt = cursor.getInt(8) == 1;
            alarm = cursor.getInt(9) == 1;

            //Create a PlanItem and add it to the ArrayList.
            item = new PlanItem(id, name, year, month, day,
                    priority, time, end, setAppt, alarm);
            items.add(item);

        } while (cursor.moveToNext());
    }

    //Close the cursor.
    cursor.close();

    //Return the items.
    return items;
}
布尔newItem只告诉方法是否创建或编辑了该项。我的问题在于创作。如您所见,它使用SQLiteDatabase.insert()方法。我甚至抓取新行的id,并用-1测试它(根据Android文档,如果出现错误,它将返回-1)。即使如此,该方法返回true,这意味着它已正确保存。 然后,一旦保存,允许用户创建项目的活动将完成并返回到显示该项目的活动。在onResume()中,它调用应用程序类以获取当天的PlanItems。它看起来像:

/**
 * Called to save a PlanItem to the SQLiteDatabase.
 * @param item = the item to save to the database.
 * @param newItem = true if the item is new, false if it exists but was edited.
 * @return true if successful, false otherwise.
 */
public boolean savePlanItem(PlanItem item, boolean newItem) {

    try {

        //Create the ContentValues.
        ContentValues values = new ContentValues();

        //Put the values in.
        values.put(PLAN_NAME, item.getName());
        values.put(PLAN_YEAR, item.getYear());
        values.put(PLAN_MONTH, item.getMonth());
        values.put(PLAN_DAY, item.getDay());
        values.put(PLAN_TIME, item.getTime());
        values.put(PLAN_END, item.getEnd());
        values.put(SET_APPT, item.isSetAppt() ? 1 : 0);
        values.put(PLAN_PRIORITY, item.getPriorityInt());
        values.put(PLAN_ALARM, item.isAlarm() ? 1 : 0);

        if (newItem) {

            //Put into the database.
            long id = plansDatabase.insert(PLANS_TABLE, null, values);

            if (id == -1) {
                return false;
            }
        }
        else {

            //Update the database.
            String where = String.format("%s = ?", PLAN_ID);
            plansDatabase.update(PLANS_TABLE, values, where, new String[] { item.getId() + "" });
        }

    }
    catch (Exception e) {
        return false;
    }

    //Since it succeeded, return true.
    return true;
}
/**
 * Called to get the agenda items for a particular day.
 * @param date = the date to get agenda items for.
 * @return the ArrayList of PlanItems for the day.
 */
public ArrayList<PlanItem> getDailyAgenda(Date d) {

    //Make a new date.
    Date date = new Date(d.getDay(), d.getMonth(), d.getYear());

    //Create the ArrayList.
    ArrayList<PlanItem> items = new ArrayList<PlanItem>();

    //Set up a query.
    Cursor cursor = plansDatabase.query(PLANS_TABLE, new String[] {PLAN_ID, PLAN_NAME, PLAN_YEAR,
            PLAN_MONTH, PLAN_DAY, PLAN_PRIORITY, PLAN_TIME, PLAN_END, SET_APPT, PLAN_ALARM},
            String.format(" %s = ? AND %s = ? AND %s = ? ", PLAN_YEAR, PLAN_MONTH, PLAN_DAY),
            new String[] {String.valueOf(date.getYear()), String.valueOf(date.getMonth()),
            String.valueOf(date.getDay())}, null, null, null);

    //Move the cursor to the first position.
    cursor.moveToFirst();

    //If there are items...
    if (!cursor.isAfterLast()) {

        //Initialize variables.
        long id;
        String name;
        int year, month, day, time, end, priority;
        boolean setAppt, alarm;
        PlanItem item;


        //Go through the database and get everything.
        do {

            //Get the values.
            id = cursor.getLong(0);
            name = cursor.getString(1);
            year = cursor.getInt(2);
            month = cursor.getInt(3);
            day = cursor.getInt(4);
            priority = cursor.getInt(5);
            time = cursor.getInt(6);
            end = cursor.getInt(7);
            setAppt = cursor.getInt(8) == 1;
            alarm = cursor.getInt(9) == 1;

            //Create a PlanItem and add it to the ArrayList.
            item = new PlanItem(id, name, year, month, day,
                    priority, time, end, setAppt, alarm);
            items.add(item);

        } while (cursor.moveToNext());
    }

    //Close the cursor.
    cursor.close();

    //Return the items.
    return items;
}
/**
*打电话来获取某一天的议程项目。
*@param date=获取议程项目的日期。
*@返回当天的计划项目列表。
*/
公共阵列列表GetDailyGenda(日期d){
//重新约会。
日期日期=新日期(d.getDay(),d.getMonth(),d.getYear());
//创建ArrayList。
ArrayList items=新建ArrayList();
//设置查询。
Cursor Cursor=plansDatabase.query(PLANS_表,新字符串[]{PLAN_ID,PLAN_名称,PLAN_年份,
计划月、计划日、计划优先级、计划时间、计划结束、设置应用、计划报警、,
格式(“%s=?和%s=?和%s=?”,计划年、计划月、计划日),
新字符串[]{String.valueOf(date.getYear()),String.valueOf(date.getMonth()),
valueOf(date.getDay())},null,null,null);
//将光标移动到第一个位置。
cursor.moveToFirst();
//如果有项目。。。
如果(!cursor.isAfterLast()){
//初始化变量。
长id;
字符串名;
整数年、月、日、时间、结束、优先级;
布尔设置应用,报警;
计划项目;
//检查数据库并获取所有信息。
做{
//获取值。
id=cursor.getLong(0);
name=cursor.getString(1);
年份=cursor.getInt(2);
月份=cursor.getInt(3);
day=cursor.getInt(4);
优先级=cursor.getInt(5);
time=cursor.getInt(6);
end=cursor.getInt(7);
setAppt=cursor.getInt(8)==1;
报警=光标。getInt(9)==1;
//创建一个PlanItem并将其添加到ArrayList。
项目=新计划项目(id、名称、年、月、日、,
优先级、时间、结束、设置应用、报警);
项目。添加(项目);
}while(cursor.moveToNext());
}
//关闭光标。
cursor.close();
//归还物品。
退货项目;
}
对象日期是我自己的对象,而不是Java对象。它只包含我需要的方法

我已经在调试器中检查并重新检查了查询。它遵循SQLite规则。但它并没有从数据库中提取任何内容,即使是在我为那天创建了一个新项目之后。进入
返回项行并返回空的ArrayList。我走遍了周围的几天,想看看这件物品是否存放在了错误的日期,但事实并非如此。我还检查了插入数据库的日期、月份和年份。他们是正确的

我来这里是想找个答案

我一辈子都搞不懂这个。请帮忙


由于这是我的第一个问题,请对如何改进我的问题发表意见。

您应该尝试将异常记录在savePlanItem()函数中,以确保插入操作完成


还有一个问题,在这些函数中,您在哪里打开数据库?

好的,事情是这样的。我现在觉得自己很愚蠢。问题解决了。它不起作用的原因是,在某些地方,我在自己的日期对象构造函数中颠倒了年份和日期。在将年、月和日直接放入查询(而不是问号)后,我发现了这一点。无论如何,我希望这是一次很好的学习体验。

我在应用程序类的onCreate()方法中打开了它。此外,我还通过对照-1检查返回的id来检查savePlanItem()方法中是否存在错误(Android文档说,当出现错误时,会为id返回-1)。尽管如此,我还是会添加日志,看看是否有什么不同。我会投票给你的答案,但我没有足够的声誉。谢谢你的帮助。如果你想知道我为什么会有这个问题,请查看问题页面;这很尴尬。谢谢你的帮助!