在content provider中使用大型二进制文件
如果在content provider中使用小的二进制文件,可以参见在content provider中使用二进制数据。如果过大,可能会引起OutOfMemory错误。可以考虑把这些过大的文件保存在文件系统中,而不是sqlite数据库中。
本文实现代码的效果和在content provider中使用二进制数据中相同,区别是二进制的图像文件不再保存在sqlite数据库中,表中只保存一个特征码字符串,其实也可不用,直接用id。然后把图片保存在/data/data/your.package/files目录下。特征码就是用于定义该目录下具体的文件名的。
首先,修改表结构:
database.execSQL("create table if not exists emperors("
+ " id integer primary key autoincrement," + " name text,"
+ "dynasty text," + "start_year text," + "image text"
+ ");");
可以看到image字段使用文本型了。
然后,getImangeData()方法的实现发生变化:
private String getImageData(int rawId) {
String uri = "";
InputStream inputStream = context.getResources().openRawResource(
rawId);byte[] data = new byte[1024 * 100];
try {
FileOutputStream outputStream = context.openFileOutput(rawId
+ ".png", Activity.MODE_WORLD_WRITEABLE);
for (int i = inputStream.read(data); i > 0; i = inputStream
.read(data)) {
outputStream.write(data, 0, i);
}inputStream.close();
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return rawId + ".png";
}
这样做,是将图片文件保存到应用的files目录下。
使用content provider的代码:
this.imageView = new ImageView(this);
try {
this.imageView
.setImageDrawable(Drawable
.createFromStream(
getContentResolver()
.openInputStream(
Uri
.withAppendedPath(
MyContentProvider.CONTENT_URI,
cursor
.getString(cursor
.getColumnIndex(MyContentProvider.IMAGE)))),
"a.png"));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
源代码见:
http://easymorse.googlecode.com/svn/tags/content.provider-0.5.0/
本文参考了:
- http://www.techjini.com/blog/2009/01/10/android-tip-1-contentprovider-accessing-local-file-system-from-webview-showing-image-in-webview-using-content/
- http://www.saturn.dti.ne.jp/~npaka/android/FileProviderEx/index.html
这篇文章上的评论的 RSS feed TrackBack URI