Android:在imageview中显示来自网址的图片

时间:2014-07-26 11:25:09

标签: android image url imageview

截图
Gridview Example

我一直在尝试在这个GirdView中显示来自url的图像。某些图像看起来很好,但有些图像没有正确显示。我还将图像保存在缓存中,以便下次更快地显示图像。这是我的代码。

MainActivity.java

package com.example.gridview;


public class MainActivity extends Activity {

ArrayList<String> imageList = new ArrayList<String>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    imageList
    .add("http://wallpapersus.com/wallpapers/2012/10/Megan-Fox-22-854x960.jpg");
    imageList.add("http://www.wallpapersdesign.net
    /wallpapers/2013/12/Transformers-Megan-Fox-854x960.jpg");
    imageList
            .add("http://wallpapersus.com/wallpapers/2012/10/Megan-Fox1-854x960.jpg");
    imageList
    .add("http://wallpapersus.com/wallpapers/2012/10/Megan-Fox-24-854x960.jpg");

    imageList
    .add("http://topwalls.net/wallpapers/2013/06/Wallpapers-Megan-Fox-11-854x960.jpg");
    imageList
            .add("http://topwalls.net/wallpapers/2013/06/Megan-Fox-133-854x960.jpg");


    imageList
            .add("http://topwalls.net/wallpapers/2013/06/Megan-Fox-89-854x960.jpg");

    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this, imageList));
    gridview.setOnItemClickListener(new OnImageClickListener(1));
}

class OnImageClickListener implements OnItemClickListener {

    public int position;

    // constructor
    public OnImageClickListener(int position) {
        this.position = position;
    }

    @Override
    public void onItemClick(AdapterView<?> v, View arg1, int arg2, long arg3) {
        Intent i = new Intent(getApplicationContext(),
                FullScreenViewActivity.class);
        Bundle basket = new Bundle();
        basket.putStringArrayList("url", imageList);
        basket.putString("position", String.valueOf(arg2));
        i.putExtras(basket);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplicationContext().startActivity(i);
        Log.e("Activity ImageClass", "Left from this class");
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.action_settings:
        refresh();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

    private void refresh() {

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this, imageList));
        gridview.setOnItemClickListener(new OnImageClickListener(1));
    }
}

这是适配器

package com.example.gridview;


public class ImageAdapter extends BaseAdapter {
private Activity mContext;
ArrayList<String> imageList;
ImageLoader imageLoader;
ProgressDialog progress;
int versionCode = 10;

public ImageAdapter(Activity c, ArrayList<String> imageList) {
    mContext = c;
    this.imageList = imageList;
    imageLoader = new ImageLoader(mContext, 200);
}

@Override
public int getCount() {
    return imageList.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

// create a new ImageView for each item referenced by the Adapter
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final ImageView imageView;
    if (convertView == null) { // if it's not recycled, initialize some
                                // attributes
        imageView = new ImageView(mContext);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {

            Log.e("Inside", "if");
            imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
            imageView.setId(position);
        } else {
            Log.e("Inside", "else");
            imageView.setLayoutParams(new GridView.LayoutParams(90, 90));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        }

    } else {

        imageView = (ImageView) convertView;
    }
    //imageLoader.clearCache();
    imageLoader.DisplayImage(imageList.get(position), imageView);

    return imageView;
}
}

ImageLoader.java

package com.example.gridview;

