我身邊追逐我的尾巴在這個相當長的一段時間。 deSelby的回答幫助了我。這是我從Facebook下載圖像(PNG和JPG)的代碼,然後使用該路徑作爲參考,從sqlite表中存儲/檢索數據。你可以看到,它實際上首先嚐試從表中讀取圖像,如果它在那裏只是返回它,否則它從Facebook獲取它,將它存儲在數據庫中,然後返回它。
private static Drawable fetchPhoto(ContentResolver cr, int source, String path) {
Drawable image = null;
myDB mDb = myDB.getInstance();
Cursor iCursor = mDb.fetchImage(cr, path);
if(iCursor != null && iCursor.moveToFirst()) {
byte[] bb = iCursor.getBlob(iCursor.getColumnIndex(Images.IMAGE));
if(iCursor != null) iCursor.close();
image = new BitmapDrawable(BitmapFactory.decodeByteArray(bb, 0, bb.length));
} else {
if(iCursor != null) iCursor.close();
//get image from path
try
{
InputStream is = (InputStream) new URL(path).getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
byte[] barray = baf.toByteArray();
bis.close();
is.close();
/* write image to db */
long id = mDb.writeImage(cr,source,path,barray);
image = new BitmapDrawable(BitmapFactory.decodeByteArray(barray, 0, barray.length));
}catch (Exception error) {
//System.out.println("Exc="+e);
}
}
return image;
}
我writeImage看起來像這樣(見下文)。
Images.IMAGE引用我表中的BLOB列的名稱。 這裏的要點是,您可以直接將byte []寫入數據庫BLOB列。 我寫的時間(utc),所以我可以根據Facebook api策略緩存數據清除舊數據。
public long writeImage(ContentResolver contentResolver, int source, String path, byte[] image) {
Time now = new Time();
now.setToNow();
ContentValues initialValues = new ContentValues();
initialValues.put(Images.IMAGE, image);
initialValues.put(Images.SOURCE, source);
initialValues.put(Images.PATH, path);
initialValues.put(Images.UTC, now.toMillis(false));
if(source == 0) initialValues.put(Images.DIRTY, 1); // sync user created images
Uri newUri = contentResolver.insert(Images.CONTENT_URI, initialValues);
String Id = newUri.getPathSegments().get(1);
return Long.parseLong(Id);
}
我使用的是內容供應商對於我的數據庫,但對於那些誰不插入代碼看起來是這樣,你可以直接使用到數據庫沒有一個供應商。 (僅供參考)。
rowId = db.insert(IMAGES_TABLE, null, values);