从CACHE(SQLITE)中获取详细信息并显示在ANDROID中

时间:2012-08-22 15:18:57

标签: android sqlite caching cursor sqliteopenhelper

我的数据库中有两个表,我的代码具有通过检查任何表中的状态来获取任何表的详细信息的逻辑。这发生在两个班级。 当我第一次启动应用程序时,它将从缓存中获取所有详细信息,直到某个时间,然后停止。在另一个类中,相同的逻辑运行但工作正常。 我几乎花了两天时间来解决它,但没有运气。这里附加了我的Logcat和代码。请有人帮忙。 感谢

SQLITEHELPER CLASS

public MysqliteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
         //this.myDatabase = this.getWritableDatabase();
    }

    /*
     * public void SQLiteDatabase(){
     * 
     * }
     */
    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(STORE_CACHE_BOOK_TABLE_CREATE);
        database.execSQL(STORE_CACHE_COMMENTS_TABLE_CREATE);
        database.execSQL(USER_LOGIN_CREDENTIALS_TABLE_CREATE);
        database.execSQL(USER_LIBRARY_DETAILS_TABLE_CREATE);
        database.execSQL(USER_STORE_DETAILS);
    }

    @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");
        // database.execSQL("DROP TABLE IF EXISTS " + StoreBookCache);
        onCreate(db);
    }

    /* Insert Values for Book_DESCRIPTION_OF_STORE */

    public void insertStoreBookDetailsIntoCache(String prod_str_Id,
            String prod_str_desc, String prod_str_Name, String prod_str_author,
            String prod_str_price, String prod_str_currency)
            throws SQLException {
        myDatabase = this.getWritableDatabase();


        Log.d("INeer'", "INSERT METHOD" + myDatabase.getPageSize());

        ContentValues contentValues = new ContentValues();
        // Put the values for Store Table.
        contentValues.put(CONST_STR_BOOK_ID, prod_str_Id);
        contentValues.put(CONST_STR_PROD_DESCR, prod_str_desc);
        contentValues.put(CONST_STR_PROD_NAME, prod_str_Name);
        contentValues.put(CONST_STR_PROD_AUTHOR, prod_str_author);
        contentValues.put(CONST_STR_PROD_PRICE, prod_str_price);
        contentValues.put(CONST_STR_PROD_CUR, prod_str_currency);

        myDatabase
                .insertOrThrow(CONST_TABLE_STORE_DETAILS, null, contentValues);

    //myDatabase.close();

    }
    public static final String Book_STR_Id = "book_str_Id";
    public static final String Book_STR_des = "book_str_des";
    public static final String Book_STR_name = "book_str_name";
    public static final String Book_STR_author = "book_str_author";
    public static final String Book_STR_price = "book_str_price";
    public static final String Book_STR_curr = "book_str_curr";

    public  Map<String, String> getStoreItemsDetails_FromCache(String Bookstrid) {
        Map<String, String> storeItemsDetails = new HashMap<String, String>();
        myDatabase = this.getReadableDatabase();
        /*final String IS_BOOK_IN_STR_CACHE_DETAILS = "SELECT  * FROM  "
            + CONST_TABLE_STORE_DETAILS + " WHERE "+ CONST_STR_BOOK_ID + "="+ Bookstrid;*/

    /*  Cursor cur = myDatabase.query(IS_BOOK_IN_STR_CACHE_DETAILS,
                new String[] { CONST_STR_BOOK_ID, CONST_STR_PROD_DESCR,
                        CONST_STR_PROD_NAME, CONST_STR_PROD_AUTHOR,
                        CONST_STR_PROD_PRICE, CONST_STR_PROD_CUR }, null, null,
                null, null, null, null);*/

        Cursor cur = myDatabase.query(CONST_TABLE_STORE_DETAILS,
                new String[] { CONST_STR_BOOK_ID, CONST_STR_PROD_DESCR,
                        CONST_STR_PROD_NAME, CONST_STR_PROD_AUTHOR,
                        CONST_STR_PROD_PRICE, CONST_STR_PROD_CUR }, CONST_STR_BOOK_ID + "="+ Bookstrid, null,
                null, null, null, null);


        if (cur.getCount() <= 0)
            return storeItemsDetails;

        cur.moveToFirst();
        while (!cur.isAfterLast()) {
            String book_storeId = cur.getString(0);
            String book_storedesc = cur.getString(1);
            String book_storename = cur.getString(2);
            String book_storeauthor = cur.getString(3);
            String book_storeprice = cur.getString(4);
            String book_storecurr = cur.getString(5);

            Log.d(MysqliteHelper.class.getName(), String.format(
                    "Fetched Book : %s and its cover location on SD Card :%s",
                    book_storeId, book_storedesc, book_storename,
                    book_storeauthor, book_storeprice, book_storecurr));
            storeItemsDetails.put(Book_STR_Id, book_storeId);// ,
                                                                    // book_storedesc,book_storename,book_storeauthor,book_storeprice,book_storecurr
            storeItemsDetails.put(Book_STR_des, book_storedesc);
            storeItemsDetails.put(Book_STR_name, book_storename);
            storeItemsDetails.put(Book_STR_author, book_storeauthor);
            storeItemsDetails.put(Book_STR_price, book_storeprice);
            storeItemsDetails.put(Book_STR_curr, book_storecurr);

            cur.moveToNext();
        }

        cur.close();
        // myDatabase.close();
        return storeItemsDetails;
    }

    /* Insert Values for Book_DESCRIPTION_OF_LIBRARY */

    public void insertLibraryBookDetailsIntoCache(String prod_lib_Id,
            String prod_lib_desc, String prod_lib_Name, String prod_lib_author,
            String prod_lib_price, String prod_lib_currency)
            throws SQLException {
        myDatabase = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        // Put the values for Store Table.
        contentValues.put(CONST_LIB_BOOK_ID, prod_lib_Id);
        contentValues.put(CONST_LIB_PROD_DESCR, prod_lib_desc);
        contentValues.put(CONST_LIB_PROD_NAME, prod_lib_Name);
        contentValues.put(CONST_LIB_PROD_AUTHOR, prod_lib_author);
        contentValues.put(CONST_LIB_PROD_PRICE, prod_lib_price);
        contentValues.put(CONST_LIB_PROD_CUR, prod_lib_currency);

        myDatabase.insertOrThrow(CONST_TABLE_LIBRARY_DETAILS, null,
                contentValues);
        //myDatabase.close();
    }
    public static final String Book_LIB_Id = "book_lib_Id";
    public static final String Book_LIB_des = "book_lib_des";
    public static final String Book_LIB_name = "book_lib_name";
    public static final String Book_LIB_author = "book_lib_author";
    public static final String Book_LIB_price = "book_lib_price";
    public static final String Book_LIB_curr = "book_lib_curr";
    public Map<String, String> getLibraryItemsDetails_FromCache(String BooklibId) {
        Map<String, String> libraryItemsDetails = new HashMap<String, String>();
        myDatabase = this.getReadableDatabase();
    /*   String IS_BOOK_IN_LIB_CACHE_DETAILS = "SELECT  * FROM  "
            + CONST_TABLE_LIBRARY_DETAILS + " WHERE "+ CONST_LIB_BOOK_ID +"="+ BooklibId;*/


        Cursor cur = myDatabase.query(CONST_TABLE_LIBRARY_DETAILS,
                new String[] { CONST_LIB_BOOK_ID, CONST_LIB_PROD_DESCR,
                        CONST_LIB_PROD_NAME, CONST_LIB_PROD_AUTHOR,
                        CONST_LIB_PROD_PRICE, CONST_LIB_PROD_CUR }, CONST_LIB_BOOK_ID +"="+ BooklibId , null,
                null, null, null, null);
        if (cur.getCount() <= 0)
            return libraryItemsDetails;

        cur.moveToFirst();
        while (!cur.isAfterLast()) {
            String book_libraryId = cur.getString(0);
            String book_librarydesc = cur.getString(1);
            String book_libraryname = cur.getString(2);
            String book_libraryauthor = cur.getString(3);
            String book_libraryprice = cur.getString(4);
            String book_librarycurr = cur.getString(5);

            Log.d(MysqliteHelper.class.getName(), String.format(
                    "Fetched Book : %s and its cover location on SD Card :%s",
                    book_libraryId, book_librarydesc, book_libraryname,
                    book_libraryauthor, book_libraryprice, book_librarycurr));
            libraryItemsDetails.put("book_lib_Id", book_libraryId);// ,
                                                                        // book_storedesc,book_storename,book_storeauthor,book_storeprice,book_storecurr
            libraryItemsDetails.put(Book_LIB_des, book_librarydesc);
            libraryItemsDetails.put(Book_LIB_name, book_libraryname);
            libraryItemsDetails.put(Book_LIB_author, book_libraryauthor);
            libraryItemsDetails.put(Book_LIB_price, book_libraryprice);
            libraryItemsDetails.put(Book_LIB_curr, book_librarycurr);

            cur.moveToNext();
        }

        cur.close();
        //myDatabase.close();
        return libraryItemsDetails;
    }

    /*
     * public void updateStoreCacheWithDetails(String prod_str_Id, String
     * prod_str_desc, String prod_str_Name, String prod_str_author, String
     * prod_str_price, String prod_str_currency){ Log.d(
     * MysqliteHelper.class.getName(), String.format(
     * "Local Image Location: %s, URL :%s", prod_str_Id,
     * prod_str_desc,prod_str_Name,
     * prod_str_author,prod_str_price,prod_str_currency) ); myDatabase =
     * this.getWritableDatabase(); ContentValues contentValues = new
     * ContentValues(); contentValues.put(CONST_STR_BOOK_ID, prod_str_Id);
     * contentValues.put(CONST_STR_PROD_DESCR, prod_str_desc);
     * contentValues.put(CONST_STR_PROD_NAME, prod_str_Name);
     * contentValues.put(CONST_STR_PROD_AUTHOR, prod_str_author);
     * contentValues.put(CONST_STR_PROD_PRICE, prod_str_price);
     * contentValues.put(CONST_STR_PROD_CUR, prod_str_currency);
     * 
     * 
     * myDatabase.update( CONST_TABLE_STORE_CACHE , contentValues,
     * CONST_STR_BOOK_ID+"=?", new String[] { prod_str_Id });
     * //myDatabase.close(); }
     */

    public void updateStoreCacheWithLocalImageLocation(
            String localImageLocation, String imageURLOnServer) {
        Log.d(MysqliteHelper.class.getName(), String.format(
                "Local Image Location: %s, URL :%s", localImageLocation,
                imageURLOnServer));
        myDatabase = this.getWritableDatabase();
        //SQLiteDatabase.openDatabase(DATABASE_NAME, null, 0);



        ContentValues contentValues = new ContentValues();
        contentValues.put(CONST_LOCAL_IMAGE_PATH, localImageLocation);

        myDatabase.update(CONST_TABLE_STORE_CACHE, contentValues,
                CONST_IMAGE_URL + "=?", new String[] { imageURLOnServer });
    // myDatabase.close();
    }

    public void insertStoreBookIntoCache(String bookId, String bookName,
            String author, String publisher, String description,
            String priceValue, String priceCurrency, String averageRating,
            String imageUrl, String localImagePath) throws SQLException {
        myDatabase = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        // Put the values for Store Table.
        contentValues.put(CONST_BOOK_ID, bookId);
        contentValues.put(CONST_BOOK_NAME, bookName);
        contentValues.put(CONST_BOOK_DESCRIPTION, description);
        contentValues.put(CONST_AVERAGE_RATING, averageRating);
        contentValues.put(CONST_IMAGE_URL, imageUrl);
        Log.d(MysqliteHelper.class.getName(), "Image URL is :" + imageUrl);
        myDatabase.insertOrThrow(CONST_TABLE_STORE_CACHE, null, contentValues);
        //myDatabase.close();
    }

    public boolean isStoreCacheEmpty() {
        myDatabase =this. getReadableDatabase();
        Cursor cur = myDatabase.query(CONST_TABLE_STORE_CACHE,
                new String[] { CONST_BOOK_ID }, null, null, null, null, null);
        boolean isEmpty = cur.getCount() <= 0;
        cur.close();
    //  myDatabase.close();
        return isEmpty;
    }

    public void insertStoreBookCommentsIntoCache(String comment, String userId,
            String bookId) throws SQLException {
        myDatabase = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();

        // Put the values for Store Table.
        contentValues.put(CONST_COMMENT_BOOK_ID, bookId);
        contentValues.put(CONST_COMMENT_TEXT, comment);
        contentValues.put(CONST_COMMENT_USER_ID, userId);

        myDatabase
                .insertOrThrow(CONST_TABLE_BOOK_COMMENTS, null, contentValues);
        //myDatabase.close();
    }

    public int rollBackStoreBookCacheRecord(String bookId) {
        myDatabase = this.getWritableDatabase();

        int status = myDatabase.delete(CONST_TABLE_STORE_CACHE, CONST_BOOK_ID
                + "=?", new String[] { bookId });

        //myDatabase.close();

        return status;
    }

    public Map<String, String> getStoreItemsFromCache() {
        Map<String, String> storeItems = new HashMap<String, String>();
        myDatabase = this.getReadableDatabase();
        Cursor cur = myDatabase.query(CONST_TABLE_STORE_CACHE, new String[] {
                CONST_BOOK_ID, CONST_LOCAL_IMAGE_PATH }, null, null, null,
                null, null);
        if (cur.getCount() <= 0)
            return storeItems;

        cur.moveToFirst();
        while (!cur.isAfterLast()) {
            String bookId = cur.getString(0);
            String bookCoverLocationOnSDCard = cur.getString(1);

            Log.d(MysqliteHelper.class.getName(), String.format(
                    "Fetched Book : %s and its cover location on SD Card :%s",
                    bookId, bookCoverLocationOnSDCard));
            storeItems.put(bookId, bookCoverLocationOnSDCard);

            cur.moveToNext();

        }
        cur.close();

        //myDatabase.close();
        return storeItems;
    }

    /*
     * public ArrayList getStoreBooksInCache() { myDatabase =
     * this.getReadableDatabase(); ArrayList prodIDs = new ArrayList();
     * 
     * Cursor cur = myDatabase.query( CONST_TABLE_STORE_CACHE , new String[]
     * {CONST_BOOK_ID},null, null, null, null, null); if( cur.getCount() <= 0 )
     * return prodIDs;
     * 
     * cur.moveToFirst(); while( ! cur.isAfterLast() ) {
     * prodIDs.add(cur.getString(0)); cur.moveToNext(); } cur.close(); return
     * prodIDs; }
     */

    public void insertintoUserCredentialTable(String username, String password)
            throws SQLException {
        myDatabase = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();

        contentValues.put(CUR_USERNAME, username);
        contentValues.put(CUR_PASSWORD, password);
        String countQuery = "SELECT  * FROM " + USER_LOGIN_CREDENTIALS;
        int userCount = 0;
        Cursor  cur = myDatabase.rawQuery(countQuery, null);
        System.out.println("cursor count" + cur.getCount());
        if (cur.getCount() < 1)
            userCount = 1;
        cur.close();
        if (userCount == 1)
            myDatabase.insertOrThrow(USER_LOGIN_CREDENTIALS, null,
                    contentValues);
        else
            myDatabase
                    .update(USER_LOGIN_CREDENTIALS, contentValues, null, null);
        cur.close();
        //myDatabase.close();
    }

    public static final String CONST_USER_NAME_KEY = "cached_username";
    public static final String CONST_USER_PASSWORD_KEY = "cached_password";

    public Map<String, String> getUserCreds() {
        Map<String, String> userLogs = new HashMap<String, String>();
        myDatabase = this.getReadableDatabase();
        Cursor cur = myDatabase.query(USER_LOGIN_CREDENTIALS, new String[] {
                CUR_USERNAME, CUR_PASSWORD }, null, null, null, null, null,
                null);
        // System.out.println("cursor" +cur.toString());
        Log.d("cursorrrr", cur.toString());
        // startManagingCursor(cur);
        cur.moveToFirst();
        while (!cur.isAfterLast()) {
            String cachedUsername = cur.getString(0);
            String cachedPassword = cur.getString(1);
            Log.d(MysqliteHelper.class.getName(), String.format(
                    "Fetched credentials : %s and password :%s",
                    cachedUsername, cachedPassword));
            userLogs.put(CONST_USER_NAME_KEY, cachedUsername);
            userLogs.put(CONST_USER_PASSWORD_KEY, cachedPassword);

            cur.moveToNext();


        }
        cur.close();

        //myDatabase.close();
        // myDatabase.close();
        return userLogs;

    }

    public static final int BOOK_DETAILS_IN_STORE_CACHE = 2;
    public static final int BOOK_DETAILS_IN_LIBRARY_CACHE = 1;

    private static final String IS_BOOK_IN_LIBRARY_CACHE = "SELECT " +CONST_LIB_BOOK_ID + " FROM " 
            + CONST_TABLE_LIBRARY_DETAILS + " WHERE "+  CONST_LIB_BOOK_ID +"=?";
    private static final String IS_BOOK_IN_STORE_CACHE = "SELECT " +CONST_STR_BOOK_ID + " FROM " 
            + CONST_TABLE_STORE_DETAILS + " WHERE "  + CONST_STR_BOOK_ID + "=?";

    public int isBookInCache(String bookId) {
        myDatabase = this.getReadableDatabase();
        //myDatabase = this.getWritableDatabase();
        Cursor cur = myDatabase.rawQuery(IS_BOOK_IN_LIBRARY_CACHE,
                new String[] { bookId });
        if (cur.getCount() > 0) {
            return BOOK_DETAILS_IN_LIBRARY_CACHE;
        } else {
            cur = myDatabase.rawQuery(IS_BOOK_IN_STORE_CACHE,
                    new String[] { bookId });
            if (cur.getCount() > 0) {
                return BOOK_DETAILS_IN_STORE_CACHE;
            }
        }
        cur.close();
        //myDatabase.close();
        return -1;

    } 

