下载文件并在android中缓存它

时间:2015-11-26 18:36:14

标签: android android-layout android-fragments android-intent

我使用以下代码从URL下载内容n图像,它工作正常,我现在想要的是缓存DownLoadImageTask从互联网下载的图像。

还有如何从缓存中恢复并在需要的地方使用它。

public class CustomAdapter extends ArrayAdapter<MyClass> {

    ArrayList<MyClass> MyClassArrayList;
    int Resourse;
    Context context;
    LayoutInflater vi;

    public CustomAdapter(Context context, int resource, ArrayList<MyClass> objects) {
        super(context, resource, objects);
        MyClassArrayList = objects;
        Resourse = resource;
        this.context = context;
        vi = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        Toast.makeText(getContext(),"View "+ position,Toast.LENGTH_LONG).show();
        if ( convertView == null)
        {
            holder = new ViewHolder();
            convertView =   vi.inflate(Resourse,null);

            holder.field1 = (TextView) convertView.findViewById(R.id.field1);
            holder.field2 = (TextView) convertView.findViewById(R.id.field2);
            holder.image = (ImageView) convertView.findViewById(R.id.image);
            convertView.setTag(holder);

        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.field1.setText((CharSequence) MyClassArrayList.get(position).getfield1());
        holder.field2.setText((CharSequence) MyClassArrayList.get(position).getfield2());
        new DownLoadImageTask(holder.image).execute(MyClassArrayList.get(position).getImage());

        return convertView;
    }

    static class  ViewHolder{
        public ImageView image;
        public TextView field1
        public TextView field2

    }

    private class DownLoadImageTask extends AsyncTask<String,Void,Bitmap>
    {
        ImageView bmImage;
        public DownLoadImageTask(ImageView bmImage)
        {
            this.bmImage = bmImage;
        }

        @Override
        protected Bitmap doInBackground(String... urls) {
            String UrlDisplay = urls[0];
            Bitmap mIcon11 = null;
            InputStream in = null;
            try {
                in = new java.net.URL(UrlDisplay).openStream();
                mIcon11= BitmapFactory.decodeStream(in);

            } catch (IOException e) {
                e.printStackTrace();
            }
            return  mIcon11;

        }

        @Override
        protected void onPostExecute(Bitmap result) {
             bmImage.setImageBitmap(result);

        }
    }
}

请帮助

1 个答案:

答案 0 :(得分:0)