如何在android中解决sqlite游标问题?

时间:2014-06-04 12:43:11

标签: android sqlite android-sqlite android-cursor

有没有人遇到类似的问题?

现在我正在使用Sqlite DB来保存android中的数据。但我得到了一些问题,如下面的logcat,这是限制,我无法运行我的应用程序。

建议请。

logcat的

06-04 12:03:05.603: E/Cursor(281): Finalizing a Cursor that has not been deactivated or closed. database = /data/data/org.twinkletech.postcourier/databases/GetNewsDetailsManager, table = null, query = SELECT  * FROM getnewsdetails
06-04 12:03:05.603: E/Cursor(281): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
06-04 12:03:05.603: E/Cursor(281):  at android.database.sqlite.SQLiteCursor.<init>(SQLiteCursor.java:210)
06-04 12:03:05.603: E/Cursor(281):  at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:53)
06-04 12:03:05.603: E/Cursor(281):  at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
06-04 12:03:05.603: E/Cursor(281):  at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1315)
06-04 12:03:05.603: E/Cursor(281):  at org.twinkletech.postcourier.DatabaseHandler.getAllContacts(DatabaseHandler.java:91)
06-04 12:03:05.603: E/Cursor(281):  at org.twinkletech.postcourier.Splash_Screen$Show_Default_News.Call_db_handler(Splash_Screen.java:133)
06-04 12:03:05.603: E/Cursor(281):  at org.twinkletech.postcourier.Splash_Screen$Show_Default_News.Call_Service(Splash_Screen.java:99)
06-04 12:03:05.603: E/Cursor(281):  at org.twinkletech.postcourier.Splash_Screen$Show_Default_News.doInBackground(Splash_Screen.java:62)
06-04 12:03:05.603: E/Cursor(281):  at org.twinkletech.postcourier.Splash_Screen$Show_Default_News.doInBackground(Splash_Screen.java:1)
06-04 12:03:05.603: E/Cursor(281):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
06-04 12:03:05.603: E/Cursor(281):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-04 12:03:05.603: E/Cursor(281):  at  java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-04 12:03:05.603: E/Cursor(281):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
06-04 12:03:05.603: E/Cursor(281):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
06-04 12:03:05.603: E/Cursor(281):  at java.lang.Thread.run(Thread.java:1096)

MainActivity.java

   String str_data = "On 14 November 1987, Tendulkar was selected to represent Mumbai in the Ranji Trophy, India's premier domestic First-class cricket tournament, for the 1987–88 season. However, he was not selected for the final eleven in any of the matches, though he was often used as a substitute fielder";

DatabaseHandler db = new DatabaseHandler(Splash_Screen.this);

            // Inserting Contacts
            Log.d("Insert: ", "Inserting ..");
            db.addContact(new NewsDetails(result_data));

            // Reading all contacts
            Log.d(">>--Reading: ", "Reading all contacts..");
            List<NewsDetails> contacts = db.getAllContacts();       

            for (NewsDetails cn : contacts) 
            {
            //  str_db_news = "Id: "+cn.getID()+" ,Name: " + cn.getName() ;
                String str_db_news = cn.getName();
                }
           }

DatabaseHandler.java

public class DatabaseHandler extends SQLiteOpenHelper
{

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "GetNewsDetailsManager";

// NewsDetails table name
private static final String TABLE_NAME = "getnewsdetails";

// NewsDetails Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";

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

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {

    String CREATE_NEWS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT"+ ")";

    db.execSQL(CREATE_NEWS_TABLE);
}


// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

    // Create tables again
    onCreate(db);
}

// Adding new contact
public void addContact(NewsDetails contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name

    // Inserting Row
    db.insert(TABLE_NAME, null, values);
    db.close(); // Closing database connection

}

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

    Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ID,
            KEY_NAME }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    NewsDetails contact = new NewsDetails(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1));
    // return contact
    return contact;
}

// Getting All Contacts
public List<NewsDetails> getAllContacts() {
    List<NewsDetails> newsdatalist = new ArrayList<NewsDetails>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            NewsDetails news_data = new NewsDetails();

//              contact.setID(Integer.parseInt(cursor.getString(0)));
            news_data.setID(cursor.getInt(0));
            news_data.setName(cursor.getString(1));

            // Adding contact to list
            newsdatalist.add(news_data);
        } while (cursor.moveToNext());
    }

    db.close(); // 


    return newsdatalist;
}

// Updating single contact
public int updateContact(NewsDetails contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName());

    // updating row
    return db.update(TABLE_NAME, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
}

// Deleting single contact
public void deleteContact(NewsDetails contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NAME, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
    db.close();
}

// Getting contacts Count
public int getContactsCount() {
    String countQuery = "SELECT  * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
}}

NewsDetails.java

public class NewsDetails {

//private variables
int _id;
String _name;

// Empty constructor
public NewsDetails(){

}
// constructor
public NewsDetails(int id, String name){
    this._id = id;
    this._name = name;
}

// constructor
public NewsDetails(String name){
    this._name = name;
}
// getting ID
public int getID(){
    return this._id;
}

// setting id
public void setID(int id){
    this._id = id;
}

// getting name
public String getName(){
    return this._name;
}

// setting name
public void setName(String name){
    this._name = name;
}}

1 个答案:

答案 0 :(得分:2)

似乎缺少关闭数据库处理中的光标。

例如:在您的getContact方法中,请不要忘记在返回值之前调用cursor.close()