【发布时间】:2013-10-04 16:34:32
【问题描述】:
我正在寻找解决方案,以超过 5 秒(这是我现在正在加载的秒数)从 SQLite 加载 20 个项目。首先,我使用的是自定义 Listview 适配器。
我在 1 秒内加载了 5 个项目。我尝试加载 20 个项目,并在 5 秒内加载它们。 这是我从数据库中检索的字段:int、String、String、int、Bytes、float、int。
如你所想,得到字节后我将它们转换为位图。
Bitmap image = convertBlobToImage(cursor.getBlob(4));
// Using this function:
public Bitmap convertBlobToImage(byte[] value){
byte[] new_value = Base64.decode(value, 0);
return BitmapFactory.decodeByteArray(new_value, 0, new_value.length);
}
因此,在我的类字段中,他们将获得不是字节,而是已经获得位图。 阅读时间长的原因之一可能是位图。我刚刚对Paint进行了测试。我保存了两个相同的图像,一个在 BMP 中,另一个在 JPG 中。 JPG 图像大小为 2,87KB,BMP 420KB!!
使用上面的代码,我得到的结果是什么?可能的解决方案之一是:http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/?
你们怎么看?谢谢。
编辑: 我正在搜索,我发现了关于 onDestroy() 的信息。我也没有实现“runOnUiThread”,我就是这样说的。但我认为并没有给我带来更好的结果。你怎么看?这能提高性能吗?
@Override
protected void onDestroy() {
super.onDestroy();
listView.setAdapter(null);
}
// And I also tried to put runOnUiThread:
runOnUiThread(new Runnable() {
@Override
public void run() {
Bundle extras = getIntent().getExtras();
if (extras != null) {
DatabaseHandler db = new DatabaseHandler(Produtos.this);
display_products = db.get_all_oc_product(extras.getString("category_id"));
listView = (ListView) findViewById(R.id.product_listview);
inputSearch = (EditText) findViewById(R.id.product_inputSearch);
adapter = new itemAdapter(Produtos.this,R.layout.row, display_products);
listView.setAdapter(adapter);
}
}
});
编辑 (2):我设法将显示 20 个项目的时间缩短了 3 秒。我通过在查询后关闭与数据库的所有连接来实现这一点。我没有正确地做到这一点。 正确方法:
cursor db.query(...)
try{
// Code
} finally {
cursor.close();
db.close();
}
编辑 (3):除了编辑 (2) 上的解决方案之外,我发现的问题之一是图像问题。 所以,我开始看它们,我看到了 2000x1800 和 300kb 甚至更大的图像,我很快发现问题就在这里。
因此,在 PHP 网络服务中,我开发了一个函数来将图像大小调整为一半并将它们转换为 jpg。
function resize($filePath){
list($width, $height) = getimagesize($filePath);
$percent = 0.5;
$newwidth = $width * $percent;
$newheight = $height * $percent;
$thumb = imagecreatetruecolor($newwidth, $newheight);
$ext = pathinfo($filePath, PATHINFO_EXTENSION);
$source = null;
if($ext == "png"){
$source = imagecreatefrompng($filePath);
}else if($ext == "jpg" || $ext == "jpeg"){
$source = imagecreatefromjpeg($filePath);
}
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
$temporary = "C:\\xampp\\htdocs\\MyExample\\images\\temporary\\" . basename($filePath);
imagejpeg($thumb, $temporary . ".jpg", 50);
ImageDestroy($thumb);
return $temporary . ".jpg";
}
使用这个解决方案,我减少了惊人的 1 秒加载 47 个项目的时间!!
【问题讨论】:
-
你真的需要将它们存储在数据库中吗?
-
我认为您应该学习如何使用 Traceview 并找出问题所在,而不仅仅是猜测:developer.android.com/tools/debugging/debugging-tracing.html
-
通常 blob 不存储在数据库中。
-
@SnakeDoc 但它通过 DB API,对吗? (另外,数据库存储为文件,如果我想这样看的话......)
-
除了在 Android 生命周期中关闭数据库,而不是 Java - 即在
Activity.onStop()中。 JVM 终止不一定发生在 Android 中