Our social:

Latest Post

Wednesday 23 January 2013

Android Custom ListView with Image and Text

Lazylist in android,listView in android,image listView in nadroid

 First of all create a new project in eclipse
Step 1:
main_activity.xml

<?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="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="278dp"
        android:layout_weight="1.05" />

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Clear Cache" />

    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="list" />

</LinearLayout>


Step 2:

row.xml

 <?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"
    android:orientation="horizontal">
   

    <ImageView
        android:id="@+id/imge"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/ic_launcher" />


    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />


    <CheckedTextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/listPreferredItemHeightSmall"
        android:checkMark="?android:attr/listChoiceIndicatorMultiple"
        android:gravity="center_vertical"
        android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
        android:paddingRight="?android:attr/listPreferredItemPaddingRight"
        android:textAppearance="?android:attr/textAppearanceListItemSmall" />

</LinearLayout>


Step 3:
MyArrayAdapter.java

 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;

class MyArrayAdapter extends ArrayAdapter<String>{
    private static LayoutInflater inflater=null;
    List<String> list;
    Activity a;
    String[] abc,data,name,desc,price,url;
    String ResString,menu_name="",description="",menu_price="",image_url="",s="",selItem,pr="",nam="",sw;
    public ImageLoader imageLoader;
    private HashMap<Integer, Boolean> myChecked = new HashMap<Integer, Boolean>();
 public MyArrayAdapter(Context context, int resource,int textViewResourceId, List<String> objects,String string) {
  super(context, resource, textViewResourceId, objects);
  list=objects;
  ResString=string;
  abc=ResString.split("##");
 
  for(int o=0;o<abc.length;){
         menu_name=menu_name+abc[o]+"##";
       o=o+4;
    }
   name =menu_name.split("##");
   
    for(int p=1;p<abc.length;){
        description=description+abc[p]+"##";
        p=p+4;
     }
    desc=description.split("##");
    for(int p=2;p<abc.length;){
          menu_price=menu_price+abc[p]+"##";
          p=p+4;
       }
    price=menu_price.split("##");
   for(int p=3;p<abc.length;){
        image_url=image_url+abc[p]+"##";
        p=p+4;
     }
    url=image_url.split("##");
  a=(Activity) context;
  for(int i = 0; i < objects.size(); i++){
   myChecked.put(i, false);
  }
 }
   
 public void toggleChecked(int position){
  if(myChecked.get(position)){
   myChecked.put(position, false);
  }else{
   myChecked.put(position, true);
  }
 
  notifyDataSetChanged();
 }

 public List<Integer> getCheckedItemPositions(){
  List<Integer> checkedItemPositions = new ArrayList<Integer>();
 
  for(int i = 0; i < myChecked.size(); i++){
   if (myChecked.get(i)){
    (checkedItemPositions).add(i);
   }
  }
 
  return checkedItemPositions;
 }

 /*public List<String> getCheckedItems(){
  List<String> checkedItems = new ArrayList<String>();
 
  for(int i = 0; i < myChecked.size(); i++){
   if (myChecked.get(i)){
    (checkedItems).add(list.get(i));
   }
  }
 
  return checkedItems;
 }*/
 public String getChecked(){
   
     String soi="";
     for(int i = 0; i < myChecked.size(); i++){
           if (myChecked.get(i)){
            soi=soi+name[i]+"\n";
           }
          }
    return soi;
     
 }

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

 public String getItem(int position) {
     return abc[position];
 }

 public long getItemId(int position) {
     return position;
 }
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
 
  if(row==null){
 inflater = (LayoutInflater)a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 imageLoader=new ImageLoader(a.getApplicationContext());
   row=inflater.inflate(R.layout.row, null); 
  }
 
  CheckedTextView checkedTextView = (CheckedTextView)row.findViewById(R.id.text1);
  TextView textView = (TextView)row.findViewById(R.id.name);
  checkedTextView.setText(price[position]);
  textView.setText(name[position]);
  ImageView img=(ImageView)row.findViewById(R.id.imge);
  Boolean checked = myChecked.get(position);
  if (checked != null) {
   checkedTextView.setChecked(checked);
   imageLoader.DisplayImage(url[position], img);
           }
 
  return row;
 }

   }


