android:从网址加载图片并在gridview中显示

时间:2012-03-15 09:45:49

标签: android image gridview

我正在制作一个应用程序,我必须得到xml的响应,我得到图像网址。现在我想将网址中的图像放入gridview但我不知道如何从网址中提取图像并放入gridview.Any帮助我将不胜感激。我的代码如下:

public class GalleryNewActivity extends Activity {

private ProgressDialog dialog;
GridView ga;
Element e;
Node elem;
 public List<Drawable> pictures;

ImageView imageView;
static final String PREFS_NAME = "MyPrefs";
static final String USER_KEY = "user";
static final String Name = "name";


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

       if(isNetworkconn()){
        new GetSPCAsyncTask().execute("");
    }else{
        showDialogOnNoInternet();
    }
  ga = (GridView)findViewById(R.id.Gallery01);
    ga.setAdapter(new ImageAdapter(this));
    imageView = (ImageView)findViewById(R.id.ImageView01);
    }



public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
    }

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

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

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

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        View v;

        if (convertView == null) { // if it's not recycled, initialize some
            // attributes

            LayoutInflater li = getLayoutInflater();
            v = li.inflate(R.layout.galleryitem, null);
            imageView = (ImageView)v.findViewById(R.id.thumbImage);

            imageView.setLayoutParams(new GridView.LayoutParams(200, 250));

            // imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(2, 5, 2, 5);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageDrawable(pictures.get(position));
        imageView.setTag(pics[position]);

        return imageView;
    }


private class GetPicsToNextPage extends AsyncTask<String, String, String>{

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

        dialog = ProgressDialog.show(GalleryNewActivity.this, "Please wait", "Loading...");

    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        String str = null;
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        dialog.dismiss();

        Intent intent = new Intent(getApplicationContext(), Flip3d.class);
        startActivity(intent);

    }
}

private boolean isNetworkconn(){
    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) {
        return true;
    }else{
        return false;
    }
}

private void showDialogOnNoInternet(){
    AlertDialog.Builder alt_bld = new AlertDialog.Builder(GalleryNewActivity.this);
    alt_bld.setTitle("Error.");
    alt_bld.setMessage("Your phone is not connected to internet.");
    alt_bld.setCancelable(false);
    alt_bld.setNeutralButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            dialog.dismiss();
        }
    });
    alt_bld.show();
}


//loader for dynamic starts
private class GetSPCAsyncTask extends AsyncTask<String, String, String>{

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog = ProgressDialog.show(GalleryNewActivity.this, "Please wait", "Loading...");
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
        String xml = XMLfunctions.getXML();
        Document doc = XMLfunctions.XMLfromString(xml);

        NodeList nodes = doc.getElementsByTagName("Image");

        for (int i = 0; i < nodes.getLength(); i++) {                           
            HashMap<String, String> map = new HashMap<String, String>();    

             e = (Element)nodes.item(i);

            //map.put("Image", XMLfunctions.getValue(e, "Image"));

            map.put("ImagePath", "Naam:" + XMLfunctions.getValue(e, "ImagePath"));


            map.put("ImageHeadline", "Headline: " + XMLfunctions.getValue(e, "ImageHeadline"));
            System.out.println(map.put("ImageHeadline", "Headline: " + XMLfunctions.getValue(e, "ImageHeadline")));

            map.put("ImageDesc", "Desc: " + XMLfunctions.getValue(e, "ImageDesc"));
            System.out.println(map.put("ImageDesc", "Desc: " + XMLfunctions.getValue(e, "ImageDesc")));

            mylist.add(map);

            Drawable d=LoadImageFromWebOperations();
            pictures.add(d);
        }       

    return xml;}
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        dialog.dismiss();

            }
    private Drawable LoadImageFromWebOperations()
    {
        String path=XMLfunctions.getValue(e, "ImagePath");
          try{
             InputStream is = (InputStream) new URL(path).getContent();
             Drawable d = Drawable.createFromStream(is, "src name");
             Log.w("CREADO","CREADO");
             return d;
         }catch (Exception e) {
             System.out.println("Exc="+e);
             return null;
         }
  }
}   
 }

3 个答案:

答案 0 :(得分:9)

我建议您查看以下解决方案,以便从网址加载图片:

  1. Android - Universal Image loader by Nostra
  2. Lazy load of images in ListView
  3. 如果您使用通用图像加载器,则可以得到结果:

    enter image description here

答案 1 :(得分:0)

使用url调用此函数,您将获得Drawable,然后将此drawable存储到自定义类中,然后放入网格视图中。 像这样调用函数

ImageOperations(this,imageurl)

public Object fetch(String address) throws MalformedURLException, IOException {

    URL url = new URL(address);
    Object content = url.getContent();
    return content;
}  

private Drawable ImageOperations(Context ctx, String url) {

    try {
        InputStream is = (InputStream) this.fetch(url);
        Drawable d = Drawable.createFromStream(is, "src");
        return d;
    } catch (MalformedURLException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
}   

答案 2 :(得分:0)

https://github.com/koush/UrlImageViewHelper

UrlImageViewHelper将使用在网址上找到的图片填充ImageView。

该示例将执行Google图片搜索并以异步方式加载/显示结果。

UrlImageViewHelper会自动下载,保存和缓存BitmapDrawables的所有图片网址。重复的网址不会被加载到内存中两次。位图内存通过使用弱引用哈希表进行管理,因此只要您不再使用该图像,就会自动对其进行垃圾回收。

否则使用此,

public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //options.inSampleSize = 1;

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }

    return bitmap;
}