2012-12-15 40 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

上述教程中的建议解决方案有效。