android中缓存并展示图片

文章标签: android,android-listview
2014-12-23 9:15:24     人阅读    

android开发中缓存图片,并展示缓存中的图片.

我现在开发中有这样一个需求,我要在ListView中展示TextView,并且根据不同的textView在 旁边展示不同的图片....

我现在的想法是通过图片懒加载的方式把图片对应的url写死到一个数组中,然后动态的创建字符串,存储到缓存中,最后显示对应的图片.

我的代码如下:

public class Tools_ListItemActivity extends ListActivity
{
    private Context context;
    String s;

    private static final String TAG_POSTS = "posts";
    private static final String TAG_MDNAME = "mdname";
    private static final String TAG_UTCOST = "utcost";
    private static final String TAG_IIMG= "iimg";
    JSONArray posts = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        s=getIntent().getExtras().getString("url");
        new ProgressTask(Tools_ListItemActivity.this).execute();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
    }

ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

     ListView lv ;



      private class ProgressTask extends AsyncTask<String, Void, Boolean> {
      private ProgressDialog dialog;

       public ProgressTask(ListActivity activity) {

       Log.i("1", "Called");
       context = activity;
       dialog = new ProgressDialog(context);
      }

       /** progress dialog to show user that the backup is processing. */

       /** application context. */
      private Context context;

       protected void onPreExecute() {
       this.dialog.setMessage("Progress start");
       this.dialog.show();
      }

       @Override
      protected void onPostExecute(final Boolean success) {
       if (dialog.isShowing()) {
        dialog.dismiss();
       }
       ListAdapter adapter = new SimpleAdapter(context, jsonlist,
         R.layout.activity_toolsitem, new String[] { TAG_IIMG, TAG_MDNAME, TAG_UTCOST  }, new int[] {
           R.id.imageViewUrl, R.id.mdname, R.id.utcost });

        setListAdapter(adapter);

        // selecting single ListView item
        lv = getListView();

      }

       protected Boolean doInBackground(final String... args) {

        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(s);


        try {
            posts = json.getJSONArray(TAG_POSTS);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try
        {
        // looping through All Contacts
        for(int i = 0; i < posts.length(); i++){
            JSONObject c = posts.getJSONObject(i);

            // Storing each json item in variable
            String mdname = c.getString(TAG_MDNAME);
            String utcost= c.getString(TAG_UTCOST);
            String iimg=c.getString(TAG_IIMG);

            //Forming the Url of the image to be shown in the list view
            String imageUrl="My_App_URL"+iimg;

/*  try {



              String imageUrl="My_App_URL"+iimg;
 
              ImageView imageView = (ImageView)findViewById(R.id.imageViewUrl);
 
              Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
 
              imageView.setImageBitmap(bitmap); 
 
            } catch (MalformedURLException e) {
 
              e.printStackTrace();
 
            } catch (IOException e) {
 
              e.printStackTrace();
 
            } */


            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_MDNAME, mdname);
            map.put(TAG_UTCOST, utcost);
            map.put(TAG_IIMG, iimg);



         jsonlist.add(map);
        } }catch (JSONException e)
        {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }


        return null;


       }

      }

在这里,我已经调试,发现imageUrl 得到正确形成。 JSON只返回JPG的名字,所以我追加了对URL并将其存储在imageUrl 。另外两个textviews正确的进行了解析和展示。我想再就是不知道如何在imageView中正确的显示image。

 

处理方法

通过 Universal Imageloader 懒加载图片,用图片的url替换写死的  urls

简单的改变下面的代码来适配你的需求
我给你提供一个完成的图片展示解决方案:


MainActivity.java 代码如下

public class MainActivity extends Activity {