public class ImageLoader {

MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
public int REQUIRED_SIZE;
private Map<ImageView, String> imageViews = Collections
        .synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Activity context;

public ImageLoader(Activity context, int size) {
    fileCache = new FileCache(context, size);
    this.context = context;
    executorService = Executors.newFixedThreadPool(20);
    REQUIRED_SIZE = size;
}

final int stub_id = R.drawable.ic_menu_camera;

public void DisplayImage(String url, ImageView imageView) {
    imageViews.put(imageView, url);
    Bitmap bitmap = memoryCache.get(url);
    if (bitmap != null)
        imageView.setImageBitmap(bitmap);
    else {
        queuePhoto(url, imageView);
        imageView.setImageResource(stub_id);
    }
}

public void setWallpaper(String url) {
    Bitmap bitmap = memoryCache.get(url);
    if (bitmap != null) {
        WallpaperManager myWallpaperManager = WallpaperManager
                .getInstance(context);
        // below line of code will set any image which is in the
        // drawable
        // folder
        // myWallpaperManager.setResource(R.drawable.icon);
        DisplayMetrics metrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int height = metrics.heightPixels;
        int width = metrics.widthPixels;
        Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap, width, height,
                true);
        WallpaperManager wallpaperManager = WallpaperManager
                .getInstance(context);
        // wallpaperManager.setWallpaperOffsetSteps(1, 1);
        wallpaperManager.suggestDesiredDimensions(width, height);
        try {
            wallpaperManager.setBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

public void DisplayImageCircle(String url, ImageView imageView) {
    imageViews.put(imageView, url);
    Bitmap bitmap = memoryCache.get(url);
    if (bitmap != null)
        imageView.setImageBitmap(bitmap);
    else {
        queuePhoto(url, imageView);
        imageView.setImageResource(stub_id);
    }

}

private void queuePhoto(String url, ImageView imageView) {
    PhotoToLoad p = new PhotoToLoad(url, imageView);
    executorService.submit(new PhotosLoader(p));
}

private Bitmap getBitmap(String url) {
    File f = fileCache.getFile(url);

    // from SD cache
    Bitmap b = decodeFile(f);
    if (b != null)
        return b;

    // from web
    try {
        Bitmap bitmap = null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imageUrl
                .openConnection();
        conn.setConnectTimeout(6000000);
        conn.setReadTimeout(6000000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
    try {
        // decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f), null, o);

        // Find the correct scale value. It should be the power of 2.

        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE
                    || height_tmp / 2 < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {
    }
    return null;
}

// Task for the queue
private class PhotoToLoad {
    public String url;
    public ImageView imageView;

    public PhotoToLoad(String u, ImageView i) {
        url = u;
        imageView = i;
    }
}

class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;

    PhotosLoader(PhotoToLoad photoToLoad) {
        this.photoToLoad = photoToLoad;
    }

    @Override
    public void run() {
        if (imageViewReused(photoToLoad))
            return;
        Bitmap bmp = getBitmap(photoToLoad.url);
        memoryCache.put(photoToLoad.url, bmp);
        if (imageViewReused(photoToLoad))
            return;
        BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
        Activity a = (Activity) photoToLoad.imageView.getContext();
        a.runOnUiThread(bd);
    }
}

boolean imageViewReused(PhotoToLoad photoToLoad) {
    String tag = imageViews.get(photoToLoad.imageView);
    if (tag == null || !tag.equals(photoToLoad.url))
        return true;
    return false;
}

// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
    Bitmap bitmap;
    PhotoToLoad photoToLoad;

    public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
        bitmap = b;
        photoToLoad = p;
    }

    @Override
    public void run() {
        if (imageViewReused(photoToLoad))
            return;
        if (bitmap != null)
            photoToLoad.imageView.setImageBitmap(bitmap);
        else
            photoToLoad.imageView.setImageResource(stub_id);
    }
}

public void clearCache() {
    memoryCache.clear();
    fileCache.clear();
}

}

我也尝试在doInBackground()中运行imageLoader,但它没用。 请帮助!!

2 个答案:

答案 0 :(得分:1)

您可以使用第三方库从网址

加载图片

您将获得以下好处:

    Multithread image loading (async or sync)
    Wide customization of ImageLoader's configuration (thread executors, downloader, decoder, memory and disk cache, display image options, etc.)
    Many customization options for every display image call (stub images, caching switch, decoding options, Bitmap processing and displaying, etc.)
    Image caching in memory and/or on disk (device's file system or SD card)
    Listening loading process (including downloading progress)

1)Universal Image loader

2)Picasso

3)Volley

答案 1 :(得分:0)

也在ImageView中设置您的网址

imageView.setTag(yourURL);
imageLoader.DisplayImage(imageList.get(position), imageView);