Step 4:
 MainActivity.java

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
     ListView listView;
        LazyAdapter adapter;
        String[] abc;
        MyArrayAdapter myArrayAdapter;
        List<String> list1;
        String string;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            new GetListTask().execute("http://10.0.2.2/www/date1.php?command=show");
            //new GetListTask().execute( "http://10.0.2.2/www/getImageUrlsAndDescription.php");
            listView=(ListView)findViewById(R.id.list);
           
           
            Button b=(Button)findViewById(R.id.button1);
            Button b1=(Button)findViewById(R.id.button2);
           
          
           
            b1.setOnClickListener(new OnClickListener(){

                public void onClick(View v) {
                   
                   
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {

                        public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
                            Toast.makeText(MainActivity.this, "You have chosen : " + " " + listView.getItemAtPosition(arg2), Toast.LENGTH_LONG).show();
                           
                        }
                       
                    } );
                }
               
            });
            b.setOnClickListener(listener);
        }
       
        @Override
        public void onDestroy()
        {
            listView.setAdapter(null);
            super.onDestroy();
        }
        public void total(View v){
            String s="";
            s= myArrayAdapter.getChecked();
           
            Toast.makeText(this, s, Toast.LENGTH_LONG).show();
        }
        public OnClickListener listener=new OnClickListener(){
            public void onClick(View arg0) {
                adapter.imageLoader.clearCache();
                adapter.notifyDataSetChanged();
            }
        };
       
        private class GetListTask extends AsyncTask<String, Void, String>{

            /**
             * Let's make the http request and return the result as a String.
             */
            protected String doInBackground(String... args) { 
               
                    Http link=new Http();
                    return link.executeHttpRequest(args[0]);
                }

            /**
             * Parse the String result, and create a new array adapter for the list
             * view.
             */
            protected void onPostExecute(String objResult) {
                String[] av=objResult.split("##");
                 abc=objResult.split("##");
                 string=objResult;
                 //Toast.makeText(MainActivity.this,abc[5], Toast.LENGTH_LONG).show();
                 list1 = new ArrayList<String>(abc.length); 
                    for (String s : abc) { 
                        list1.add(s); 
                    } 
                    myArrayAdapter = new MyArrayAdapter(MainActivity.this,R.layout.row, android.R.id.text1,list1,string);
               
                  
                    //adapter=new LazyAdapter(MainActivity.this, abc);
                 listView.setAdapter(myArrayAdapter);
                 listView.setOnItemClickListener(new OnItemClickListener() {

                        public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3) {
                            Toast.makeText(MainActivity.this, "You have chosen : " + " " + listView.getItemAtPosition(position), Toast.LENGTH_LONG).show();
                            myArrayAdapter.toggleChecked(position);
                        }
                       
                    } );
                }
               
                    }
     
        } 

Step 5:

 ImageLoader.java


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.os.Handler;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {
   
    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;
    Handler handler=new Handler();//handler to display images in UI thread
   
    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }
   
    final int stub_id=R.drawable.ic_launcher;
    public void DisplayImage(String url, ImageView imageView)
    {
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }
       
    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }
   
    private Bitmap getBitmap(String url)
    {
        File f=fileCache.getFile(url);
       
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;
       
        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex){
           ex.printStackTrace();
           if(ex instanceof OutOfMemoryError)
               memoryCache.clear();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            FileInputStream stream1=new FileInputStream(f);
            BitmapFactory.decodeStream(stream1,null,o);
            stream1.close();
           
            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
           
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            FileInputStream stream2=new FileInputStream(f);
            Bitmap bitmap=BitmapFactory.decodeStream(stream2, null, o2);
            stream2.close();
            return bitmap;
        } catch (FileNotFoundException e) {
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
   
    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }
   
    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }
       
        public void run() {
            try{
                if(imageViewReused(photoToLoad))
                    return;
                Bitmap bmp=getBitmap(photoToLoad.url);
                memoryCache.put(photoToLoad.url, bmp);
                if(imageViewReused(photoToLoad))
                    return;
                BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
                handler.post(bd);
            }catch(Throwable th){
                th.printStackTrace();
            }
        }
    }
   
    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }
   
    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }



Step 6:

 Http.java


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class Http {
    String name;
    private String st;
    public String Hello(String s){
        return st="helllo"+s;
    }
    public String getName(){
        return st;
       
    }
    public void setName(String s){
        st=s;
    }
     public String executeHttpRequest(String data) {
            String result = "";
            try {
                    URL url = new URL(data);
                    URLConnection connection = url.openConnection();
                  
                    /*
                     * We need to make sure we specify that we want to provide input and
                     * get output from this connection. We also want to disable caching,
                     * so that we get the most up-to-date result. And, we need to
                     * specify the correct content type for our data.
                     */
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setUseCaches(false);
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                    // Send the POST data
                    DataOutputStream dataOut = new DataOutputStream(connection.getOutputStream());
                    dataOut.writeBytes(data);
                    dataOut.flush();
                    dataOut.close();

                    // get the response from the server and store it in result
                    DataInputStream dataIn = new DataInputStream(connection.getInputStream());
                    String inputLine;
                    while ((inputLine = dataIn.readLine()) != null) {
                            result += inputLine;
                    }
                    dataIn.close();
            } catch (IOException e) {
                    /*
                     * In case of an error, we're going to return a null String. This
                     * can be changed to a specific error message format if the client
                     * wants to do some error handling. For our simple app, we're just
                     * going to use the null to communicate a general error in
                     * retrieving the data.
                     */
                    e.printStackTrace();
                    result = null;
            }

            return result;
    }
   


Step 7:

 Utils.java

import java.io.InputStream;
import java.io.OutputStream;

public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }


 Step 8:

AndroidMenifeast.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lazy"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/hello" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
   
   
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>





Source Code DownLoad