2

i am making an app in which i have to get response from xml and i get image urls .Now i want to put images from urls into gridview but i dnt know how to extract images from urls and put in gridview.Any help will be appreciated.My code is as follows:

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;
         }
  }
}   
 }
RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166
  • 1
    Please edit your question and remove all code that's not related to your question. There's no need to dump all your code into the question when you're only asking about 10 lines of it. – Aleks G Mar 15 '12 at 09:47

3 Answers3

9

I would suggest you to check below solutions for loading images from URL:

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

Result you can get if you use Universal image loader:

enter image description here

Community
  • 1
  • 1
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
0

call this function with url you will get Drawable , and then store this drawables into custom class and then place in grid view. call function like this

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;
    }
}   
RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166
  • Can you please elobrate means where to write the above code in my code and what to do next –  Mar 15 '12 at 10:00
0

https://github.com/koush/UrlImageViewHelper

UrlImageViewHelper will fill an ImageView with an image that is found at a URL.

The sample will do a Google Image Search and load/show the results asynchronously.

UrlImageViewHelper will automatically download, save, and cache all the image urls the BitmapDrawables. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically.

else use this,

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;
}
Karthi
  • 13,624
  • 10
  • 53
  • 76