Android 惰性加载列表-需要一些帮助吗
所以基本上每个人都需要这样做,从web或缓存中加载一些图像到listview。我发现Fedor的Lazy List是一个很好的例子,我正试图让它满足我的需要,但是我有一些问题。我的案例中的图像是加密的。所以我需要在设备上加密它们并在列表视图中显示它们。现在我得到了以下代码:Android 惰性加载列表-需要一些帮助吗,android,image,android-assets,lazylist,Android,Image,Android Assets,Lazylist,所以基本上每个人都需要这样做,从web或缓存中加载一些图像到listview。我发现Fedor的Lazy List是一个很好的例子,我正试图让它满足我的需要,但是我有一些问题。我的案例中的图像是加密的。所以我需要在设备上加密它们并在列表视图中显示它们。现在我得到了以下代码: private Bitmap getBitmap(String src) { Bitmap myBitmap = null; try { //Decryption
private Bitmap getBitmap(String src) {
Bitmap myBitmap = null;
try {
//Decryption
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
AssetManager is = this.getAssets();
InputStream input = is.open(src); //open file in asset manager
CipherInputStream cis = new CipherInputStream(input, cipher);
myBitmap = BitmapFactory.decodeStream(cis);
}
catch(Exception e){
e.printStackTrace();
Log.v("ERROR","Error : "+e);
}
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.v("ERROR","Error : "+e);
return null;
}
}
据我所知,这是不正确的(我不明白为什么,这就是我需要帮助的原因)。以下是我得到的例外:
08-11 13:38:51.163: WARN/System.err(4731): java.lang.NullPointerException
08-11 13:38:51.163: WARN/System.err(4731): at android.content.ContextWrapper.getAssets(ContextWrapper.java:74)
08-11 13:38:51.163: WARN/System.err(4731): at com.custom.lazylist.ImageLoader.getBitmap(ImageLoader.java:79)
08-11 13:38:51.163: WARN/System.err(4731): at com.custom.lazylist.ImageLoader.access$0(ImageLoader.java:70)
08-11 13:38:51.163: WARN/System.err(4731): at com.custom.lazylist.ImageLoader$PhotosLoader.run(ImageLoader.java:200)
下面是ImageLoader类的全部代码:
package com.custom.lazylist;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.fedorvlasov.lazylist.R;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
public class ImageLoader extends Activity {
//the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
private HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>();
private File cacheDir;
public ImageLoader(Context context){
//Make the background thead low priority. This way it will not affect the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
final int stub_id=R.drawable.stub;
public void DisplayImage(String url, Activity activity, ImageView imageView)
{
if(cache.containsKey(url))
imageView.setImageBitmap(cache.get(url));
else
{
queuePhoto(url, activity, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, Activity activity, ImageView imageView)
{
//This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p=new PhotoToLoad(url, imageView);
synchronized(photosQueue.photosToLoad){
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
//start thread if it's not started yet
if(photoLoaderThread.getState()==Thread.State.NEW)
photoLoaderThread.start();
}
private Bitmap getBitmap(String src) {
Bitmap myBitmap = null;
//Decryption
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
AssetManager is = this.getAssets();
InputStream input = is.open(src); //open file in asset manager
CipherInputStream cis = new CipherInputStream(input, cipher);
myBitmap = BitmapFactory.decodeStream(cis);
}
catch(Exception e){
e.printStackTrace();
Log.v("ERROR","Error : "+e);
}
return myBitmap;
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
PhotosQueue photosQueue=new PhotosQueue();
public void stopThread()
{
photoLoaderThread.interrupt();
}
//stores list of photos to download
class PhotosQueue
{
private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();
//removes all instances of this ImageView
public void Clean(ImageView image)
{
for(int j=0 ;j<photosToLoad.size();){
if(photosToLoad.get(j).imageView==image)
photosToLoad.remove(j);
else
++j;
}
}
}
class PhotosLoader extends Thread {
public void run() {
try {
while(true)
{
//thread waits until there are any images to load in the queue
if(photosQueue.photosToLoad.size()==0)
synchronized(photosQueue.photosToLoad){
photosQueue.photosToLoad.wait();
}
if(photosQueue.photosToLoad.size()!=0)
{
PhotoToLoad photoToLoad;
synchronized(photosQueue.photosToLoad){
photoToLoad=photosQueue.photosToLoad.pop();
}
Bitmap bmp=getBitmap(photoToLoad.url);
cache.put(photoToLoad.url, bmp);
Object tag=photoToLoad.imageView.getTag();
if(tag!=null && ((String)tag).equals(photoToLoad.url)){
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
if(Thread.interrupted())
break;
}
} catch (InterruptedException e) {
//allow thread to exit
}
}
}
PhotosLoader photoLoaderThread=new PhotosLoader();
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
ImageView imageView;
public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
public void run()
{
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
imageView.setImageResource(stub_id);
}
}
public void clearCache() {
//clear memory cache
cache.clear();
//clear SD cache
File[] files=cacheDir.listFiles();
for(File f:files)
f.delete();
}
}
package com.custom.lazylist;
导入java.io.File;
导入java.io.IOException;
导入java.io.InputStream;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.util.HashMap;
导入java.util.Stack;
导入javax.crypto.Cipher;
导入javax.crypto.cipheriputstream;
导入javax.crypto.spec.IvParameterSpec;
导入javax.crypto.spec.SecretKeySpec;
导入com.fedorvlasov.lazylist.R;
导入android.app.Activity;
导入android.content.Context;
导入android.content.res.AssetManager;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.util.Log;
导入android.widget.ImageView;
公共类ImageLoader扩展活动{
//最简单的内存缓存实现。应该用SoftReference或BitmapOptions.Inpurgable(自1.6起)之类的东西来代替
私有HashMap缓存=新建HashMap();
私有文件cacheDir;
公共图像加载器(上下文){
//将后台设为低优先级。这样不会影响UI性能
photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
//查找目录以保存缓存的图像
if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_-MOUNTED))
cacheDir=新文件(android.os.Environment.getExternalStorageDirectory(),“LazyList”);
其他的
cacheDir=context.getCacheDir();
如果(!cacheDir.exists())
cacheDir.mkdirs();
}
最终int stub_id=R.drawable.stub;
public void DisplayImage(字符串url、活动活动、图像视图)
{
if(cache.containsKey(url))
setImageBitmap(cache.get(url));
其他的
{
队列照片(url、活动、图像视图);
setImageResource(存根id);
}
}
私有void queuePhoto(字符串url、活动活动、ImageView ImageView)
{
//此ImageView以前可能用于其他图像。因此队列中可能有一些旧任务。我们需要丢弃它们。
Photosque.Clean(imageView);
PhotoToLoad p=新的PhotoToLoad(url,imageView);
已同步(PhotoQueue.photosToLoad){
photoqueue.photoload.push(p);
photoqueue.phototoload.notifyAll();
}
//如果尚未启动,则启动线程
if(photoLoaderThread.getState()==Thread.State.NEW)
photoLoaderThread.start();
}
私有位图getBitmap(字符串src){
位图myBitmap=null;
//解密
试一试{
Cipher Cipher=Cipher.getInstance(“AES/CBC/NoPadding”);
SecretKeySpec keySpec=新的SecretKeySpec(“01234567890abcde”.getBytes(),“AES”);
IvParameterSpec ivSpec=新的IvParameterSpec(“fedcba9876543210.getBytes());
cipher.init(cipher.DECRYPT_模式,keySpec,ivSpec);
AssetManager is=this.getAssets();
InputStream input=is.open(src);//在资产管理器中打开文件
CipherInputStream cis=新的CipherInputStream(输入,密码);
myBitmap=BitmapFactory.decodeStream(cis);
}
捕获(例外e){
e、 printStackTrace();
Log.v(“错误”,“错误:+e”);
}
返回我的位图;
}
//队列的任务
私有类光电负载
{
公共字符串url;
公共影像视图;
公共PhotoToLoad(字符串u,图像视图i){
url=u;
imageView=i;
}
}
PhotosQueue PhotosQueue=新的PhotosQueue();
公共void stopThread()
{
photoLoaderThread.interrupt();
}
//存储要下载的照片列表
类队列
{
私有堆栈photoload=新堆栈();
//删除此ImageView的所有实例
公共空间清理(图像视图图像)
{
对于(int j=0;j有两件事不对:
如果ImageLoader不是活动,则不应扩展活动(如您所确认的)。每当您发现自己需要在不应该是活动的对象中扩展活动时,您需要一个上下文。通常,将上下文另存为成员变量private Context mContext;
,然后将遇到问题的行更改为AssetManager is=this.mContext.getAssets()
这在您的情况下不起作用。您需要使用AsyncTask或将ImageLoader转换为服务。问题是您需要后台线程中的上下文。但是,如果创建ImageLoader(以及后台线程)的活动否则,当后台线程调用getAssetManager()
时,mContext可能不是有效的上下文。如果将其转换为服务,则服务将是有效的上下文,并为您提供访问资产管理器的权限
创建服务的确切步骤不在本回答的范围内,但您可以从服务的Android文档开始,并从那里开始:
编辑:用于备份注释的代码(如下)
事实上,我不认为把它变成一个加载图像的服务是一个好主意,因为我认为当用户切换到另一个屏幕(活动)时,加载会停止。如果用户决定返回列表视图,他们会再次开始加载。但这是我的意见,梅
...
// ***** ADDITION *****
private AssetManager mAssetManager;
public ImageLoader(Context context){
//Make the background thead low priority. This way it will not affect the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
// ***** ADDITION *****
mAssetManager = context.getAssets();
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
private Bitmap getBitmap(String src) {
Bitmap myBitmap = null;
//Decryption
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
// ***** CHANGE *****
InputStream input = mAssetManager.open(src); //open file in asset manager
CipherInputStream cis = new CipherInputStream(input, cipher);
myBitmap = BitmapFactory.decodeStream(cis);
}
catch(Exception e){
e.printStackTrace();
Log.v("ERROR","Error : "+e);
}
return myBitmap;
}
....