Android Java编码:如何访问列表视图的下载图像

Android Java编码:如何访问列表视图的下载图像,java,android,image,listview,Java,Android,Image,Listview,通过修改教程代码来尝试不同的东西来进行工作学习。我还在认真学习阶段,所以如果这个问题听起来很无知,请原谅。我使用以下代码通过解析的XML文件下载图像文件(来自教程/示例): 我想我知道使用getResources()不是访问图像所需的。问题是我所尝试的一切都不起作用,getPath()等等。 这些图像将在应用程序中使用,但会发生更改,因此无法将其包含在apk中。还试图考虑是否安装了sd卡,因此存在不使用硬编码目录路径的问题。 我非常感谢您的建议和评论。这段代码中有很多地方不太正确。 在您学习的过

通过修改教程代码来尝试不同的东西来进行工作学习。我还在认真学习阶段,所以如果这个问题听起来很无知,请原谅。我使用以下代码通过解析的XML文件下载图像文件(来自教程/示例):

我想我知道使用
getResources()
不是访问图像所需的。问题是我所尝试的一切都不起作用,
getPath()
等等。 这些图像将在应用程序中使用,但会发生更改,因此无法将其包含在apk中。还试图考虑是否安装了sd卡,因此存在不使用硬编码目录路径的问题。
我非常感谢您的建议和评论。

这段代码中有很多地方不太正确。 在您学习的过程中,我将给您一些示例代码,这样您就可以开始并继续使用更好的方向。请注意,您的代码可以通过使用HttpUrlConnection而不是Android文档推荐的HttpClient来改进。还请注意,图像的url被转换为整数散列,因此您可以将其用作文件名。也可以使用内部或外部存储。这只是AsyncTask,我希望您多挖掘一点,自己创建映像适配器。继续

public static class ImageCacher extends AsyncTask<String, String, Integer>{

    Context context;
    ImageView iv;
    Bitmap b;


    public ImageCacher(Context context, ImageView iv){
        this.context = context;
        this.iv = iv;
    }

    @Override
    protected Integer doInBackground(String... params) {

        for(String p:params){
            //Modification to get relative urls
            final String param;
            if(!p.startsWith("http")){
                param = URL_BASE+p;
            }else{
                param = p;
            }

            //check if already CACHED
            File file = getFileForCachedImage(param);

            b = getCachedImage(file);
            if(b != null){
                if(iv != null){
                    iv.post(new Runnable() {

                        public void run() {
                            String tag = (String) iv.getTag();
                            if(tag != null){
                                if(tag.matches(param))
                                    iv.setImageBitmap(b);
                            }

                        }
                    });
                }

                return 0;
            }else{
                file.delete();
            }

            //download
            //file = new File(context.getFilesDir(), filename); //OLD way
            file = getFileForCachedImage(param);
            b = saveImageFromUrl(context, param);
            if(b != null){
                if(iv != null){
                    iv.post(new Runnable() {

                        public void run() {
                            String tag = (String) iv.getTag();
                            if(tag != null){
                                if(tag.matches(param))
                                    iv.setImageBitmap(b);
                            }

                        }
                    });
                }
            }
        }

        return 0;
    }

}

/**
 * Gets an image given its url
 * @param param
 */
public static Bitmap saveImageFromUrl(Context context, String fullUrl) {
    Bitmap b = null;

    try {
        URL url = new URL(fullUrl);
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.connect();
        //save bitmap to file
        InputStream is = conn.getInputStream();
        //String filename = String.format("%d", fullUrl.hashCode()); //ORIGINAL way
        //File file = new File(context.getFilesDir(), filename);    //original way
        File file = getFileForCachedImage(fullUrl);
        if(file.exists()){
            //delete
            file.delete();
            file=null;
        }
        //file = new File(context.getFilesDir(), filename);  //ORIGINAL way
        file = getFileForCachedImage(fullUrl);

        FileOutputStream out = new FileOutputStream(file);
        byte buffer[] = new byte[256];
        while(true){
            int cnt = is.read(buffer);
            if(cnt <=0){
                break;
            }
            out.write(buffer,0, cnt);
        }

        out.flush();
        out.close();
        is.close();

        b = BitmapFactory.decodeFile(file.getAbsolutePath());

    } catch (Exception e) {
    //  e.printStackTrace();
    }

    return b;
}

