我正在尝试从中获取图像(路径)sqldatabase
并将图像放入gridview
. 但我经常得到一个OutOfMemoryError
. 这是我的代码:
public void dos(File myDir)
{
Cursor test;
MyDB con = new MyDB(mContext);
test = con.selectImages();
List<String> array = new ArrayList<String>();
while(test.moveToNext()){
String uname = test.getString(2);
array.add(uname);
}
List<File> list = new ArrayList<File>();
for (int i = 0; i < array.size(); i++) {
list.add(new File(myDir + "/" + array.get(i)));
}
System.out.println(list);
for (File file : list) {
mThumbs.add(Drawable.createFromPath(file.getPath()));
}
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(230, 310));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageDrawable(mThumbs.toArray(new Drawable[list.size()])[position]);
return imageView;
}
这是错误:
10-12 10:56:43.820 19786-19786/de.treevo.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:530)
at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:303)
at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:329)
at android.graphics.drawable.Drawable.createFromPath(Drawable.java:916)
at de.treevo.app.ImageAdapter.dos(ImageAdapter.java:76)
at de.treevo.app.main_list.onCreate(main_list.java:75)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2293)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
at android.app.ActivityThread.access$600(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1269)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5289)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
at dalvik.system.NativeStart.main(Native Method)
我在 main_list.java 中的代码:
ImageAdapter image = new ImageAdapter(this);
image.dos(filedir)
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(image);
我的问题:我该怎么做才能让它在没有任何内存不足错误的情况下正常工作。我的测试设备是 Google 的 Nexus 7。
编辑:感谢您的回复meredrica。当每个图像都保存在内存中时,这就解释了很多。我的新问题:id 还能从数据库中读取图像名称并将它们放在网格视图中吗?