2012-12-15 44 views
1

我試圖在我的Content Provider中存儲大文件(位圖),但不知道如何。我爲我的記錄添加了一個「_data」字段,並覆蓋了我的Content Provider的openFile()方法。如何處理「_data」字段?

public void onCreate(SQLiteDatabase db) { 
    db.execSQL("create table contact (_id integer primary key autoincrement, NAME text collate nocase, IMAGE text, _data text);"); 
} 

public ParcelFileDescriptor openFile(Uri uri, String mode) 
    throws FileNotFoundException { 

    String rowID = uri.getPathSegments().get(1); 
    String dir = Environment.DIRECTORY_PICTURES; 

    File file = new File(getContext().getExternalFilesDir(dir), rowID); 
    if (!file.exists()) { 
     try { 
      file.createNewFile(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    int fileMode = 0; 
    if (mode.contains("w")) 
     fileMode |= ParcelFileDescriptor.MODE_WRITE_ONLY; 
    if (mode.contains("r")) 
     fileMode |= ParcelFileDescriptor.MODE_READ_ONLY; 
    if (mode.contains("+")) 
     fileMode |= ParcelFileDescriptor.MODE_APPEND; 
    return ParcelFileDescriptor.open(file, fileMode); 
} 

我正在使用內容解析器的openOutputStream()方法來插入位圖。

ContentValues values = new ContentValues(); 
values.put("NAME", "abc"); 
Uri rowUri = cr.insert(MyContentProvider.CONTENT_URI, values); 
values.put("IMAGE", rowUri.toString()); 
cr.update(rowUri, values, null, null); 

InputStream inputStream = httpConnection.getInputStream(); 
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
String line = null; 
try { 
    Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://www.xyz.com/abc.jpg").getContent()); 
    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, cr.openOutputStream(rowUri)); 
} catch (MalformedURLException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

當我這樣做時,文件存儲在我的SD卡,但「_data」字段保持空白。我做錯了什麼?

我是否需要自己寫「_data」字段?根據this tutorial答案似乎是「是」。 「_data」字段在insert()方法內寫入,該文件在設備上具有確切的文件路徑。記錄中的URI引用IMAGE不是必需的。但教程已經有幾年了,我還沒有找到另一個例子,其中「_data」直接寫成這樣。有人知道一個很好的例子嗎?

回答

1

上述教程中的建議解決方案有效。