Android异步从网络下载图片并且缓存图片到本地的demo

luxiaojie 发布于 2012/12/21 21:35
阅读 3K+
收藏 0
@Simpleness 你好,想跟你请教个问题:

我是一个刚学习android的小白。看了你 Android异步从网络下载图片并且缓存图片到本地的demo这篇文章后,想把自己学着写的的一个代码做下修改,但是不知道从什么地方开始把图片加到缓存文件夹,如果可以的话麻烦指出一下
package travel.ui;

import travel.bll.Json;
import travel.ui.R;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewSwitcher;

public class Food extends Activity implements
    AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory
{
  private ImageSwitcher mSwitcher;
  private Gallery myGallery;
  private String sid=null;
  TextView name=null;
  TextView js=null;
  private List<String> myImageURL ;
  private List<String> foodid ;
 
  private List<String> myImageURL01;

  /**
   * 初始化方法,读取网络地址,解析XML数据
   * @param url
   */
  private void init(String url) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Log.e("urlvalue", url);
    myImageURL = new ArrayList<String>();
    myImageURL01 = new ArrayList<String>();
    foodid= new ArrayList<String>();
   
    InputStream is = null;
    try {
      
      HttpClient client = new DefaultHttpClient();
      try {
        //向指定的url发送http请求
        HttpResponse response = client.execute(new HttpGet(url));
        //取得服务器返回的响应
        HttpEntity entity = response.getEntity();
//        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
        is=entity.getContent();
        
      } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      System.out.println(is);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(is);
        System.out.println(document+"document");
        Element root = document.getDocumentElement();
        System.out.println(root+"root");
        NodeList imageNode = root.getElementsByTagName("img");
        System.out.println(imageNode.getLength()+"长度");
        for (int i=0;i<imageNode.getLength();i++){
            Element imageElement = (Element)imageNode.item(i);
            if("img".equals(imageElement.getNodeName())){
              NodeList properties = imageElement.getChildNodes();
              for (int j=0;j<properties.getLength();j++){
                Node property = properties.item(j);
                if(property.getNodeType()==Node.ELEMENT_NODE){
                  Element childElement = (Element)property;
                  if ("icon".equals(childElement.getNodeName())){
                       myImageURL.add(childElement.getFirstChild().getNodeValue());
                     } else if("src".equals(childElement.getNodeName())) {
                       myImageURL01.add(childElement.getFirstChild().getNodeValue());
                  }
                     else if ("id".equals(childElement.getNodeName())){
                    	 foodid.add(childElement.getFirstChild().getNodeValue());
                     }
                }
              }
            } else if ("count".equals(imageElement.getNodeName())){
              Integer.parseInt(imageElement.getNodeValue());
            }
            
            
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally{
      try{
        if(is != null){
          is.close();
        }
      }catch (Exception e) {
        // TODO: handle exception
      }
    }
    
  }
  
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.food);
    
    Intent a =getIntent();
    Json ss =new Json();
	int food_id =a.getIntExtra("food_id",1);
    if(food_id==1)
    {
    	 init("http://"+ss.ip+"/admin/xml/food/cjxc.xml");
    }
    else if(food_id==2)
    {
    	 init("http://"+ss.ip+"/admin/xml/food/tsyx.xml");
    }
    else if(food_id==3)
    {
    	 init("http://"+ss.ip+"/admin/xml/food/xcmj.xml");
    }
    else
    {
    	 init("http://"+ss.ip+"/admin/xml/food/dftc.xml");
    }
    
   
    name=(TextView)findViewById(R.id.name);
    js=(TextView)findViewById(R.id.js);
js.setMovementMethod(ScrollingMovementMethod.getInstance());
    mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
    mSwitcher.setFactory(this);
    /* 设置加载Switcher的模式 */
    mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
        android.R.anim.fade_in));
    /* 设置输出Switcher的模式 */
    mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
        android.R.anim.fade_out));
    
    myGallery = (Gallery) findViewById(R.id.myGallery);
    myGallery.setAdapter(new myInternetGalleryAdapter(this));

    myGallery.setOnItemSelectedListener(this);
   
  }

  public class myInternetGalleryAdapter extends BaseAdapter
  {
    private Context myContext;
    private int mGalleryItemBackground;

    public myInternetGalleryAdapter(Context c)
    {
      this.myContext = c;
      TypedArray a = myContext
          .obtainStyledAttributes(R.styleable.Gallery);

      mGalleryItemBackground = a.getResourceId(
          R.styleable.Gallery_android_galleryItemBackground, 0);

      a.recycle();
    }

    public int getCount()
    {
      return myImageURL.size();
    }

    public Object getItem(int position)
    {
      return position;
    }

    public long getItemId(int position)
    {
      return position;
    }

    public float getScale(boolean focused, int offset)
    {
      return Math.max(0, 1.0f / (float) Math.pow(2, Math
          .abs(offset)));
    }

    public View getView(int position, View convertView,
        ViewGroup parent)
    {
      
      ImageView imageView = new ImageView(this.myContext);
      
      try
      {
        URL aryURI = new URL(myImageURL.get(position));
        URLConnection conn = aryURI.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        Bitmap bm = BitmapFactory.decodeStream(is);
        is.close();
        imageView.setImageBitmap(bm);
      } catch (IOException e)
      {
        e.printStackTrace();
      }

      imageView.setScaleType(ImageView.ScaleType.FIT_XY);
      imageView.setLayoutParams(new Gallery.LayoutParams(130, 105));
      imageView.setBackgroundResource(mGalleryItemBackground);
      return imageView;
    }
  }

  /* 设置加载Switcher的图档 */
  public void onItemSelected(AdapterView parent, View view,
      int position, long id)
  {

    try
    {
      URL sURI = new URL(myImageURL01.get(position));
      sid= foodid.get(position);
      URLConnection conn = sURI.openConnection();
      conn.connect();
      InputStream is = conn.getInputStream();
      Bitmap bm = BitmapFactory.decodeStream(is);
      is.close();
      BitmapDrawable bitDrawable = new BitmapDrawable(bm);
      mSwitcher.setImageDrawable(bitDrawable);
    } catch (Exception e)
    {
      Log.e("Error", "switch Exception");
    }
    Log.e("ABC", id + "");
   
    set(Integer.parseInt(sid));
    System.out.println(sid+"ID");
  }

  public void onNothingSelected(AdapterView<?> parent)
  {
    // TODO Auto-generated method stub

  }

  public ImageView imageView;

  /* 呈现Switcher的模式 */
  public View makeView()

  {
    imageView = new ImageView(this);

    Log.e("ABC", "begin flush");
    try
    {

      URL sURI = new URL(myImageURL01.get(0));
      URLConnection conn = sURI.openConnection();
      conn.connect();
      InputStream is = conn.getInputStream();
      Bitmap bm = BitmapFactory.decodeStream(is);
      is.close();
      imageView.setImageBitmap(bm);

    } catch (MalformedURLException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    imageView.setBackgroundColor(0xFF000000);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
   // imageView.setPadding(100, 0, 0, 10);
    imageView.setLayoutParams(new ImageSwitcher.LayoutParams(360,270));
    return imageView;
  }
  public void set(int sid)
  {
    Json ss =new Json();
    String n=ss.fanhui("sf_id",Integer.toString(sid),"http://"+ss.ip+"/admin/huoqu/hq.php?sf_id="+sid);
    System.out.println(n);
    try{
      JSONArray jArray=new JSONArray(n);
      for(int j=0;j<jArray.length();j++){
        JSONObject json_data=jArray.getJSONObject(j);
        name.setText(json_data.getString("sf_name"));
        js.setText("        "+json_data.getString("sf_describe"));
      }
    }catch(JSONException e){
      Log.e("log_tag","错误" + e.toString());
    }
  }
}

加载中
返回顶部
顶部