【问题标题】:android:load images from url and show in gridviewandroid:从 url 加载图像并在 gridview 中显示
【发布时间】:2026-01-27 08:10:01
【问题描述】:

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

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;
         }
  }
}   
 }

【问题讨论】:

  • 请编辑您的问题并删除所有与您的问题无关的代码。当您只询问大约 10 行代码时,无需将所有代码转储到问题中。

标签: android image gridview


【解决方案1】:

我建议您检查以下从 URL 加载图像的解决方案:

  1. Android - Universal Image loader by Nostra
  2. Lazy load of images in ListView

使用通用图片加载器可以获得的结果:

【讨论】:

  • @user775 很高兴您得到了解决方案 :) 干杯!!
【解决方案2】:

用 url 调用这个函数你会得到 Drawable ,然后把这个 drawables 存储到自定义类中,然后放在网格视图中。 像这样调用函数

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;
    }
}   

【讨论】:

  • Can you elobrate 意思是在我的代码中在哪里写上面的代码以及接下来要做什么
【解决方案3】:

https://github.com/koush/UrlImageViewHelper

UrlImageViewHelper 将使用在 URL 中找到的图像填充 ImageView。

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

UrlImageViewHelper 将自动下载、保存和缓存 BitmapDrawables 中的所有图像 url。重复的 url 不会被加载到内存中两次。位图内存使用弱引用哈希表进行管理,一旦图像不再被您使用,它将自动被垃圾回收。

别用这个,

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;
}

【讨论】: