Home > Android > Android : Dynamic List View with Image and Text

Android : Dynamic List View with Image and Text

To construct dynamic list view in android ( list values from a php server page  which contains image and text as list values ) .

Here I am using Jsoup to parse the HTML elements from server php page to get image and text values and display values in Listview :

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class CurrentActivity extends Activity {

    ListView list;
    LazyAdapter adapter;
    ImageView imageView;
    private String[] mStrings=new String[12];
    private String[] tStrings=new String[12];
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.listmain);
        getList();

        list=(ListView)findViewById(R.id.list);
        adapter=new LazyAdapter(this, mStrings,tStrings);
        list.setAdapter(adapter);
        list.setClickable(true);


    	list.setOnItemClickListener(new OnItemClickListener(){
    	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
    		System.out.println("List ID value ::::::::::::::::::"+arg0.getId()+"list1::::::::::;"+arg1.getId());
    		Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
			 startActivity(myIntent);

		}
    	}); 
    }

    @Override
    public void onDestroy()
    {
        adapter.imageLoader.stopThread();
        list.setAdapter(null);
        super.onDestroy();
    }

    public OnClickListener listener=new OnClickListener(){
        public void onClick(View arg0) {
            adapter.imageLoader.clearCache();
            adapter.notifyDataSetChanged();     
        }
    };

    private void getList(){
    	int index=0;
    	int tIndex=0;
		try {
			HttpParams httpParameters = new BasicHttpParams();
			// Set the timeout in milliseconds until a connection is established.
			int timeoutConnection = 10000;
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

			// Set the default socket timeout (SO_TIMEOUT) 
			// in milliseconds which is the timeout for waiting for data.
			int timeoutSocket = 10000;
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

			Document doc = Jsoup.connect("http://host/categories.php").get();
			Elements tds = doc.select("td");
			//String[] s = (String[])tds.toArray();
			List<String> csvList = new ArrayList<String>();

			for (Element td : tds) {
				  String tdText = td.text();
				  csvList.add(td.text());
		    }
	           // SimpleAdapter adapter = new SimpleAdapter(EventList.this, fillMaps, R.layout.viewlist, from, to);

			for (int i = 2; i <= csvList.size(); i=i+3) {
				mStrings[index]=csvList.get(i).toString();
				index++;
			    System.out.println("Image String Object :::: "+mStrings);
			}

			for (int j = 1; j <= csvList.size(); j=j+3) {
				tStrings[tIndex]=csvList.get(j).toString();
				tIndex++;
			    System.out.println("Image String Object :::: "+csvList.get(j).toString());
			}

		} catch (Exception e) {
			Intent myIntent = new Intent(CurrentActivity.this, DefaultActivity.class);
			 startActivity(myIntent);
		}
    }


    private class LazyAdapter extends BaseAdapter{

        private Activity activity;
        private String[] data;
        private String[] textdata;
        private LayoutInflater inflater=null;
        public ImageLoader imageLoader; 

        public LazyAdapter(Activity a, String[] d,String[] t) {
            activity = a;
            data=d;
            textdata=t;
            inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            imageLoader=new ImageLoader(activity.getApplicationContext());
        }

        public int getCount() {
            return data.length;
        }

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

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

        public  class ViewHolder{
            public TextView text;
            public ImageView image;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View vi=convertView;
            final ViewHolder holder;
            if(convertView==null){
                vi = inflater.inflate(R.layout.item, null);
                holder=new ViewHolder();
                holder.text=(TextView)vi.findViewById(R.id.text);;
                holder.image=(ImageView)vi.findViewById(R.id.image);
                vi.setTag(holder);
            }
            else
                holder=(ViewHolder)vi.getTag();

            holder.text.setText(textdata[position]);
            holder.image.setTag(data[position]);
            imageLoader.DisplayImage(data[position], activity, holder.image);

            holder.text.setOnClickListener(new OnClickListener() {
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				System.out.println("List ID value ::::::::::::::::::"+holder.text.getText()+"list1::::::::::;");

    				if(holder.text.getText().equals("ListA")){

    					Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
    					myIntent.putExtra("catId", "1");
						startActivity(myIntent);

    				}

    			}
            	}); 



            return vi;
        }

    /*	public void onClick(View v) {
    		Intent myIntent = new Intent(v.getContext(), ButtonsActivity.class);
            startActivityForResult(myIntent, 0);

    	}*/
    }
}



listmain.xml file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

	<TextView
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="Dynamic ListView "
		style="?textTitle"/>

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:layout_weight="1"/>



</LinearLayout>



item.xml Layout file :
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">
  <ImageView
  	  android:id="@+id/image"
	  android:layout_width="50dip"
	  android:layout_height="50dip" android:src="@drawable/stub" android:scaleType="centerCrop"/>
  <TextView
  	  android:id="@+id/text"
  	  android:layout_width="fill_parent"
	  android:layout_height="wrap_content"
	  android:layout_weight="1" android:layout_gravity="left|center_vertical" android:textSize="20dip" android:layout_marginLeft="10dip" style="?listItem"/>
</LinearLayout>
Categories: Android
  1. September 23, 2011 at 9:35 am

    A screenshot of the finished product would be great 🙂

    Like

  2. peter
    November 16, 2011 at 1:50 am

    i copied your code into Eclipse and tried to get it to run. But it could not compile because
    things like Default.class were missing. Can you either provide the complete code as a zip file
    or post the complete code so that it works. if this is a library issue, then please provide
    which jar files one needs.

    The concepts you use are nice, but not much use if the user can’t get it to work.

    Like

    • November 18, 2011 at 6:13 pm

      Peter ,
      Dafault.class–> You can define this class based on your functionality .

      Just download jsoup-1.4.1.jar , to parse the XML response and dynamically populate the ListView elements .

      Like

  3. A
    January 27, 2012 at 8:52 pm

    Hey, can u mail the entire code and what are the steps to do this and how to run it.

    Like

  4. March 16, 2012 at 1:24 pm

    Hi, Everybody, Good Morn,
    am also having tat kind of problem,am a child in android,pls help me send the full code and how can implement tat,i think ur all my profess…pls guys help me….this is my mail id [velsans@gmail.com]

    Like

  5. NewB
    June 19, 2012 at 1:51 pm

    Very good tutorial indeed but i have one query…
    Can any1 tell me that how to implement onClick method on images ( not list iteam),,,I want to implement method when user click on particular image and I can implement further actions by knowing which listiteam’s image was clicked….
    Thx in advance…

    Like

  1. No trackbacks yet.

Leave a comment