  private String[] mStrings={
            "http://xxx/profile_images/670625317/aam-logo-v3-twitter.png",
            "http://xxx/profile_images/740897825/AndroidCast-350_normal.png",
            "http://xxx/profile_images/121630227/Droid_normal.jpg",
            "http://a1.xxx/profile_images/957149154/twitterhalf_normal.jpg",
            "http://a1.xxx/profile_images/97470808/icon_normal.png",
            "http://xxx/profile_images/511790713/AG.png",
            "http://xxx/profile_images/956404323/androinica-avatar_normal.png",
            "http://a1.xxx/profile_images/909231146/Android_Biz_Man_normal.png",
            "http://xxx/profile_images/72774055/AndroidHomme-LOGO_normal.jpg",
            "http://a1.xxx/profile_images/349012784/android_logo_small_normal.jpg",
            "http://a1.xxx/profile_images/841338368/ea-twitter-icon.png",
            "http://xxx/profile_images/64827025/android-wallpaper6_2560x160_normal.png",
            "http://xxx/profile_images/77641093/AndroidPlanet_normal.png",
            "http://a1.xxx/profile_images/605536070/twitterProfilePhoto_normal.jpg",
            "http://a1.xxx/profile_images/850960042/elandroidelibre-logo_300x300_normal.jpg",
            "http://a1.xxx/profile_images/655119538/andbook.png",
            "http://xxx/profile_images/768060227/ap4u_normal.jpg",
            "http://a1.xxx/profile_images/74724754/android_logo_normal.png",
            "http://xxx/profile_images/681537837/SmallAvatarx150_normal.png",
            "http://a1.xxx/profile_images/63737974/2008-11-06_1637_normal.png",
            "http://xxx/profile_images/548410609/icon_8_73.png",
            "http://a1.xxx/profile_images/612232882/nexusoneavatar_normal.jpg",
            "http://a1.xxx/profile_images/213722080/Bugdroid-phone_normal.png",
            "http://a1.xxx/profile_images/645523828/OT_icon_090918_android_normal.png",
            "http://xxx/profile_images/64827025/android-wallpaper6_2560x160_normal.png",
            "http://xxx/profile_images/77641093/AndroidPlanet.png",
            "http://a1.xxx/profile_images/605536070/twitterProfilePhoto_normal.jpg",
            "http://a1.xxx/profile_images/850960042/elandroidelibre-logo_300x300_normal.jpg",
            "http://a1.xxx/profile_images/655119538/andbook_normal.png",
            "http://xxx/profile_images/511790713/AG_normal.png",
            "http://xxx/profile_images/956404323/androinica-avatar.png",
            "http://a1.xxx/profile_images/909231146/Android_Biz_Man_normal.png",
            "http://xxx/profile_images/72774055/AndroidHomme-LOGO_normal.jpg",
            "http://a1.xxx/profile_images/349012784/android_logo_small_normal.jpg",
            "http://a1.xxx/profile_images/841338368/ea-twitter-icon_normal.png",
            "http://xxx/profile_images/64827025/android-wallpaper6_2560x160_normal.png",
            "http://xxx/profile_images/77641093/AndroidPlanet.png",
            "http://a1.xxx/profile_images/605536070/twitterProfilePhoto_normal.jpg",
            "http://xxx/profile_images/64827025/android-wallpaper6_2560x160_normal.png",
            "http://xxx/profile_images/77641093/AndroidPlanet_normal.png",
            "http://a1.xxx/profile_images/605536070/twitterProfilePhoto_normal.jpg",
            "http://a1.xxx/profile_images/850960042/elandroidelibre-logo_300x300.jpg",
            "http://a1.xxx/profile_images/655119538/andbook_normal.png",
            "http://xxx/profile_images/511790713/AG_normal.png",
            "http://xxx/profile_images/956404323/androinica-avatar_normal.png",
            "http://a1.xxx/profile_images/909231146/Android_Biz_Man_normal.png",
            "http://xxx/profile_images/121630227/Droid.jpg",
            "http://a1.xxx/profile_images/957149154/twitterhalf_normal.jpg",
            "http://a1.xxx/profile_images/97470808/icon_normal.png",
            "http://xxx/profile_images/511790713/AG_normal.png",
            "http://xxx/profile_images/956404323/androinica-avatar_normal.png",
            "http://a1.xxx/profile_images/909231146/Android_Biz_Man.png",
            "http://xxx/profile_images/72774055/AndroidHomme-LOGO_normal.jpg",
            "http://a1.xxx/profile_images/349012784/android_logo_small_normal.jpg",
            "http://a1.xxx/profile_images/841338368/ea-twitter-icon_normal.png",
            "http://xxx/profile_images/64827025/android-wallpaper6_2560x160_normal.png",
            "http://xxx/profile_images/77641093/AndroidPlanet.png",
            "http://xxx/profile_images/670625317/aam-logo-v3-twitter_normal.png",
            "http://xxx/profile_images/740897825/AndroidCast-350_normal.png",
            "http://xxx/profile_images/121630227/Droid_normal.jpg",
            "http://a1.xxx/profile_images/957149154/twitterhalf_normal.jpg",
            "http://a1.xxx/profile_images/97470808/icon.png",
            "http://xxx/profile_images/511790713/AG_normal.png",
            "http://xxx/profile_images/956404323/androinica-avatar_normal.png",
            "http://a1.xxx/profile_images/909231146/Android_Biz_Man_normal.png",
            "http://xxx/profile_images/72774055/AndroidHomme-LOGO_normal.jpg",
            "http://a1.xxx/profile_images/349012784/android_logo_small_normal.jpg",
            "http://a1.xxx/profile_images/841338368/ea-twitter-icon.png",
            "http://xxx/profile_images/64827025/android-wallpaper6_2560x160_normal.png",
            "http://xxx/profile_images/77641093/AndroidPlanet_normal.png",
            "http://a1.xxx/profile_images/605536070/twitterProfilePhoto_normal.jpg",
            "http://a1.xxx/profile_images/850960042/elandroidelibre-logo_300x300_normal.jpg",
            "http://a1.xxx/profile_images/655119538/andbook_normal.png",
            "http://xxx/profile_images/768060227/ap4u_normal.jpg",
            "http://a1.xxx/profile_images/74724754/android_logo.png",
            "http://xxx/profile_images/681537837/SmallAvatarx150_normal.png",
            "http://a1.xxx/profile_images/63737974/2008-11-06_1637_normal.png",
            "http://xxx/profile_images/548410609/icon_8_73_normal.png",
            "http://a1.xxx/profile_images/612232882/nexusoneavatar_normal.jpg",
            "http://a1.xxx/profile_images/213722080/Bugdroid-phone_normal.png",
            "http://a1.xxx/profile_images/645523828/OT_icon_090918_android.png",
            "http://xxx/profile_images/64827025/android-wallpaper6_2560x160_normal.png",
            "http://xxx/profile_images/77641093/AndroidPlanet_normal.png",
            "http://a1.xxx/profile_images/605536070/twitterProfilePhoto_normal.jpg",
            "http://a1.xxx/profile_images/850960042/elandroidelibre-logo_300x300_normal.jpg",
            "http://a1.xxx/profile_images/655119538/andbook.png",
            "http://xxx/profile_images/511790713/AG_normal.png",
            "http://xxx/profile_images/956404323/androinica-avatar_normal.png",
            "http://a1.xxx/profile_images/909231146/Android_Biz_Man_normal.png",
            "http://xxx/profile_images/72774055/AndroidHomme-LOGO_normal.jpg",
            "http://a1.xxx/profile_images/349012784/android_logo_small_normal.jpg",
            "http://a1.xxx/profile_images/841338368/ea-twitter-icon.png",
            "http://xxx/profile_images/64827025/android-wallpaper6_2560x160_normal.png",
            "http://xxx/profile_images/77641093/AndroidPlanet_normal.png",
            "http://a1.xxx/profile_images/605536070/twitterProfilePhoto_normal.jpg",
            "http://xxx/profile_images/64827025/android-wallpaper6_2560x160_normal.png",
            "http://xxx/profile_images/77641093/AndroidPlanet_normal.png",
            "http://a1.xxx/profile_images/605536070/twitterProfilePhoto.jpg",
            "http://a1.xxx/profile_images/850960042/elandroidelibre-logo_300x300_normal.jpg",
            "http://a1.xxx/profile_images/655119538/andbook_normal.png",
            "http://xxx/profile_images/511790713/AG_normal.png",
            "http://xxx/profile_images/956404323/androinica-avatar_normal.png",
            "http://a1.xxx/profile_images/909231146/Android_Biz_Man_normal.png",
            "http://xxx/profile_images/121630227/Droid_normal.jpg",
            "http://a1.xxx/profile_images/957149154/twitterhalf.jpg",
            "http://a1.xxx/profile_images/97470808/icon_normal.png",
            "http://xxx/profile_images/511790713/AG_normal.png",
            "http://xxx/profile_images/956404323/androinica-avatar_normal.png",
            "http://a1.xxx/profile_images/909231146/Android_Biz_Man_normal.png",
            "http://xxx/profile_images/72774055/AndroidHomme-LOGO_normal.jpg",
            "http://a1.xxx/profile_images/349012784/android_logo_small.jpg",
            "http://a1.xxx/profile_images/841338368/ea-twitter-icon_normal.png",
            "http://xxx/profile_images/64827025/android-wallpaper6_2560x160_normal.png",
            "http://xxx/profile_images/77641093/AndroidPlanet_normal.png"
    };

    ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv= (ListView) findViewById(R.id.lv);
    lv.setAdapter(new LazyAdapter(this,mStrings));
}
}

