关闭最近的应用程序后,Sqlite数据不会显示

时间:2018-01-21 09:59:39

标签: android sqlite

每次停止应用程序时,都不会显示数据库中的数据,而是从第一个数据库创建数据库。 我不确切地知道问题出在哪里 需要更多准确的指导 现在存储和显示信息,但是当从最近的应用程序关闭应用程序时,将重建数据库。

public SevenLearnDatabaseOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
    try {

        db.execSQL("CREATE TABLE IF NOT EXISTS " + POST_TABLE_NAME + " (" +
                COL_ID + " INTEGER PRIMARY KEY, " +
                COL_PAGE + " TEXT, " +
                COL_PAGE2 + " TEXT, " +
                COL_NIAT + " TEXT, " +
                COL_DATE + " TEXT);");

        Log.e(TAG, "onCreate: " + "create database");

    } catch (SQLException e) {
        Log.e(TAG, "onCreate: " + e.toString());
    }
}

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

}


public boolean addPost(Post post) {
    ContentValues cv = new ContentValues();
    cv.put(COL_ID, post.getId());
    cv.put(COL_PAGE, post.getPage());
    cv.put(COL_PAGE2, post.getPage2());
    cv.put(COL_NIAT, post.getNiat());
    cv.put(COL_DATE, post.getDate());

    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    long isInserted = sqLiteDatabase.insert(POST_TABLE_NAME, null, cv);

    Log.i(TAG, "addPost: " + isInserted + "-" + post.getDate());

    if (isInserted > 0) {
        return true;
    } else {
        return false;
    }
}

public void addPosts(List<Post> posts) {
    for (int i = 0; i < posts.size(); i++) {
            addPost(posts.get(i));
    }
}

public List<Post> getPosts() {
    List<Post> posts = new ArrayList<>();

    SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
    Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + POST_TABLE_NAME, null);
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        while (!cursor.isAfterLast()) {
            Post post = new Post();
            post.setId(cursor.getInt(0));
            post.setPage(cursor.getString(1));
            post.setPage2(cursor.getString(2));
            post.setNiat(cursor.getString(3));
            post.setDate(cursor.getString(4));
            posts.add(post);
            cursor.moveToNext();
        }
    }
    cursor.close();
    sqLiteDatabase.close();
    System.out.println("rrrrrrrrrrrrrrr" + cursor.getCount());
    return posts;
}

1 个答案:

答案 0 :(得分:0)

我相信这段代码会导致getPosts方法失败,因为在调用cursor.getCount()时Cursor会被关闭。

cursor.close();
sqLiteDatabase.close();
System.out.println("rrrrrrrrrrrrrrr" + cursor.getCount());
return posts;

尝试将其更改为: -

System.out.println("rrrrrrrrrrrrrrr" + cursor.getCount()); //<<<< MOVED BEFORE CURSOR CLOSE
cursor.close();
sqLiteDatabase.close();
return posts;