ACTIVITY这里检查表格中是否存在书籍

MysqliteHelper sqlhelpe = new MysqliteHelper(this);
         result = sqlhelpe.isBookInCache(Book_Id);
        Log.d("Book details are in :" + result,"");
        if (result == sqlhelpe.BOOK_DETAILS_IN_LIBRARY_CACHE) {
            BookDetailsScreen bkds=new BookDetailsScreen();
            System.out.println(Book_Id);
            // bkds.GetLibDetails(Book_Id);
            GetLibDetails(Book_Id);
            Log.d("Getting book details from Library cache","");
            // Get the details from Library cache
        } else if (result == sqlhelpe.BOOK_DETAILS_IN_STORE_CACHE) {
            GetStrDetails(Book_Id);
            Log.d("Getting book details from store cache","");
            // Get the details from Store cache
        } else {
            Log.d("Getting book details from the server","");
            new AsyncBookDetail_Store().execute("");

        }

这里有关于Acivity的详细信息:

public String GetStrDetails(String book_Id){
        // HashMap<String, String> cachedProdLib = new HashMap<String, String>();

        Map<String, String> cachestr = sqlHelper.getStoreItemsDetails_FromCache(book_Id);
        //if (!cachestr.entrySet().isEmpty()) {     //Iterator<String> LibbookIds = cachedProdList.keySet().iterator();
             //String StrBook_Id=cachedProdList.get("book_lib_Id");
            StrBook_Id=cachestr.get(MysqliteHelper.Book_STR_Id);
             //Log.d(StrBook_Id, "Book Id Fom Data base");
              StrBook_Name=cachestr.get(MysqliteHelper.Book_STR_name);
              StrBook_Desc=cachestr.get(MysqliteHelper.Book_STR_des);
              StrBook_author=cachestr.get(MysqliteHelper.Book_STR_author);
              StrBook_Price=cachestr.get(MysqliteHelper.Book_STR_price);
              StrBook_Curr=cachestr.get(MysqliteHelper.Book_STR_curr);
             Message myMessage = new Message();
                Bundle resBundle = new Bundle();
                resBundle.putString("descripti",
                        StrBook_Desc);
                resBundle.putString("book_Name",
                        StrBook_Name);
                resBundle.putString("author", StrBook_author);
                resBundle.putString("price",StrBook_Price);
                resBundle.putString("currency",
                        StrBook_Curr);

                myMessage.setData(resBundle);
                handler.sendMessage(myMessage);
        //}

        return null;

    }