main activity 配置文件如下
activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/lv"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000000"
    android:focusableInTouchMode="false"
    android:listSelector="@android:color/transparent"
    android:layout_weight="2.0"
    android:divider="#000000"
    android:headerDividersEnabled="false"
    android:footerDividersEnabled="false"
    android:dividerHeight="8dp"
    android:drawSelectorOnTop="false"
    />
</RelativeLayout>

android 延迟加载对应的适配器
LazyAdapter.java

public class LazyAdapter extends BaseAdapter {

private Activity activity;
private String data[];
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
DisplayImageOptions options;

public LazyAdapter(Activity a, String[] d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    File cacheDir = StorageUtils.getOwnCacheDirectory(a, "MyFolderCache");


 //    获得单例模式  ImageLoader
   imageLoader = ImageLoader.getInstance();
 // 为 ImageLoader 创建 configuration
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
              // You can pass your own memory cache implementation
             .discCacheExtraOptions(1024, 1024, CompressFormat.PNG, 100)
             .discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation
             .discCacheFileNameGenerator(new HashCodeFileNameGenerator())
             .enableLogging()
             .build();
 //   通过刚才创建的 configuration 初始化 ImageLoader
 imageLoader.init(config);
    //imageLoader.init(ImageLoaderConfiguration.createDefault(a));
   // imageLoader=new ImageLoader(activity.getApplicationContext());
    options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.ic_launcher)
    .cacheInMemory()
    .cacheOnDisc()
    .displayer(new RoundedBitmapDisplayer(20))
    .build();
}



