无法从SQLite数据库中获取数据

时间:2016-03-24 16:13:02

标签: android sqlite

我已设法使用此代码

在SQLiteDatabase中插入数据
    void addAlarm(Alarms alarms) {
        Log.i("Point","process is starting");
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_ALARM, alarms.getAlarm());

        // Inserting Row
        db.insert(TABLE_ALARMS, null, values);
        db.close(); // Closing database connection
        Log.i("Point","inserting is done in addAlarm method");
    }

但后来我想用这种方法获取数据:

    Long getAlarm(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_ALARMS, new String[]{COLUMN_ID,
                        COLUMN_ALARM}, COLUMN_ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null);
        Long l = null;
        if (cursor != null && cursor.moveToFirst()) {
           l = cursor.getLong(1);
        }
        // return contact
        return l;
    }

在我想知道数据仍然在数据库中之后,我使用了这段代码:

mySQLiteHelper = new MySQLiteHelper(context);
        Log.i("Point",Long.toString(mySQLiteHelper.getAlarm(0)));
        Log.i("Point",Long.toString(mySQLiteHelper.getAlarm(1)));

那时我在logcat上得到了NullPointerException。 有人可以解释为什么会这样吗?我该怎么办?

而且当我想删除它时,我没有错误或异常。 这是删除数据的代码:

public void deleteAlarm(int id) {
        Log.i("Point","deleting is starting");
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_ALARMS, COLUMN_ID + " = ?",
                new String[] { String.valueOf(id) });
        db.close();
        Log.i("Point","deleting is over");
    }

谢谢。

修改

我的整个代码:

public class MySQLiteHelper extends SQLiteOpenHelper {
    public static final String TABLE_ALARMS = "alarms";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_ALARM = "alarm";
    public static final String DB_PATH = "/DATA/data/db1/databases/";

    public static final String DATABASE_NAME = "alarms.db";
    private static final int DATABASE_VERSION = 1;

    // Database creation sql statement
    private static final String DATABASE_CREATE = "create table "
            + TABLE_ALARMS + "(" + COLUMN_ID
            + " integer primary key autoincrement, " + COLUMN_ALARM
            + " text not null);";

    public MySQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //Log.w(MySQLiteHelper.class.getName(),
        //        "Upgrading database from version " + oldVersion + " to "
        //                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ALARMS);
        onCreate(db);
    }
    void addAlarm(Alarms alarms) {
        Log.i("Point","process is starting");
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_ALARM, alarms.getAlarm());

        // Inserting Row
        db.insert(TABLE_ALARMS, null, values);
        db.close(); // Closing database connection
        Log.i("Point","inserting is done in addAlarm method");
    }

    // Getting single contact
    Long getAlarm(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_ALARMS, new String[]{COLUMN_ID,
                        COLUMN_ALARM}, COLUMN_ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null);
        Long l = null;
        if (cursor != null && cursor.moveToFirst()) {
           l = cursor.getLong(1);
        }
        // return contact
        return l;
    }
    public void deleteAlarm(int id) {
        Log.i("Point","deleting is starting");
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_ALARMS, COLUMN_ID + " = ?",
                new String[] { String.valueOf(id) });
        db.close();
        Log.i("Point","deleting is over");
    }
}

错误:

Process: com.example.amadey.myapplication, PID: 1509
    java.lang.RuntimeException: Unable to start receiver com.example.amadey.myapplication.EndReceiver: java.lang.NullPointerException
            at android.app.ActivityThread.handleReceiver(ActivityThread.java:2414)
            at android.app.ActivityThread.access$1700(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            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:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.amadey.myapplication.EndReceiver.onReceive(EndReceiver.java:20)
            at android.app.ActivityThread.handleReceiver(ActivityThread.java:2407)
            at android.app.ActivityThread.access$1700(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            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:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)

和Alarms.class:

public class Alarms{
    private int id;
    private String alarms;
    private Long alarm;

    public Alarms(int id,Long l){
        this.alarm = l;
        this.id = id;
    }
    public long getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Long getAlarm() {
        return alarm;
    }

    public void setAlarms(String alarms) {
        this.alarms = alarms;
    }
}

public class EndReceiver extends BroadcastReceiver {
    MySQLiteHelper mySQLiteHelper;
    public EndReceiver() {
    }

EndReceiver.class

    @Override
    public void onReceive(Context context, Intent intent) {
        context.stopService(new Intent(context, MyService.class));
        context.stopService(new Intent(context, MyService2.class));
        mySQLiteHelper = new MySQLiteHelper(context);
        Log.i("Point",Long.toString(mySQLiteHelper.getAlarm(0)));
        Log.i("Point",Long.toString(mySQLiteHelper.getAlarm(1)));
        Log.i("Point", "next step is deleting");
        mySQLiteHelper.deleteAlarm(0);
        mySQLiteHelper.deleteAlarm(1);
        Log.i("Point","deleting is done");

        mySQLiteHelper.close();
        /*Intent intent1 = new Intent(Intent.ACTION_MAIN);
        intent1.addCategory(Intent.CATEGORY_HOME);
        intent1.addCategory(Intent.CATEGORY_LAUNCHER);
        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);*/
    }
}

1 个答案:

答案 0 :(得分:1)

所以,我看到的一些事情是......

  1. 您的表格定义为两列,COLUMN_ID integerCOLUMN_ALARM text
  2. 您的警报对象有三个字段。一个int id,一个String alarms和一个Long alarm。我假设String alarms是您要插入数据库的值,因为该列的类型为text
  3. alarms.getAlarm()正在返回Long对象,而不是字符串,但您尝试将Long值插入textvalues.put(COLUMN_ALARM, alarms.getAlarm()); } ...
  4. 您的实际问题是l = cursor.getLong(1); 返回null 因为根据文档getLong()将“在列值为null时抛出异常,列类型不是一个整体类型“
  5. 通常,如果您不理解使用Long对象的原因,则应使用原始long

    要解决您的问题,我建议您考虑执行以下某些操作

    1. 确保数据实际存储在数据库中。
    2. 修复CREATE TABLE语句的列类型,使COLUMN_ALARM成为integer类型,以存储您可以正确查询的Long值。
    3. 使用cursor.getString(1)代替cursor.getLong(1)来检索TEXT
    4. 定义String getAlarms()方法以实际返回String alarms值并将其插入数据库而不是Long对象values.put(COLUMN_ALARM, alarms.getAlarms());