Naresh Sharma
Naresh Sharma

Reputation: 4323

I want to show images in a gridview from the sever means i have the URL of the images

Grid View works fine when i show the images from an array but when i tried to show the images from the server it will not worked and given a blank screen. I have the following code please tell me where i am doing something wrong.

1.Main class for the Gridview

package com.grid_example;      

import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;

public class Grid_exampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));
    }
}

2.ImageAddpter class to get the images from the server and show in a gridview

package com.grid_example;    

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    String path;
    Bitmap bmp;
    // Bitmap[] bitmapArray = new Bitmap[20];
    ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>(20);

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

    public int getCount() {
        return bitmapArray.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) {
        ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageBitmap(bitmapArray.get(position));
        return imageView;
    }

    // references to our images

    ImageAdapter() {
        String xml = XMLfunctions_wallpaper.getXML();
        Document doc = XMLfunctions_wallpaper.XMLfromString(xml);
        // Document doc = XMLfunctions.XMLfromString(this.getResources().openRawResource(R.raw.music));
        NodeList nodes = doc.getElementsByTagName("content");
        for(int i=0;i<nodes.getLength();i++){
            Element e=(Element)nodes.item(i);               
            try{
                path=XMLfunctions_wallpaper.getValue(e,"previews");
                System.out.println(path);
                URL ulrn = new URL(path);
                HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
                InputStream is = con.getInputStream();
                 bmp = BitmapFactory.decodeStream(is);
                 // Bitmap  bm = Bitmap.createBitmap(bmp);            
                 bitmapArray.add(bmp); // Add a bitmap          
            }catch(Exception e1){}              
        }
    }
}

3.XMLFunction_wallpaper class for the parsing of the images

    package com.grid_example;

    import java.io.IOException;
    import java.io.StringReader;
    import java.io.UnsupportedEncodingException;
    import java.net.MalformedURLException;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;    

    public class XMLfunctions_wallpaper {

    public final static Document XMLfromString(String xml){

        Document doc = null;

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is); 

        } catch (ParserConfigurationException e) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        } catch (SAXException e) {
            System.out.println("Wrong XML file structure: " + e.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("I/O exeption: " + e.getMessage());
            return null;
        }

        return doc;

    }

    /** Returns element value
      * @param elem element (it is XML tag)
      * @return Element value otherwise empty String
      */
     public final static String getElementValue( Node elem ) {
         Node kid;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
                     if( kid.getNodeType() == Node.TEXT_NODE  ){
                         return kid.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     public static String getXML(){  
            String line = null;

            try {

                DefaultHttpClient httpClient = new DefaultHttpClient();
                //HttpPost httpPost = new HttpPost("http://hellosunshine.in/keyss/music.xml");
                HttpPost httpPost = new HttpPost("http://m.hellosunshine.in/content/wallpaper.xml");

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                line = EntityUtils.toString(httpEntity);

            } catch (UnsupportedEncodingException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (MalformedURLException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            } catch (IOException e) {
                line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
            }

            return line;    
    }

    public static int numResults(Document doc){     
        Node results = doc.getDocumentElement();
        int res = -1;

        try{
            res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
        }catch(Exception e ){
            res = -1;
        }

        return res;
    }

    public static String getValue(Element item, String str) {       
        NodeList n = item.getElementsByTagName(str);        
        return XMLfunctions_wallpaper.getElementValue(n.item(0));
    }    
}

4.My layout for gridview

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>

Any help is appreciated.

Upvotes: 2

Views: 1368

Answers (1)

0xC0DED00D
0xC0DED00D

Reputation: 20348

If the image URL you are getting from parsing XML is correct then you can make an array of Bitmaps first and then pass it to your Adapter. The code to convert URL into Bitmaps is as follows: (In case you don't have it.)

public static Bitmap getBitmapFromURL(String src) {
    try {
        Log.d("URL",src);
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

EDIT: Here's the ArrayAdapter class which you need to use instead of BaseAdapter one.

public class CustomAdapter extends ArrayAdapter<ImageView>{
Activity context;
int linearResource;
public CustomAdapter(Context context, int resources, List<ImageView> objects){
    super(context, resources, objects);
    this.context=(Activity) context;
}
public View getView(int position, View convertView, ViewGroup parent){
    ImageView imageView;

    LayoutInflater mInflater = context.getLayoutInflater();
    if (convertView == null){
        row = getItem(position);
    }
    else{
        imageView= (ImageView) mInflater.inflate(R.layout.images, null);
        //or imageView=new imageView(context);
    }

    return imageView;
}
}

While setting the Adapter in the GridView, Use the following code.

gridView.setAdapter(new CustomAdapter(this, 0, imageData));//Where imageData is the ArraList<ImageView> type and where you've stored your ImageViews.

Upvotes: 2

Related Questions