public int getCount() {
    return data.length;
}

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

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

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    ViewHolder vh = new ViewHolder();;
    if(convertView==null)
    {

    vi = inflater.inflate(R.layout.row, null);
    vh.iv=(ImageView)vi.findViewById(R.id.ivv);
    vh.pb= (ProgressBar)vi.findViewById(R.id.pb);
    vh.tv = (TextView) vi.findViewById(R.id.textView1);
    vh.tv1= (TextView) vi.findViewById(R.id.textView2);

    }
    vh.tv.setText("Image in postion =");
    vh.tv1.setText(""+position);
    display(vh.iv, data[position], vh.pb);
    //imageLoader.displayImage(data.get(position).toString(), image,options);

    return vi;
}

public void display(ImageView img, String url, final ProgressBar spinner)
{
    imageLoader.displayImage(url, img, options, new ImageLoadingListener() {
        @Override
        public void onLoadingStarted(String imageUri, View view) {
         spinner.setVisibility(View.VISIBLE);
        }
        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
         spinner.setVisibility(View.GONE);


        }
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
         spinner.setVisibility(View.GONE);
        }
        @Override
        public void onLoadingCancelled(String imageUri, View view) {

        }

});
}
 public static class ViewHolder
 {
  ImageView iv;
  TextView tv,tv1;
  ProgressBar pb;

 }
}


row.xml 配置文件如下

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:src="@drawable/ic_launcher" />
 <ProgressBar
    android:id="@+id/pb"
    android:layout_centerInParent="true"
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

 <TextView
     android:id="@+id/textView1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_above="@+id/textView2"
     android:layout_alignParentLeft="true"
     android:layout_marginBottom="21dp"
     android:layout_marginLeft="31dp"
     android:text="TextView" />

 <TextView
     android:id="@+id/textView2"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/textView1"
     android:layout_alignParentBottom="true"
     android:text="TextView" />

  </RelativeLayout>


permission in manifest

<uses-permission android:name="android.permission.INTERNET"/>


 


原文地址:http://www.itmmd.com/201412/363.html
该文章由 萌萌的IT人 整理发布,转载须标明出处。

Android 截取 Bitmap   上一篇
下一篇  android中以最好的方式实例化 Android Fragment
精彩回复
我要追加问题,请求站长解决!
姓名:       

《程序员app》专门为程序员量身定做!