场景是,最初,我将能够看到缓存中的所有细节,但有时它会停止从缓存中获取详细信息,即使它已插入。 登录CAT 08-23 03:27:32.774:E / Database(1093):从未在数据库'/data/data/com.pumpkynhead.ebookportal.ebook/databases/Books.db'上显式调用close() 08-23 03:27:32.774:E / Database(1093):android.database.sqlite.DatabaseObjectNotClosedException:应用程序未关闭此处打开的游标或数据库对象 08-23 03:27:32.774:E / Database(1093):在android.database.sqlite.SQLiteDatabase。(SQLiteDatabase.java:1810) 08-23 03:27:32.774:E / Database(1093):在android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:817) 08-23 03:27:32.774:E / Database(1093):在android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:851) 08-23 03:27:32.774:E / Database(1093):在android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:844) 08-23 03:27:32.774:E / Database(1093):在android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:540) 08-23 03:27:32.774:E / Database(1093):在android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203) 08-23 03:27:32.774:E / Database(1093):在android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98) 08-23 03:27:32.774:E / Database(1093):在android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:158) 3月8日至23日:27:32.774:E /数据库(1093):在com.pumpkynhead.ebookportal.ebook.util.MysqliteHelper.isBookInCache(MysqliteHelper.java:510) 3月8日至23日:27:32.774:E /数据库(1093):在com.pumpkynhead.ebookportal.ebook.BookDetailsS​​creen_Store.onCreate(BookDetailsS​​creen_Store.java:104) 08-23 03:27:32.774:E / Database(1093):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 08-23 03:27:32.774:E / Database(1093):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 08-23 03:27:32.774:E / Database(1093):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 08-23 03:27:32.774:E / Database(1093):在android.app.ActivityThread.access $ 2300(ActivityThread.java:125) 08-23 03:27:32.774:E / Database(1093):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:2033) 08-23 03:27:32.774:E / Database(1093):在android.os.Handler.dispatchMessage(Handler.java:99) 08-23 03:27:32.774:E / Database(1093):在android.os.Looper.loop(Looper.java:123) 08-23 03:27:32.774:E / Database(1093):在android.app.ActivityThread.main(ActivityThread.java:4627) 08-23 03:27:32.774:E / Database(1093):at java.lang.reflect.Method.invokeNative(Native Method) 08-23 03:27:32.774:E / Database(1093):at java.lang.reflect.Method.invoke(Method.java:521) 3月8日至23日:27:32.774:E /数据库(1093):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:868) 08-23 03:27:32.774:E / Database(1093):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 08-23 03:27:32.774:E / Database(1093):at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

通常,没有理由关闭数据库,特别是如果您需要在不同的地方不时访问它。

此外,您需要确保使用SQLiteOpenHelper类的单个实例,因为不支持对同一个数据库使用多个SQLiteOpenHelper实例,这会导致您面临的问题。