/**
 * Gets the file to cache the image
 * @param url
 * @return
 */
public static File getFileForCachedImage(String url) {

    /**
     * Modification for relative urls
     */
    if(!url.startsWith("http")){
        url = URL_BASE+url;
    }

    String filename = String.format("%d.cached", url.hashCode());

    /**
     * External storage
     */
    File file = new File(Environment.getExternalStorageDirectory(), EXT_DIR_NAME+"/"+filename);  //EXTERNAL storage
    String parent = file.getParent();
    if(parent != null){
        new File(parent).mkdirs();
    }

    /**
     * Internal storage
     */
    //File file = new File(context.getFilesDir(), filename);  //INTERNAL storage

    return file;

}

/**
 * Returns a bitmap object if cached
 * @param file
 * @return
 */
public static Bitmap getCachedImage(File file) {

    try {
        return BitmapFactory.decodeFile(file.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
公共静态类ImageCacher扩展异步任务{
语境;
ImageView iv;
位图b;
公共ImageCacher(上下文,ImageView iv){
this.context=上下文;
这4.iv=iv;
}
@凌驾
受保护的整数doInBackground(字符串…参数){
for(字符串p:params){
//修改以获取相对URL
最终字符串参数;
如果(!p.startsWith(“http”)){
param=URL_BASE+p;
}否则{
参数=p;
}
//检查是否已缓存
File File=getFileForCachedImage(参数);
b=getCachedImage(文件);
如果(b!=null){
如果(iv!=null){
四.员额(新的可运行(){
公开募捐{
String标记=(String)iv.getTag();
如果(标记!=null){
if(标记匹配(参数))
iv.设置图像位图(b);
}
}
});
}
返回0;
}否则{
delete();
}
//下载
//file=新文件(context.getFilesDir(),filename);//旧方法
file=getFileForCachedImage(参数);
b=saveImageFromUrl(上下文,参数);
如果(b!=null){
如果(iv!=null){
四.员额(新的可运行(){
公开募捐{
String标记=(String)iv.getTag();
如果(标记!=null){
if(标记匹配(参数))
iv.设置图像位图(b);
}
}
});
}
}
}
返回0;
}
}
/**
*获取给定url的图像
*@param-param
*/
公共静态位图saveImageFromUrl(上下文上下文,字符串fullUrl){
位图b=null;
试一试{
URL=新URL(完整URL);
URLConnection conn=url.openConnection();
conn.setDoInput(真);
连接();
//将位图保存到文件
InputStream is=conn.getInputStream();
//String filename=String.format(“%d”,fullUrl.hashCode());//原始方式
//File File=新文件(context.getFilesDir(),filename);//原始方式
File File=getFileForCachedImage(fullUrl);
if(file.exists()){
//删除
delete();
file=null;
}
//file=新文件(context.getFilesDir(),filename);//原始方式
file=getFileForCachedImage(fullUrl);
FileOutputStream out=新的FileOutputStream(文件);
字节缓冲区[]=新字节[256];
while(true){
int cnt=is.read(缓冲区);

如果(cnt如果你想使用ImageLoader,我强烈建议你使用。顺便说一句,你能重新格式化你的问题吗?谢谢你,Junior!肯定有更多的东西可以分解和学习。感觉很好,我实际上可以理解其中的逻辑。可能会有更多的问题,但第一个问题:为什么文件名使用哈希代码?除非你跟踪它是通过数据库表进行的,名称的更改是否会使以后的使用变得困难,回拨是否需要额外的编码?我想,当我使用下载的XML文件来处理数据时,似乎只使用名称的解析值会更简单。没有什么特别的。如果您需要,.cached扩展名将它们隐藏在库中使用外部存储。否则,你会在用户库中无缘无故地获得大量图像。如果你愿意,你甚至可以构建自己的目录结构作为缓存,但不要忘记url分隔符。好的,我正在学习!第一件事:了解Java编码约定!第二件事:将代码分成更小的块,类/片段是一个好方法第三件事:我通过编写/重写示例代码并使其工作,学习得更好。现在,如果我能掌握静态/非静态。。。。。
  String uri = "drawable/"+ downloadedImgs.get(position).get(KEY_ICON);
          int imageResource =   holwtt.getContext().getApplicationContext().getResources().getIdentifier(uri, null, holwtt.getContext().getApplicationContext().getPackageName());
          Drawable image = holwtt.getContext().getResources().getDrawable(imageResource);
          holder.firstImg.setImageDrawable(image);
public static class ImageCacher extends AsyncTask<String, String, Integer>{

    Context context;
    ImageView iv;
    Bitmap b;


    public ImageCacher(Context context, ImageView iv){
        this.context = context;
        this.iv = iv;
    }

    @Override
    protected Integer doInBackground(String... params) {

        for(String p:params){
            //Modification to get relative urls
            final String param;
            if(!p.startsWith("http")){
                param = URL_BASE+p;
            }else{
                param = p;
            }

            //check if already CACHED
            File file = getFileForCachedImage(param);

            b = getCachedImage(file);
            if(b != null){
                if(iv != null){
                    iv.post(new Runnable() {

                        public void run() {
                            String tag = (String) iv.getTag();
                            if(tag != null){
                                if(tag.matches(param))
                                    iv.setImageBitmap(b);
                            }

                        }
                    });
                }

                return 0;
            }else{
                file.delete();
            }

            //download
            //file = new File(context.getFilesDir(), filename); //OLD way
            file = getFileForCachedImage(param);
            b = saveImageFromUrl(context, param);
            if(b != null){
                if(iv != null){
                    iv.post(new Runnable() {

                        public void run() {
                            String tag = (String) iv.getTag();
                            if(tag != null){
                                if(tag.matches(param))
                                    iv.setImageBitmap(b);
                            }

                        }
                    });
                }
            }
        }

        return 0;
    }

}

/**
 * Gets an image given its url
 * @param param
 */
public static Bitmap saveImageFromUrl(Context context, String fullUrl) {
    Bitmap b = null;

    try {
        URL url = new URL(fullUrl);
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.connect();
        //save bitmap to file
        InputStream is = conn.getInputStream();
        //String filename = String.format("%d", fullUrl.hashCode()); //ORIGINAL way
        //File file = new File(context.getFilesDir(), filename);    //original way
        File file = getFileForCachedImage(fullUrl);
        if(file.exists()){
            //delete
            file.delete();
            file=null;
        }
        //file = new File(context.getFilesDir(), filename);  //ORIGINAL way
        file = getFileForCachedImage(fullUrl);

        FileOutputStream out = new FileOutputStream(file);
        byte buffer[] = new byte[256];
        while(true){
            int cnt = is.read(buffer);
            if(cnt <=0){
                break;
            }
            out.write(buffer,0, cnt);
        }

        out.flush();
        out.close();
        is.close();

        b = BitmapFactory.decodeFile(file.getAbsolutePath());

    } catch (Exception e) {
    //  e.printStackTrace();
    }

    return b;
}

/**
 * Gets the file to cache the image
 * @param url
 * @return
 */
public static File getFileForCachedImage(String url) {

    /**
     * Modification for relative urls
     */
    if(!url.startsWith("http")){
        url = URL_BASE+url;
    }

    String filename = String.format("%d.cached", url.hashCode());

    /**
     * External storage
     */
    File file = new File(Environment.getExternalStorageDirectory(), EXT_DIR_NAME+"/"+filename);  //EXTERNAL storage
    String parent = file.getParent();
    if(parent != null){
        new File(parent).mkdirs();
    }

    /**
     * Internal storage
     */
    //File file = new File(context.getFilesDir(), filename);  //INTERNAL storage

    return file;

}

/**
 * Returns a bitmap object if cached
 * @param file
 * @return
 */
public static Bitmap getCachedImage(File file) {

    try {
        return BitmapFactory.decodeFile(file.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}