This tutorial follows the old way of customizing the ListView using a third party library.
Consider reading the more efficient solution which uses Volley library to achieve the same. Android Custom ListView with Image and Text using Volley

This is a tutorial about customizing listview with an image and text. For this tutorial I am using some of the classes from this link. In this tutorial I explained how to load images from remote url and update into listview. Also explained how to design listview with your custom styles and colors instead of using default listview style.

Download Code

The Sample XML

For this tutorial I am using following sample XML which has some data and a thumbnail image url. You can get this XML by accessing https://api.androidhive.info/music/music.xml

<?xml version="1.0" encoding="UTF-8"?>
<music>
    <song>
        <id>1</id>
        <title>Someone Like You</title>
        <artist>Adele</artist>
        <duration>4:47</duration>
	    <plays>1662</plays>
	    <thumb_url>https://api.androidhive.info/music/images/adele.png</thumb_url>
    </song>
	<song>
        <id>2</id>
        <title>Space Bound</title>
        <artist>Eminem</artist>
        <duration>4:38</duration>
	    <plays>1900</plays>
	    <thumb_url>https://api.androidhive.info/music/images/eminem.png</thumb_url>
    </song>
       .
       .
       .
       .
</music>

Before going further make sure that you covered Android XML Parsing Tutorial and Android ListView Tutorial before

Creating New Project

1. Create new project in your Eclipse IDE and fill all the details. File ⇒ New Project
2. If you notice the screen shots I designed listview with gradient background. To define gradient style create three new XML files under drawable folder and name them as gradient_bg.xml, list_selector.xml and gradient_bg_hover.xml and fill with following code. Also the thumbnail image has white background, for this I used image_bg.xml
Right Click and drawable-hdpi ⇒ New ⇒ Android XML File

gradient_bg.xml – Default Background Gradient Style

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#f1f1f2"
      android:centerColor="#e7e7e8"
      android:endColor="#cfcfcf"
      android:angle="270" />
</shape>

gradient_bg_hover.xml – Gradient Style for on hover state

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#18d7e5"
      android:centerColor="#16cedb"
      android:endColor="#09adb9"
      android:angle="270" />
</shape>

list_selector.xml – Actual liststyle which combines the above two styles

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<item
	 android:state_selected="false"
		android:state_pressed="false"
		android:drawable="@drawable/gradient_bg" />

	<item android:state_pressed="true"
		android:drawable="@drawable/gradient_bg_hover" />

	<item android:state_selected="true"
	 android:state_pressed="false"
		android:drawable="@drawable/gradient_bg_hover" />
</selector>

image_bg.xml – is for white border around the image in listview

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
      <shape
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#dbdbdc" />
            <solid android:color="#FFFFFF" />
        </shape>
   </item>
</layer-list>

3. Now open your main.xml file and define a listview in it.

<?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="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />

</LinearLayout>

4. Next step is to design single listrow. Create a new XML file under layout folder and name it as list_row.xml.
Right Click ⇒ New ⇒ Android XML File

In this tutorial I custom designed a listview which contains an image on leftside, time and arrow at the right end and a title in middle. I used RelativeLayout as parent node and placed all the remaining items using relative positioning properties. Check the following image

android custom listview

list_row.xml – Single ListRow Layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_selector"
    android:orientation="horizontal"
    android:padding="5dip" >

	<!--  ListRow Left sied Thumbnail image -->
	<LinearLayout android:id="@+id/thumbnail"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:padding="3dip"
        android:layout_alignParentLeft="true"
        android:background="@drawable/image_bg"
	    android:layout_marginRight="5dip">

		<ImageView
			android:id="@+id/list_image"
	        android:layout_width="50dip"
	        android:layout_height="50dip"
	        android:src="@drawable/rihanna"/>

	</LinearLayout>

	<!-- Title Of Song-->
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Rihanna Love the way lie"
        android:textColor="#040404"
        android:typeface="sans"
        android:textSize="15dip"
        android:textStyle="bold"/>

	<!-- Artist Name -->
    <TextView
        android:id="@+id/artist"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:textColor="#343434"
        android:textSize="10dip"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Just gona stand there and ..." />

	<!-- Rightend Duration -->
    <TextView
        android:id="@+id/duration"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/title"
        android:gravity="right"
        android:text="5:45"
        android:layout_marginRight="5dip"
        android:textSize="10dip"
        android:textColor="#10bcc9"
        android:textStyle="bold"/>

     <!-- Rightend Arrow -->
     <ImageView android:layout_width="wrap_content"
     	android:layout_height="wrap_content"
     	android:src="@drawable/arrow"
     	android:layout_alignParentRight="true"
     	android:layout_centerVertical="true"/>

</RelativeLayout>

The above XML will provide you output like below

android listview selected state

5. Until now we completed designing part of the listview. Next step is to parse the xml and update the data into listview. Create a new java class file in your src folder. Right Click on src ⇒ New ⇒ Class and name it as LazyAdapter.java

package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class LazyAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList&lt;HashMap&lt;String, String&gt;&gt; data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader; 

    public LazyAdapter(Activity a, ArrayList&lt;HashMap&lt;String, String&gt;&gt; d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

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

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

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

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.list_row, null);

        TextView title = (TextView)vi.findViewById(R.id.title); // title
        TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
        TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
        ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

        HashMap&lt;String, String&gt; song = new HashMap&lt;String, String&gt;();
        song = data.get(position);

        // Setting all values in listview
        title.setText(song.get(CustomizedListView.KEY_TITLE));
        artist.setText(song.get(CustomizedListView.KEY_ARTIST));
        duration.setText(song.get(CustomizedListView.KEY_DURATION));
        imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
        return vi;
    }
}

6. Now open your MainActivity class and type the following code. In the following code I am getting xml from url and parsing it. While parsing I am storing all the xml data into HashMap and finally I am passing HashMap to LazyAdapter class.

package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;

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

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class CustomizedListView extends Activity {
	// All static variables
	static final String URL = "https://api.androidhive.info/music/music.xml";
	// XML node keys
	static final String KEY_SONG = "song"; // parent node
	static final String KEY_ID = "id";
	static final String KEY_TITLE = "title";
	static final String KEY_ARTIST = "artist";
	static final String KEY_DURATION = "duration";
	static final String KEY_THUMB_URL = "thumb_url";

	ListView list;
    LazyAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ArrayList&lt;HashMap&lt;String, String&gt;&gt; songsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();

		XMLParser parser = new XMLParser();
		String xml = parser.getXmlFromUrl(URL); // getting XML from URL
		Document doc = parser.getDomElement(xml); // getting DOM element

		NodeList nl = doc.getElementsByTagName(KEY_SONG);
		// looping through all song nodes &lt;song&gt;
		for (int I = 0; I &lt; nl.getLength(); i++) {
			// creating new HashMap
			HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
			Element e = (Element) nl.item(i);
			// adding each child node to HashMap key =&gt; value
			map.put(KEY_ID, parser.getValue(e, KEY_ID));
			map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
			map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
			map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
			map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

			// adding HashList to ArrayList
			songsList.add(map);
		}

		list=(ListView)findViewById(R.id.list);

		// Getting adapter by passing xml data ArrayList
        adapter=new LazyAdapter(this, songsList);
        list.setAdapter(adapter);

        // Click event for single list row
        list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView&lt;?&gt; parent, View view,
					int position, long id) {

			}
		});
	}
}

Add Permissions in AndroidManifest.xml

Open your AndroidManifest.xml file add two permissons INTERNET and WRITE_EXTERNAL_STORAGE.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.example.androidhive" android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="8" />

	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<activity android:name=".CustomizedListView" android:label="@string/app_name">
			<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.INTERNET" />
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

Also you need 5 more classes in order to run this project. I am giving the code for each class at the end of the article. After adding all the classes if you run the project it will show output like below
ListView Default State

android customized listview

ListView on Select State

android customized listview hover

Other Classes you needed to run this project

You also need to include following class which deals functionalities like fetching images from WEB, storing them in cache and clearing cache etc., Make sure that you included following files in your project.

XMLParser.java

package com.example.androidhive;

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

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.ClientProtocolException;
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.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {

	// constructor
	public XMLParser() {

	}

	/**
	 * Getting XML from URL making HTTP request
	 * @param url string
	 * */
	public String getXmlFromUrl(String url) {
		String xml = null;

		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

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

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// return XML
		return xml;
	}

	/**
	 * Getting XML DOM element
	 * @param XML string
	 * */
	public Document getDomElement(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) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (SAXException e) {
				Log.e("Error: ", e.getMessage());
	            return null;
			} catch (IOException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			}

	        return doc;
	}

	/** Getting node value
	  * @param elem element
	  */
	 public final String getElementValue( Node elem ) {
	     Node child;
	     if( elem != null){
	         if (elem.hasChildNodes()){
	             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
	                 if( child.getNodeType() == Node.TEXT_NODE  ){
	                     return child.getNodeValue();
	                 }
	             }
	         }
	     }
	     return "";
	 }

	 /**
	  * Getting node value
	  * @param Element node
	  * @param key string
	  * */
	 public String getValue(Element item, String str) {
			NodeList n = item.getElementsByTagName(str);
			return this.getElementValue(n.item(0));
		}
}

ImageLoader.java

package com.example.androidhive;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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.app.Activity;
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&lt;ImageView, String&gt; imageViews=Collections.synchronizedMap(new WeakHashMap&lt;ImageView, String&gt;());
    ExecutorService executorService; 

    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }

    final int stub_id = R.drawable.no_image;
    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 (Exception ex){
           ex.printStackTrace();
           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;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //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&lt;REQUIRED_SIZE || height_tmp/2&lt;REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        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;
        }

        @Override
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }

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

}

MemoryCache.java

package com.example.androidhive;

import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import android.graphics.Bitmap;

public class MemoryCache {
    private Map&lt;String, SoftReference&lt;Bitmap&gt;&gt; cache=Collections.synchronizedMap(new HashMap&lt;String, SoftReference&lt;Bitmap&gt;&gt;());

    public Bitmap get(String id){
        if(!cache.containsKey(id))
            return null;
        SoftReference&lt;Bitmap&gt; ref=cache.get(id);
        return ref.get();
    }

    public void put(String id, Bitmap bitmap){
        cache.put(id, new SoftReference&lt;Bitmap&gt;(bitmap));
    }

    public void clear() {
        cache.clear();
    }
}

Utils.java

package com.example.androidhive;

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){}
    }
}

FileCache.java

package com.example.androidhive;

import java.io.File;
import android.content.Context;

public class FileCache {

    private File cacheDir;

    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }

    public File getFile(String url){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        //Another possible solution (thanks to grantland)
        //String filename = URLEncoder.encode(url);
        File f = new File(cacheDir, filename);
        return f;

    }

    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }

}
This image for thumbnail purpose
android custom listview
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Mark

    HI!
    i want to display orginal image as downloaded from url, which line i need to change ?

  • Puneet

    getting error in xml parser

    04-22 15:43:31.903: E/Error:(739): expected: /meta read: head (position:END_TAG @15:10 in java.io.StringReader@40e2a9d8)

  • Ivan Sanchez

    Hi, thank you very much for your fantastic code. A have a question, how i can load an image from sdcard or internal device? I’m trying it but i don’t find the correct answer. Sorry for my english and for my question, i’m beginner at android. Thank you very much again, bye bye

  • nithu

    Sir while implementing the given code unfortunately my UI stopped.Logcat showing error in HttpResponse in XMLParser and String XML in Main Activity.How can I rectify that sir.Please reply me.

  • Firdi

    Thanks Ravi! It’s amazing that you have shared this brilliant piece of code here. Just typing this in, getting it to run and trying to understand the concepts you used have taught me more in one day than I would understand in weeks. Thanks again for the good work.

  • Firdi

    It would have been a much more honest tutorial if Ravi would have provided a link to the MIT licensed LazyList library that he has used for his lazy image loading caching concepts.

  • Can’t download the file. Any problems maybe?

  • Valerio

    I downloaded this tutorial but this is logcat with error:
    Please help me, i need this tutorial ^^

    05-04 19:58:16.561: E/Trace(1311): error opening trace file: No such file or directory (2)

    05-04 19:58:17.511: E/Error:(1311): expected: /hr read: body (position:END_TAG @6:8 in java.io.StringReader@4121e2b8)

    05-04 19:58:17.511: D/AndroidRuntime(1311): Shutting down VM

    05-04 19:58:17.521: W/dalvikvm(1311): threadid=1: thread exiting with uncaught exception (group=0x40a13300)

    05-04 19:58:17.531: E/AndroidRuntime(1311): FATAL EXCEPTION: main

    05-04 19:58:17.531: E/AndroidRuntime(1311): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidhive/com.example.androidhive.CustomizedListView}: java.lang.NullPointerException

    05-04 19:58:17.531: E/AndroidRuntime(1311): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at android.app.ActivityThread.access$600(ActivityThread.java:130)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at android.os.Handler.dispatchMessage(Handler.java:99)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at android.os.Looper.loop(Looper.java:137)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at android.app.ActivityThread.main(ActivityThread.java:4745)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at java.lang.reflect.Method.invokeNative(Native Method)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at java.lang.reflect.Method.invoke(Method.java:511)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at dalvik.system.NativeStart.main(Native Method)

    05-04 19:58:17.531: E/AndroidRuntime(1311): Caused by: java.lang.NullPointerException

    05-04 19:58:17.531: E/AndroidRuntime(1311): at com.example.androidhive.CustomizedListView.onCreate(CustomizedListView.java:43)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at android.app.Activity.performCreate(Activity.java:5008)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)

    05-04 19:58:17.531: E/AndroidRuntime(1311): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)

    05-04 19:58:17.531: E/AndroidRuntime(1311): … 11 more

    • Ravalesh

      I got the Same error. Used HttpGet httpPost=new HttpGet(url); instead of HttpPost httpPost = new HttpPost(url);inside getXmlFromUrl procedure. Worked fine.

      • huuhuybn

        because get data from url xml error.you shounld get data xml from other :).i try and run app ok 🙂

      • maryllien

        i’ve tried what you’ve said… but it’s still giving me nullpointerexception…..

      • ltd

        YEAH, thanks

    • Huynh

      String xml = parser.getXmlFromUrl(URL); —> this error,return null :D,

      you have to get data from other

      • maryllien

        from other what??? other xml????
        i’m sorry… i’m new to this… i haven’t used xml parsing before…

        • huuhuybn

          create new xml and parsing xml yourself 🙂

  • Robbie

    Is it at all possible to add Async tasking to this so that it works in 4.0+?

    Thanks

  • borg

    hello…i download this code and fix her properties but it does not work…it display (force close)…

    • caesardo

      change the HttpPost to HttpGet in getXmlFromUrl method in XmlParser class.. works like charm

      • Satish Kumar

        still am getting same problem

      • Fahad Khan

        Perfect!

        • Ibrahem Al-Betar

          Yes the problem is solved 🙂

    • Karen

      You have to download the xml file and put it in your own server, and then change the HttpPost to HttpGet.

      • Ragumanikandan

        its working without downloading the xml.. Thanks..

  • Emrullah Lüleci

    this code has some problem at Activity a=(Activity)photoToLoad.imageView.getContext();in PhotosLoader class. Somehow it cannot take the activity of the imageView and doesn’t run the BitmapDisplayer on Ui thread. So I took the activity as parameter and called the runOnUiThread directly from activity and it worked. I couldn’t understand the reason but solution is this.

    • Mazen Kasser

      Can you please show in code what did you do? I am a beginner to Android and its been two days… the sample code never worked, I am using Mac, so I have no idea how all these people got it working!

  • Jason

    Someone is selling this FREE excellent tutorial on chupamobile for $19. Here’s the link. http://www.chupamobile.com/products/details/795/Custom+ListView+with+Images+and+Text/

    • Mazen Kasser

      I am ready to buy it if it works!

  • Mazen Kasser

    Well it looks great tutorial. I have downloaded the source code tried to launch the project and didn’t work, with showing “Unfortunately, CustomizedListView has stopped…” so people can you please, for God Sake, stop asking repeated questions and let us just to get the solution for this issue!!!

  • Mazen Kasser

    Can you please tell me why the sample code is not working!

  • Sid

    It’s not running throwing null pointer exception

  • Sameer

    This Amazing tutorial about ListView with Image And Text. I love androidHive

  • Rahul

    hi

    i am rahul i have downloaded whole code and when i executed this project then i getting an error in CustomizedListView class at line 43 (NodeList nl = doc.getElementsByTagName(KEY_SONG);) error message is Caused by: java.lang.NullPointerException

    so provide solution why i am getting error…………

    • MarCo

      yeah… me too… the logcat always give me a null pointer exception… how can i make it run??? please help… i really need help….

      • sanjay

        This xml parsing Error please change the URL and (KEY_SONG);) Nod and chield nod change………..

  • alen

    Very useful codes,But when I tried with other “URL” and key values it doesn’t work ,it gets stuck in a loading page when i try to run the app.So can you please give me some suggestions regarding what all changes I need to do get the app executing properly with the new Url.

    Thanks in Advance

  • rajesh

    nice tutorial………..

  • Vbk

    nice tutorial thanx

  • Krishna Veni

    Hi Amit Suro & & Dsireesha0309 ., i have passing image from one activity to another activity using following code.its working well…

    ImageLoader imageLoader = new ImageLoader(getApplicationContext());

    final ImageView ima = (ImageView) findViewById(R.id.icon);
    imageLoader.DisplayImage(_Image, ima);

  • Vikas B L

    I tried onclick listener. But it is not working. I don’t what the problem in it. Even my eclipse not generating R.java. Please suggest any solution.

  • priyanga Ranasinghe

    This is Nice Tutorial.

    So, How can add Search view to this list. I try to used Text Watcher but it not success. here my code I used in Main Activity.

    adapter = new CustomListViewAdapter(this,R.layout.list_row, rowItems);
    listView.setAdapter(adapter);
    listView.setTextFilterEnabled(true);

    editText.addTextChangedListener(new TextWatcher() {

    public void onTextChanged(CharSequence arg0, int arg1, int arg2,
    int arg3) {

    }

    public void beforeTextChanged(CharSequence arg0, int arg1,
    int arg2, int arg3) {

    }

    public void afterTextChanged(Editable arg0) {
    ActivityName.this.adapter.getFilter().filter(arg0);

    }
    });

    Help me

    Thank you.

  • mario

    pretty good tutorial !
    Thanks for that …

  • Ahmed Sabry

    Thanks Man!!

  • Writwick Daz

    Why are you specifying “hdpi”? AFAIK, This is not resolution specific.

  • MarCo

    hi… im marco… i downloaded the code… but it didn’t work… then i try to simulate step by step of your tutorial, and i did also copy the codes posted here… but it still didn’t work… the logcat always give me a NullPointerException… what should i do to make it run??? please help….

  • muriel

    hi ravi…. i have downloaded your code but when i run it,,, it gives me null pointer exception… why was that??? please need answer….

  • Mesud emre

    Can we use loading image jar to load the images?

  • MacBloke

    Great tutorial.

    One question, though. I want to use a list view to view an XML feed in a fragment and all I can get is a blank list view. My code is below – where am I going wrong?

    package com.macbloke.fragmentlistview;

    import android.net.Uri;

    import android.os.AsyncTask;

    import android.os.Bundle;

    import android.support.v4.app.Fragment;

    import android.view.LayoutInflater;

    import android.view.View;

    import android.view.ViewGroup;

    import org.apache.http.HttpResponse;

    import org.apache.http.client.ClientProtocolException;

    import org.apache.http.client.methods.HttpGet;

    import org.apache.http.impl.client.DefaultHttpClient;

    import org.w3c.dom.Document;

    import org.w3c.dom.Element;

    import org.w3c.dom.NodeList;

    import org.xmlpull.v1.XmlPullParser;

    import org.xmlpull.v1.XmlPullParserException;

    import org.xmlpull.v1.XmlPullParserFactory;

    import java.io.IOException;

    import java.io.InputStream;

    import java.net.MalformedURLException;

    import java.net.URI;

    import java.net.URISyntaxException;

    import java.net.URL;

    import java.util.ArrayList;

    import java.util.List;

    import java.net.*;

    import java.io.*;

    import java.util.*;

    import android.app.ListActivity;

    import android.content.Context;

    import android.content.Intent;

    import android.os.Bundle;

    import android.view.LayoutInflater;

    import android.view.Menu;

    import android.view.MenuInflater;

    import android.view.MenuItem;

    import android.view.View;

    import android.view.ViewGroup;

    import android.widget.ArrayAdapter;

    import android.widget.ListAdapter;

    import android.widget.ImageButton;

    import android.widget.ListView;

    import android.widget.SimpleAdapter;

    import android.app.ListFragment;

    public class Fragment3 extends Fragment {

    // All static variables

    static final String URL = “http://www.someurl.com/rss/news”;

    // XML node keys

    static final String KEY_ITEM = “item”; // parent node

    static final String KEY_TITLE = “title”;

    static final String KEY_DATE = “pubDate”;

    static final String KEY_LINK = “link”;

    static final String KEY_DESC = “description”;

    ListView rssListView;

    LazyAdapter rssAdapter;

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View root = inflater.inflate(R.layout.fragment3, container, false);

    // Download the data

    ArrayList<HashMap> rssArticleList = new ArrayList<HashMap>();

    XMLParser parser = new XMLParser();

    String xml = parser.getXmlFromUrl(URL); // getting XML from URL

    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName(KEY_TITLE);

    // looping through all article nodes

    for (int i = 0; i < nl.getLength(); i++) {

    // creating new HashMap

    HashMap map = new HashMap();

    Element e = (Element) nl.item(i);

    // adding each child node to HashMap key => value

    map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));

    map.put(KEY_DATE, parser.getValue(e, KEY_DATE));

    map.put(KEY_LINK, parser.getValue(e, KEY_LINK));

    map.put(KEY_DESC, parser.getValue(e, KEY_DESC));

    // adding HashList to ArrayList

    rssArticleList.add(map);

    }

    rssListView=(ListView)root.findViewById(R.id.list);

    // Getting adapter by passing xml data ArrayList

    rssAdapter=new LazyAdapter(getActivity(), rssArticleList);

    rssListView.setAdapter(rssAdapter);

    return root;

    }

    }

    • MacBloke

      D’Oh!

      Replaced:

      NodeList nl = doc.getElementsByTagName(KEY_TITLE);

      with:

      NodeList nl = doc.getElementsByTagName(KEY_ITEM);

      All is now well.

  • ujjwal

    indeed a good tutorial…as i am a beginner in android..and i am running the tutorial its not working..so wud u please tell me how can i get it working…ASAP..

  • Osama Mursleen

    Good Tutorial….

  • Edward Lee

    Hi Adroid, use notifyDataSetInvalidated() may resolve you problem.

  • Darpan

    This is one great post. Very elaborated tutorial. Good work !

  • Edward Lee

    Dear, friend. I have pass this tutorial code to my GitHub ( https://github.com/EdwardLee03/android_tutorial/tree/master/ListView ), that is run OK. Good luck!

    IDE: Android Studio
    Android Version: 4.0.3

    The following is difference point:
    MusicActivity.java

    protected void onCreate(Bundle savedInstanceState) {
    if (DEVELOPER_MODE) {
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    .build());
    }

    super.onCreate(savedInstanceState);

    AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
    Map song = (Map) adapter.getItem(position);
    ImageView thumbImage = (ImageView) view.findViewById(R.id.thumb_image);
    ImageLoader imageLoader = adapter.getImageLoader();
    imageLoader.displayImage(song.get(Song.THUMB_URL), thumbImage);
    adapter.notifyDataSetInvalidated();
    }
    }
    };

    LazyAdapter.java

    public View getView(int position, View view, ViewGroup viewGroup) {

    this.notifyDataSetChanged(); // Important!

    return view;
    }

    ImageLoader.java

    private Bitmap getBitmap(String imageUrl) {

    // from Web
    try {
    URL url = new URL(imageUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(3000);
    conn.setReadTimeout(10000);
    conn.setInstanceFollowRedirects(true);
    conn.setRequestMethod(“GET”);
    conn.setDoInput(true);
    conn.connect();

    InputStream in = conn.getInputStream();
    OutputStream out = new FileOutputStream(file);
    IOUtils.copy(in, out);
    in.close();
    out.close();
    conn.disconnect();

    bitmap = decodeFile(file);

    }

  • MrH

    Hi mate,

    Thank you for this post. I am getting this error:

    org.apache.harmony.xml.dom.ElementImpl cannot be cast to android.renderscript.Element

    Any suggestion?

    • MrH

      Dont worry. I fixed it. It was me mistake. Your code it perfect.

  • I found you articles form here as well http://www.9android.net/custom-listview-image-text/. its horrible copying some ones articles and publish.

  • Giasafox

    And what about if I want NOT to read the uploaded xml file, but to have a static xml file in the resources of my app and read the information from that??????
    How can I implement this?????

  • howien

    Hi ravi,
    i realized that, it cant functioned without internet connection. may i know how to make it functioned without internet connection? means that the images and the data will store in device maybe cache when first time access to the internet?

    Thanks!

  • love

    I was able to run this project. But when im trying to use my own xml file and my own url it seems like there’s a problem because it kept on stopping when i try to run it 🙁

  • mahmoud elsafy

    exceptions in the logcat here :
    1- HttpResponse httpResponse = httpClient.execute(httpPost);
    2- String xml = parser.getXmlFromUrl(URL);

    when i try to run the application unfortunately has stopped , please help me as i am new in android

  • Thorsten

    Some remarks and best practices:

    Don’t use right-pointing carets on line items: http://developer.android.com/design/patterns/pure-android.html

    Don’t use SoftReference starting from Android 2.3 (better: use the LruCache from the Support Library): http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

    Don’t use DOM (better: use the XmlPullParser as recommended by Google): http://developer.android.com/training/basics/network-ops/xml.html

    Even better than XML: use JSON to reduce bandwidth consumtion/battery drainage and Google’s Volley networking library (as presented at the Google IO 2013): http://www.youtube.com/watch?v=yhv8l9F44qo and https://android.googlesource.com/platform/frameworks/volley/+/master

    Don’t use Apache’s DefaultHttpClient starting from Android 2.3: http://android-developers.blogspot.de/2011/09/androids-http-clients.html

    And finally: free resources and/or close streams always in a try-finally-construct.

  • Henrique Dn Maina

    Nice post. I like it and am using it.

    However i have a question.

    Instead of having an xml file, i want to use JSON data generated by a php with data as sampled below

    success: 1,size: 3,
    details: [
    {
    id : 1,
    title : “Someone Like You”,
    artise : “Adele”,
    duration : “4:47”
    thumb_url : “http://api.androidhive.info/music/images/adele.png”
    },
    {
    id : 2,
    title : “Someone Like You 2”,
    artise : “Adele”,
    duration : “4:47”
    thumb_url : “http://api.androidhive.info/music/images/adele.png”
    },
    {
    id : 3,
    title : “Someone Like You 3”,
    artise : “Adele”,
    duration : “4:47”
    thumb_url : “http://api.androidhive.info/music/images/adele.png”
    }

    ]

    • Thorsten

      And what is the question? How to generate JSON on server side? How to parse JSON on Android? Btw. the JSON example above isn’t valid: success and size are part of an JSONObject, so the whole fragment should be enclosed in curly braces.

    • Trollzito
  • Zeus

    Can u pls tell me how i can implement the above project using tab navigation and onclick to display the individual item the tab should still be visible, i tried to do it but onclick creates a new activity and the tab goes missing.
    thnx

  • Abhishek Mirajkar

    (Unfortunately, app has stopped)…
    I changed HttpPost to HttpGet in XMLParser class but it showing me above error in AVD.
    plz help….

  • Groxor

    Thanks! 😀 this source worked!

  • James Green

    Thank you Ravi for the detailed description on Android Listview , there’s one more video I found on youtube link: https://www.youtube.com/watch?v=0zQCv0Xb3pk
    other users should find this useful, it helped me alot

  • ihsanul

    hi ravi
    if i get image manual from folder drawable-hdpi
    i dont use URL = “http://api.androidhive.info/music/music.xml”
    how i can do it?
    help me

  • Nirmal

    so u can use image button instead of image

  • Martin

    Hello. I would like to know if it is possible to have 400 elements in the xml file but only load 20 at a time in my application. Everytime my user reaches the bottom of the screen by scrolling, then the next 20 elements will be loaded and displayed. If this is possible, could You please supply the code needed. Thanks

  • Asad Mirza

    Hi, I am using Listview with AutoSrcoll for bundle of items… i got a problem, ‘THE ITEMS WHICH ARE SHOWN ON SCREEN, THOSE ARE JUST VISIBLE… IN AUTOSCROLL WHEN NEW ITEMS COMES ON THE SCREEN, WITHOUT TOUCHING THERE IS NOTHING & AFTER TOUCH ON SCREEN THE BLANK SCREEN COME TO FILL WITH BOTTOM ITEMS’
    Suppose there are 10 items, 5 are on screen, five are at bottom, on autosroll the bottom`s five comes invisible before touching….
    I NEED A COMPLETE SLIDE SHOW IN LISTVIEW WHICH MUST SHOW ALL ITEMS VISIBLE TILL END WITHOUT TOUCHING!!!
    PLEASE HELP ME OUT… I AM STRUCK HERE FOR LAST 3 DAYS….

  • Muhammad Rafiq Asim

    it is not working ….it stooped on launching…help please

    • abdullah

      what is you specific error in Log.cat or console ?

  • Muhammad Rafiq Asim

    it shows message “Has stopped unfortunatally”

    • abdullah

      Ok I understand but you can be more specific, first of all check your manifest file

  • abdullah

    I have an NullPointerException in NodeList nl = doc.getElementsByTagName(KEY_SONG);

  • leroux

    I Just follow this tutorial but when I running my emulator I got message ‘Unfortunately app.apk has stopped’ why? I check in my project not found error

  • mangesh kaduskar

    How to set click listener to individual component in listview.
    I want to call next activity on author text click to show details about that specific cell.

  • Jian Liew

    I’m just wondering, when do you ever clear the cache? yes there is a function called clearcache() in imageloader, but you technically never call it.

  • Jian Liew

    When should I clear the cache if I update the image in the url

  • Niluka Subasinghe

    Hi,
    i want to add a radio button to above customize listview for each row. then the user can select one radio button at a time. this should work for scroll able list (list item count might be 50). once the user select a radio button and click the button in the bottom, that selected item id, name (using viewholder or any other option) should be taken.
    Please help me on this. i need a working source code

  • Sumair

    hi there,
    can u refer me to a tutorial, which can explain how to search values from database,
    in simple words, an application that reminds any pre-set activity, and we can also manually search for any event in that application.

  • Stephen Sugrue

    how do i get the data out for the intent in

    list.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView parent, View view,

    int position, long id) {

    String name = ((TextView) view.findViewById(R.id.name)).getText().toString();

    String role = ((TextView) view.findViewById(R.id.role)).getText().toString();

    String location = ((TextView) view.findViewById(R.id.location)).getText().toString();

    String email = ((TextView) view.findViewById(R.id.email)).getText().toString();

    String phone = ((TextView) view.findViewById(R.id.phone)).getText().toString();

    // Starting new intent

    Intent in = new Intent(getApplicationContext(), SelectedStaffMember.class);

    in.putExtra(KEY_NAME, name);

    in.putExtra(KEY_ROLE, role);

    in.putExtra(KEY_LOCATION, location);

    in.putExtra(KEY_PHONE, phone);

    in.putExtra(KEY_EMAIL, email);

    startActivity(in);

    }

    });

    something like that but it wont work

  • akhil nair

    Hey i want to know how to switch class while using XMLparser or listView for example in above program
    we got KEY_TITLE now when i select an item from list it should switch to KEY_TITLE.java class

  • rijotech

    Nice tutorial, I’m a noob and i was wondering how can i play a video on click?

    for example i have added to my CustomizedListView.java

    map.put(KEY_VIDEO_URL, parser.getValue(e, KEY_VIDEO_URL));

    and to my xml
    http://somewebsite.demovideo.mp4

    i was wondering if the get and play video function can bet implemented on the listener

    // Click event for single list row
    list.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView parent, View view,
    int position, long id) {

    if it can be done in conjunction with that how can it be done?

  • Fahad Khan

    Excellent

  • Whitepaper

    Hi,

    Very Nice Tutorial .Code works like a champ and its very good one.But how can i load images from the Local XML files which have something like this :-

    R.id.adele.png

    Any hint or any clue on this

  • KP Ranjith

    is tat all u given in tis tutorial r ur own examples frd??

  • Sameer

    Being a Blogger, your way of explanation satisfy me pretty much.

  • Guest

    can Anyone teach me how to add a On Loading effect before the item load finish in you this tutorial?
    i have try to implement asyntask but failed~

  • akhil nair

    hey guys i got a problem when i installed my CLV in mobile it shows default icons…..what should i do….

  • Ankur Agrawal

    Unable to do this in Asynctask.

    Please give the process.

    Please please please

  • andriangungon

    Sir i followed your tutorials and its really working very well, I only have one question on how to add load more function to it. Please consider me. Thanks.

  • Ajay Bhimani

    I have used same xml files which you used but still i am not getting bluelight. i am not able to understand what is problem. can you please help ? thanks 🙂

  • Can

    Hello, code works like a charm but I have a problem. Although bitmaps are retrived from sd cards so fast, I cannot see the images on screen. It takes ages to load all of them. What would be the reason? (All bitmaps are cached but they are displayed veeeery slowly)

  • Samie

    Nice one… Thanks
    Please how can I display this listview in a fragment instead of an activity?

    • Without knowing any details of what you are asking, you can probably use the same thing in a fragment with a listview, or just by using a listfragment.

      • allk

        no it is not, this syntax returns an eror in findViewById and (this, songsList);

        list=(ListView)findViewById(R.id.list);

        // Getting adapter by passing xml data ArrayList

        adapter=new LazyAdapter(this, songsList);

        list.setAdapter(adapter);

        // Click event for single list row

        list.setOnItemClickListener(new OnItemClickListener() {

        • allk

          getView().findViewById(R.id.list); to replace list=(ListView)findViewById(R.id.list);

          • mofagh

            and what to do with “this” error??

  • Guest

    What I should do to decrease de height of all columns?

  • JohnB

    What I should do to decrease de height of all rows?

  • Akshay Taru

    Hi Ravi,
    Thanks nice code. I want to add filter to this ListView, I have same structure ArrayList of HashMap.
    Can you suggest me how to perform filtering?

  • Deepak Kanyan

    its very long procedure……………………

  • Deepak Kanyan

    how to do this by getview()

  • Rupesh

    Sir i followed your tutorials and its really working very well, I only
    have one question on how to add load more function on Scroll moving. Please
    consider me. Thanks.

  • Emre Koç

    when you will be post it ? we are waiting for one year . search function adding this tutorial?. you said i am posting? where is it?

  • aref

    hi
    thanks for your article

    but :

    i use Arabic char in xml file and when load in my phone device it was non-readable…

    i ask you how can i insert Arabic or Farsi char in XML file an show correct them …
    please tel me to my email

  • Kratos

    It seems no code without AsyncTask is gonna work on my phone….pisses me off…nw i hv to restructure so many things…Damn u NetworkOnMainThreadException

  • Iliiazbek Akhmedov

    This is just a great article! Awesome!

  • lio

    it is very usefull and simple.
    Thank you very much, that helps me a lot.

  • Robert Musau

    Excellent piece of code and well laid out. However, after creating my own xml file on my server and trying it out, I received the following error:

    12-25 18:13:25.688: E/Error:(6019): PI must not start with xml (position:unknown xm@1:7 in java.io.StringReader@4056be68)

    I have seen several questions below asking how to solve it. Well, you add the following code to remove the header after the xml file is retrieved:

    xml=xml.replace("<?xml version="1.0" encoding="utf-8"?>", "");

    This is added immediately under the following piece of code in the XMLParser.java

    xml = EntityUtils.toString(httpEntity);

    Make sure the way you spell the words “xml version” and “UTF-8” is exactly the same way as it is in the xml file because the replace function is case sensitive.

    • Vasudev Vyas

      where i wrote this statement?

  • Guest

    ” xml=xml.replace(“”, “”); “

  • Guest

    🙂

  • Robert Musau

    xml=xml.replace("<?xml version="1.0" encoding="utf-8"?>", "");

    • Vasudev Vyas

      where???

  • mohhamad

    this listview dont support arabic font
    what can i do ??

  • Androider

    Hi! Very nice tutorial! I am novice with Android, anybody knows how can I get the song´s id when I click in the list item? Thank you!

    • Androider

      Sorry, I reply my own question and the solution:

      Toast.makeText(CustomizedListView.this, “You Clicked at “+songsList.get(+position).get(“id”), Toast.LENGTH_SHORT).show();

  • Toshi

    Great Tutorial! With this tutorial how can i make my data available offline?

  • Ivan Molina

    why isn’t this code working on android 4.+ ?(I’ve teste it and its just working on 2.1-2.3).

    • TheDude

      If you changed the minSdkVersion to one higher than Honeycomb you will get a NetworkOnMainThreadException

      • Ivan Molina

        @TheDude, not even,,heheeh, I’ve changed the minSdkVersion to a one higher then 11(i went till 14),ad it didn’t work !,so your “solution didn’t work !,the solution is use ASYNCTASK !

    • Abid

      yes this code won’t work on latest mobile phones as android now not allow network connection on main thread, you have to use either AsyncTask or create sub thread to do so. Sub Threading is pain in the ass because when you create one you have to use runonmainui to make change on the main thread as when your sub thread completes task. you better use AsyncTask to do so.

  • Saydur Rahman

    Great works Sir!But i have a simple demand! “When a row is selected some information will display” How can i do it? Sir please consider me……………..

  • Raman

    private Map<String, SoftReference<Bitmap>> cache=Collections.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());

    Please explain

  • Raman

    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());

  • Raman

    public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d)

  • Raman

    private ArrayList<HashMap<String, String>> data;

  • Raman

    HashMap<String, String> song = new HashMap<String, String>();

  • kumar

    &gt

  • Mr H

    Hi guys,
    I implemented this and in Android 2.3.3 thumbnail image in the row gets cut off on each side. Can someone please test it? Thanks

    • Hman

      Ignore this guys. All good. Problem was somewhere else. Android 2.3.3 parsing the & in the URL differently.
      Thanks
      H

  • Carel

    GReat example, works like a charm. Question, If i download xml file images etc, and copy accross to my website to test (and yes, i did correct path of images) i keep getting 0 records from XML file – no errors in LOG, all work wells except, 0 records, any idea of where to start, most frustrating. regards Carl

  • Daniel Linsenbarth

    Trying to get this to work with AsyncTask. Could you show us how?

  • Ivan Molina

    yeah i agree with Daniel Linsenbarth , please Ravi Tamada , show us how to get this example working with Asynctask!

    • Idea Man

      I can share the fixed code which works with latest versions as well using Asynctask as well.
      luvrajind@gmail.com

      • Daniel Linsenbarth

        I have sent an email to you.

      • Ivan molina

        I already sent you an email,I’ll appreciate it.

    • Abdqr92
    • Vivek Priyadarshi

      hey molina

      just put this code in xml parsing class under public String getXmlFromUrl(String url) method

      if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
      }

      i hope you got the solution

      cheers !!

  • Bharat Jiyani

    Great Tutorial 🙂 Can anyone help on how to implement searchView with this list

    • abhimanyu

      use textwatcher..

  • Idea Man

    I can share the fixed code which works with latest versions as well using Asynctask as well.

    I am available at luvrajind@gmail.com

  • george

    Hi all. I am a novice in developing app and thanks to
    Ravi for all good work that is doing . I’m working at a simple app and I get
    stuck . if you have knowledge of
    building android apps, and make team
    with me please replay to george.celsie@gmail.com . Thanks ang
    good luck for all your projects.

  • jovel6

    hi ravi!nice blog, is there any way you can bulid an application wherein the data that will be displayed on the expandable list is from an xml file service?

  • mukund c.gokulan

    Hi, can u help me? i need a listview with two textviews, and using it i need to display 2 strings, string a, in large size and string b in small size, on clicking that list view string b should be passed. please help

  • Abdqr92

    refer to this URL to see how it works with Asynctask.
    http://stackoverflow.com/questions/8706464/defaulthttpclient-to-androidhttpclient

  • Bhavika Joshi

    It is very useful tutorial. Thank you very much for sharing your knowledge. I have little doubt about it is why we create list_selector.xml, gradient_bg.xml, gradient_bg_hover.xml, image_bg.xml files under drawable folder?? why not creating in layout folder???

  • Rohit Gupta

    Hi admin, I have got OutOfMemory error in this complete process, The size of images are 10kb – 20kb, How can I overcome from this problem.

  • Snn

    i hope one of you answer.
    how can i pick a image from this list and using by intent show in other activity ?
    for example. i want to show up albums cover in single row activity, how can i do that ?

  • Adrian

    Hi, everything works fine, thanks for the code, just one question.. i want to be able to click on each listview item and for each item to open a url on the phone browser, the url will also be on the xml, so each item has independent url (placed on each xml item manually by me)

  • Guest

    Can’t read the LazyAdapter.java -.-‘ please fix it.. some code as example:

    private ArrayList<HashMap<String, String>> data;

  • Guest

    public class LazyAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader;

    public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader=new ImageLoader(activity.getApplicationContext());
    }

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

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

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

    public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
    vi = inflater.inflate(R.layout.list_row, null);

    TextView title = (TextView)vi.findViewById(R.id.title); // title
    TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
    TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
    ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

    HashMap<String, String> song = new HashMap<String, String>();
    song = data.get(position);

    // Setting all values in listview
    title.setText(song.get(CustomizedListView.KEY_TITLE));
    artist.setText(song.get(CustomizedListView.KEY_ARTIST));
    duration.setText(song.get(CustomizedListView.KEY_DURATION));
    imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
    return vi;
    }
    }

  • Knot

    how do i setOnItemClickListener and let it Intent to another activity. and sent some (putExtra) value to another activity, please suggest me….

  • Rajan Lal

    Whats the use of imageViewReused? In which scenario this will help?

  • Hit Chikani

    private String writeXml(List messages){
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    try {
    serializer.setOutput(writer);
    serializer.startDocument(“UTF-8”, true);
    serializer.startTag(“”, “messages”);
    serializer.attribute(“”, “number”, String.valueOf(messages.size()));
    for (Message msg: messages){
    serializer.startTag(“”, “message”);
    serializer.attribute(“”, “date”, msg.getDate());
    serializer.startTag(“”, “title”);
    serializer.text(msg.getTitle());
    serializer.endTag(“”, “title”);
    serializer.startTag(“”, “url”);
    serializer.text(msg.getLink().toExternalForm());
    serializer.endTag(“”, “url”);
    serializer.startTag(“”, “body”);
    serializer.text(msg.getDescription());
    serializer.endTag(“”, “body”);
    serializer.endTag(“”, “message”);
    }
    serializer.endTag(“”, “messages”);
    serializer.endDocument();
    return writer.toString();
    } catch (Exception e) {
    throw new RuntimeException(e);
    }
    }

  • Jr Girotto

    Olá, Bom dia e Parabéns pelo Post. Alguém poderia me dizer como incluir uma BUSCA DINÂMICA nesse projeto? Ex.: …?????????????????????

  • Guest

    having issues getting this working with async task can some one please email me at wbrowser0900@gmail.com

  • nadhems

    can someone send me the json parsing sollution

    • Ronel Gonzales

      use this code

      /**
      * Async task class to get json by making HTTP call
      */
      private class GetSitesList extends AsyncTask {

      @Override
      protected void onPreExecute() {
      super.onPreExecute();
      // Showing progress dialog
      pDialog = new ProgressDialog(SiteListActivity.this);
      pDialog.setMessage(“Please wait…”);
      pDialog.setCancelable(false);
      pDialog.show();

      }

      @Override
      protected Void doInBackground(Void… arg0) {
      // Creating service handler class instance
      ServiceHandler sh = new ServiceHandler();

      // Making a request to url and getting response
      List params = new ArrayList();
      params.add(new BasicNameValuePair(“query_search”, “”));
      String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET, params);

      Log.d(“Response: “, “> ” + jsonStr);

      if (jsonStr != null) {
      try {
      JSONObject jsonObj = new JSONObject(jsonStr);

      // Getting JSON Array node
      // contacts = jsonObj.getJSONArray(TAG_CONTACTS);
      JSONArray array = new JSONArray(
      jsonObj.getString(TAG_SITELIST));
      // looping through All Contacts
      for (int i = 0; i < array.length(); i++) {

      JSONObject row = array.getJSONObject(i);

      String SiteCode = row.getString(TAG_SiteCode);
      String SiteName = row.getString(TAG_SiteName);
      String SiteAlias = row.getString(TAG_SiteAlias);
      String SiteMap= row.getString(TAG_SiteMap);
      // tmp hashmap for single contact
      HashMap contact = new HashMap();

      // adding each child node to HashMap key => value
      contact.put(TAG_SiteCode, SiteCode);
      contact.put(TAG_SiteName, SiteName);
      contact.put(TAG_SiteAlias, SiteAlias);
      contact.put(TAG_SiteMap, SiteMap);
      // adding contact to contact list
      SiteList.add(contact);
      }

      } catch (JSONException e) {
      e.printStackTrace();
      }
      } else {
      Log.e(“ServiceHandler”, “Couldn’t get any data from the url”);
      }

      return null;
      }

      @Override
      protected void onPostExecute(Void result) {
      super.onPostExecute(result);
      // Dismiss the progress dialog

      adapter=new SiteListAdapter(SiteListActivity.this,SiteList);
      list.setAdapter(adapter);

      if (pDialog.isShowing())
      pDialog.dismiss();
      }

    • Ronel Gonzales

      package com.example.pism;

      import java.io.IOException;
      import java.io.UnsupportedEncodingException;
      import java.util.List;

      import org.apache.http.HttpEntity;
      import org.apache.http.HttpResponse;
      import org.apache.http.NameValuePair;
      import org.apache.http.client.ClientProtocolException;
      import org.apache.http.client.entity.UrlEncodedFormEntity;
      import org.apache.http.client.methods.HttpGet;
      import org.apache.http.client.methods.HttpPost;
      import org.apache.http.client.utils.URLEncodedUtils;
      import org.apache.http.impl.client.DefaultHttpClient;
      import org.apache.http.util.EntityUtils;

      public class ServiceHandler {

      static String response = null;
      public final static int GET = 1;
      public final static int POST = 2;

      public ServiceHandler() {

      }

      /*
      * Making service call
      * @url – url to make request
      * @method – http request method
      * */
      public String makeServiceCall(String url, int method) {
      return this.makeServiceCall(url, method, null);
      }

      /*
      * Making service call
      * @url – url to make request
      * @method – http request method
      * @params – http request params
      * */
      public String makeServiceCall(String url, int method,
      List params) {
      try {
      // http client
      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpEntity httpEntity = null;
      HttpResponse httpResponse = null;

      // Checking http request method type
      if (method == POST) {
      HttpPost httpPost = new HttpPost(url);
      // adding post params
      if (params != null) {
      httpPost.setEntity(new UrlEncodedFormEntity(params));
      }

      httpResponse = httpClient.execute(httpPost);

      } else if (method == GET) {
      // appending params to url
      if (params != null) {
      String paramString = URLEncodedUtils
      .format(params, “utf-8”);
      url += “?” + paramString;
      }
      HttpGet httpGet = new HttpGet(url);

      httpResponse = httpClient.execute(httpGet);

      }
      httpEntity = httpResponse.getEntity();
      response = EntityUtils.toString(httpEntity);

      } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      } catch (ClientProtocolException e) {
      e.printStackTrace();
      } catch (IOException e) {
      e.printStackTrace();
      }

      return response;

      }
      }

  • nadhems

    please send me the json parsion solution for this tauto email ::: nadhems91@gmail.com

  • olbers

    very good tutorial to be developed

  • Are these two methods implemented as they should?

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

    I think they are not, because I dont see you using the “real” id of the song: the one in the map, with key KEY_ID.

    I think that the real intention was the following:

    public Object getItem(int position) {
    return this.data.get(position);
    }
    public long getItemId(int position) {
    return Long.parseLong(this.data.get(position).get(KEY_ID));
    }

    this way, the onItemClick receives a useful id parameter.

  • Hogehoge

    What’s the license for this source code?
    I couldn’t find the LICENSE file in this page and the file.

  • Ostap

    Thank you. I did this stuff differently but your solution is better.

  • Levent

    good job!
    well…how to adding search in it its so important Ravi
    Thx

  • kingmumu

    when i run the project, the log show it :error opening trace file: No such file or directory (2)

    Refusing to reopen boot DEX ‘/system/framework/hwframework.jar’

    (i couldn’t find where’s the error)

  • Chris

    Is it possible to use JSON-Objects instead of XML?

  • I want to ask that when clicked will appear from the new look how? example source code

  • Asis

    Hi,i fellow your lesson http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/

    , I have 3 fragments.xml .sould i create the class list_row.xml? thank you?

  • nadeem

    i have created my own xml and uploaded it on my ulr but not working with customlistview my xml url is http://www.academicwriters.org//Academicwriters/Quran/DrIsrarAhmed/audio.xml but not display any error or any row

  • Max

    Thanks a lot for such a wondeful post 🙂 It helped me a lot

    can i add search field for this ?

  • tia86

    There’s a serious bug in this example.
    The loader takes the ImageView reference so:
    1) if there’s a confguration change while the loader is downloading the image, the imageview reference is invalid. Also the GC cannot discard the view since it’s used by the loader (bad bad bad)
    2) Since the ListView tries to reuse the old row views, you have the chance to load the downloaded image on the wrong row

  • Rudi TheJack

    i use this code but something happening in logcat when i clicked listview:
    06-22 00:42:08.070: E/InputDispatcher(617): Motion event has invalid pointer count 0; value must be between 1 and 16.
    06-22 00:42:08.180: E/InputDispatcher(617): Motion event has invalid pointer count 0; value must be between 1 and 16.
    06-22 00:42:08.320: V/AudioHardware(526): open playback normal
    06-22 00:42:08.320: V/AudioHardware(526): write() wakeup setting route SPK

    whats wrong with this code or in my setting?

  • Farah

    Amazing tutorial! Many similar tutorials out there but yours has an amazing design for the listview items!

  • Michael

    Thanks for this code. But my problem with that is: How can i programmatically remove an item and repaint the view?
    Thanks for all answers in advance!

  • Ronel Gonzales

    thanks for this code. plz help i want my onitemclick not working..

  • teerapat

    why some image show but some image not show ?

  • hbibgi

    please this code doesn’t work on higer API it only works in API 8, 10 please help me i want your helps
    what can i do so that it works on higer API ex: on API 14 or 17 thanks!!

    • Vivek Priyadarshi

      just put this code under public String getXmlFromUrl(String url) in xml parsing class..her is the code

      if (android.os.Build.VERSION.SDK_INT > 9) {

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

      StrictMode.setThreadPolicy(policy);

      }

      hope this will work for you…

  • Ganesh

    I can’t download the source code.

  • hbibgi

    i done it but i don’t know how to get the xml photos please help me!

  • Arihant Jain

    can you please tell me how to use edit box in list view fro creating user entry form ??

  • Johnny B III

    I’ve tried to modify this to work in android studio to no avail.
    it needs the process to be in a background call to work. and i still cant get it to load for beans.

    ****** any one have a working zip file of an android studio project please? ******

    here is my project files so far. (please mod it to work if you can, i been trying for 3 days now looking up each error it gets – its nuts. way too many problems)

    http://dragonsworkshop.com/android/Events.zip

  • SONIARYA

    HOW WE CAN INSERT SPINNER TEXT+IMAGE IN SQLITE

  • Vivek Priyadarshi

    hi..

    very good tutorial but i have a problem ..when i change sdk vesrsion 19 .its shows an error.why
    ?? and how to solve this problem …plzzz reply anyone …

  • Sahil Kashyap

    would you help me use this code in upnp project

  • Dee

    hi

    thanks for this…

    where do the extra 5 files go? in which folder in the project?

    also what about the code for these files:

    @drawable/image_bg

    @drawable/rihanna
    @drawable/arrow

    the finished listview looks awesome

    however with the proper code for the files, it cannot be acheived..

    thanks

  • Vivek Priyadarshi

    how do i get images in another page ??

  • Hi

    Thanks to giving good code^^
    I use this project very well!

    However, I should use not English but Korean.

    How can I use korean parsing in the listview??

    Xml is made of korean characters.

    I am wondering how to use korean with utf-8.

  • Vivek Priyadarshi

    how do i add check box???

  • Felix

    great tutorial, thanks a lot

  • Aryan

    Love the way you lie rocks xd :p. Nice tutorial

  • Vega

    How do i add a search functionality for this one. Thank you

  • passingby

    Thank you for your Code.

  • Carl Wang

    I’m new in android. When I run these code, there are following exceptions thrown out,

    1.android-os-networkonmainthreadexception
    2.Only the original thread that created a view hierarchy can touch its views.

    My sdk info:

  • junior

    a question, if i want play a music from a remote server?

  • Don

    Look forward to your design section where you would hopefully focus on stuff that’s design oriented like this post.

  • Hello ravi, i face a problem in XMLParser.java file. It is showing a error “The method getElementsByTagName(String) is undefined for the type Element” . How can i solve this ??

    • Sardasht

      import this :
      import org.w3c.dom.Element;

  • Praveen Nikhare

    Can we create listview with radiobutton and imageview?

  • Prajwal

    How to add onClick to items inside the row.
    for eg adding OnClick Listener to TextView and Button residing inside RelativeLayout

  • Rege

    Dear All,

    First, I thank you this examples! 🙂

    What is the problem this code:

    20341-20341/com.example.shadow.upload E/AndroidRuntime﹕ FATAL EXCEPTION: main

    Process: com.example.shadow.upload, PID: 20341

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.shadow.upload/com.example.shadow.upload.GalleryActivity}: android.os.NetworkOnMainThreadException

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)

    at android.app.ActivityThread.access$800(ActivityThread.java:144)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:136)

    at android.app.ActivityThread.main(ActivityThread.java:5139)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:515)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)

    at dalvik.system.NativeStart.main(Native Method)

    Caused by: android.os.NetworkOnMainThreadException

    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)

    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)

    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)

    at java.net.InetAddress.getAllByName(InetAddress.java:214)

    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)

    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)

    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)

    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)

    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)

    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)

    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)

    at com.example.shadow.upload.XMLParser.getXmlFromUrl(XMLParser.java:45)

    at com.example.shadow.upload.GalleryActivity.onCreate(GalleryActivity.java:48)

    at android.app.Activity.performCreate(Activity.java:5231)

    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)

    at android.app.ActivityThread.access$800(ActivityThread.java:144)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:136)

    at android.app.ActivityThread.main(ActivityThread.java:5139)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:515)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)

    at dalvik.system.NativeStart.main(Native Method)

    GalleryActivity => CustomizedListView

    I create the Button and if I click button start GalleryActivity (alias: CustomizedListView)

    What the problem? I think 3 days ago :S

    Thanks for helps.

    • usee_me

      from your debug message, i think the problem happened because of http connection run on main thread. make it run on another thread using asynctask. you can find more information on android sdk documentation. thank you

  • Great Tutorial ,Thanks a lotzz……

  • N.vignesh kumar

    how to share image which shown in imageviewer, i have searched some of the code related to the topic but they shared a particular image only and they gave a name of the particular image in the program.but i am searching for share the image which is selected from imageview.

  • needmoretouch
  • waytoweb jain

    hey if i want to image load from internal memory like path is /data/data/com.wtow.restaurant/app_files/Restaurant/broccolicasserole.jpg.
    and i am use imageloader class. but i can not fatch image from that. please help me.
    its working from url image but if internal memory image not fatching

  • we need same like tutorial but when click on listview to open a new activity with detail….. from MYSQL Database… Thanks All (anyone can tell me) mhadevice@gmail.com

  • Ganza Charles

    you have nice tutorials, but you should use Android Studio. Eclipse is outdated

    • Yeah, but all these tutorials are posted before Android Studio is introduced. I am trying update one by one.

      • Ganza Charles

        yeah, i realized that some were made in 2012, Android Studio wasn’t made. i tried to follow these steps but they don’t work in Android Studio, i get many errors! nice work on the tutorials though 🙂

  • namo

    thanks sir for the tut. i believe that the same can be applied equally for a json fetched array results right?

  • Sikander Bhutto

    hi ravi, i’m using this code in fragment, where in my project two tabs
    one is “image” and second is “video” but this is not working error is
    showing in adapter please help me sikanderbhutto1@gmail.com

  • Parwez Khan

    package com.example.demodb;

    import java.util.ArrayList;

    import java.util.List;

    import com.example.adapter.StudentModel;

    import android.content.ContentValues;

    import android.content.Context;

    import android.database.Cursor;

    import android.database.sqlite.SQLiteDatabase;

    import android.database.sqlite.SQLiteDatabase.CursorFactory;

    import android.database.sqlite.SQLiteOpenHelper;

    import android.util.Log;

    import android.widget.Toast;

    public class DbHelper extends SQLiteOpenHelper {

    SQLiteDatabase db;

    public static final String DB_NAME = “MyDBName.db”;

    public static final String TABLE_NAME_STU = “student”;

    public static final String STUDENT_COLUMN_ROLL = “roll”;

    public static final String STUDENT_COLUMN_NAME = “sname”;

    public static final String STUDENT_COLUMN_CONTACT = “contact”;

    /*

    * static final String CREATE_DB_TABLE =” CREATE TABLE ” + TABLE_NAME_STU +

    * ” (_id INTEGER PRIMARY KEY AUTOINCREMENT, ” +” name TEXT NOT NULL, ”

    * +” grade TEXT NOT NULL);”;

    */

    public DbHelper(Context context) {

    super(context, DB_NAME, null, 1);

    // TODO Auto-generated constructor stub

    }

    @Override

    public void onCreate(SQLiteDatabase db) {

    // TODO Auto-generated method stub

    db.execSQL(“create table ” + TABLE_NAME_STU + “(ID INTEGER PRIMARY KEY AUTOINCREMENT, ” + STUDENT_COLUMN_NAME

    + ” text, ” + STUDENT_COLUMN_ROLL + ” text, ” + STUDENT_COLUMN_CONTACT + ” text);”);

    /*

    * String a=”CREATE TABLE Persons ( ID int NOT NULL AUTO_INCREMENT,

    * LastName varchar(255) NOT NULL, FirstName varchar(255), Address

    * varchar(255), City varchar(255), PRIMARY KEY (ID) )”;

    */

    }

    public boolean chkalready(String roll, String contact) {

    String sql = “SELECT * FROM ” + TABLE_NAME_STU + ” WHERE roll=” + roll + ” OR contact=” + contact;

    db = this.getReadableDatabase();

    Log.d(“Query”, sql);

    // Cursor mCursor = db.rawQuery(“SELECT * FROM ” + TABLE_NAME_STU +

    // ” WHERE roll=? OR contact=?”, new String[]{roll,contact});

    Cursor mCursor = db.rawQuery(sql, null);

    if (mCursor.getCount() > 0) {

    return true;

    } else {

    return false;

    }

    }

    public boolean insdataStudent(String name, String roll, String contact) {

    db = this.getWritableDatabase();

    ContentValues cv = new ContentValues();

    cv.put(STUDENT_COLUMN_NAME, name);

    cv.put(STUDENT_COLUMN_ROLL, roll);

    cv.put(STUDENT_COLUMN_CONTACT, contact);

    db.insert(TABLE_NAME_STU, null, cv);

    db.close();

    return true;

    }

    public List Stdetails() {

    /*

    * ArrayList stname = new ArrayList(); ArrayList

    * roll = new ArrayList(); ArrayList contact = new

    * ArrayList();

    */

    List studentlist = new ArrayList();

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor res = db.rawQuery(“select * from student”, null);

    res.moveToFirst();

    /*

    * while(res.isAfterLast() == false) {

    * stname.add(res.getString(res.getColumnIndex(STUDENT_COLUMN_NAME)));

    * roll.add(res.getString(res.getColumnIndex(STUDENT_COLUMN_ROLL)));

    * contact

    * .add(res.getString(res.getColumnIndex(STUDENT_COLUMN_CONTACT)));

    * res.moveToNext(); }

    */

    if (res.moveToFirst()) {

    do {

    StudentModel stmodel = new StudentModel();

    /* appStatus.setId(Integer.parseInt(cursor.getString(0))); */

    stmodel.setName(res.getString(1));

    stmodel.setRoll(res.getString(2));

    stmodel.setContact(res.getString(3));

    studentlist.add(stmodel);

    } while (res.moveToNext());

    }

    return studentlist;

    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL(“DROP TABLE IF EXISTS student”);

    onCreate(db);

    }

    }

  • Parwez

    package com.example.demodb;

    import java.util.ArrayList;

    import java.util.List;

    import com.example.adapter.CustomListAdapter;

    import com.example.adapter.StudentModel;

    import android.support.v7.app.ActionBarActivity;

    import android.app.Activity;

    import android.content.Intent;

    import android.net.Uri;

    import android.os.Bundle;

    import android.util.Log;

    import android.view.Menu;

    import android.view.MenuItem;

    import android.view.View;

    import android.view.View.OnClickListener;

    import android.widget.AdapterView;

    import android.widget.AdapterView.OnItemClickListener;

    import android.widget.ArrayAdapter;

    import android.widget.ImageView;

    import android.widget.ListView;

    import android.widget.TextView;

    import android.widget.Toast;

    public class RetrieveDetails extends Activity {

    ListView lv;

    DbHelper mydb;

    List ss;

    ImageView txt_call;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_retrieve_details);

    mydb = new DbHelper(this);

    // Log.d(“Check Point”, “Point 1”);

    // mydb = new DbHelper(this);

    lv = (ListView) findViewById(R.id.lv1);

    ss = mydb.Stdetails();

    String[] sname = new String[ss.size()];

    // Log.d(“Check Point 1”, “” + sname);

    String[] roll = new String[ss.size()];

    String[] con = new String[ss.size()];

    for (int i = 0; i < ss.size(); i++) {

    Log.d("cccc", "" + ss.get(i));

    sname[i] = ss.get(i).getName();

    roll[i] = ss.get(i).getRoll();

    con[i] = ss.get(i).getContact();

    }

    // Log.d("Check Point 2", "" + ss);

    // ArrayList aa=(ArrayList)

    // mydb.getAllStudent();

    // Log.d(“detail”, “”+aa);

    CustomListAdapter adapter = new CustomListAdapter(this, sname, roll, con);

    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new OnItemClickListener() {

    @Override

    public void onItemClick(AdapterView parent, View view, final int position, long id) {

    txt_call = (ImageView) view.findViewById(R.id.txt_call);

    txt_call.setOnClickListener(new OnClickListener() {

    @Override

    public void onClick(View v) {

    Toast.makeText(getApplicationContext(), “Clicked Item” + ss.get(position).getContact(),

    Toast.LENGTH_SHORT).show();

    Intent callIntent = new Intent(Intent.ACTION_CALL);

    callIntent.setData(Uri.parse(“tel:” + ss.get(position).getContact().toString()));

    startActivity(callIntent);

    }

    });

    // Toast.makeText(getApplicationContext(), “Clicked Item”,

    // Toast.LENGTH_SHORT).show();

    }

    });

    }

    }

  • Parwez

    package com.example.adapter;

    import java.util.ArrayList;

    import com.example.demodb.R;

    import com.example.adapter.*;

    import android.app.Activity;

    import android.content.Context;

    import android.support.v4.app.INotificationSideChannel.Stub;

    import android.view.LayoutInflater;

    import android.view.View;

    import android.view.ViewGroup;

    import android.widget.ArrayAdapter;

    import android.widget.ImageView;

    import android.widget.TextView;

    public class CustomListAdapter extends ArrayAdapter {

    private final Activity context;

    private final String[] stname;

    private final String[] roll;

    private final String[] contact;

    public CustomListAdapter(Activity context, String[] stname, String[] roll, String[] contact) {

    super(context, R.layout.itemdemolist, contact);

    // TODO Auto-generated constructor stub

    this.context = context;

    this.stname = stname;

    this.roll = roll;

    this.contact = contact;

    }

    public View getView(int position, View view, ViewGroup parent) {

    LayoutInflater inflater = context.getLayoutInflater();

    View rowView = inflater.inflate(R.layout.itemdemolist, null, true);

    TextView snam = (TextView) rowView.findViewById(R.id.stname);

    TextView rolla = (TextView) rowView.findViewById(R.id.roll);

    TextView con = (TextView) rowView.findViewById(R.id.contact);

    snam.setText(stname[position]);

    rolla.setText(roll[position]);

    con.setText(contact[position]);

    return rowView;

    };

    }

    /*

    * public class CustomListAdapter extends ArrayAdapter {

    *

    * public CustomListAdapter(Context context, ArrayList stmo) {

    * super(context, 0, stmo);

    *

    * }

    *

    * public View getview(int position, View convertView, ViewGroup parent) {

    * StudentModel st = getItem(position); if (convertView == null) { convertView =

    * LayoutInflater.from(getContext()).inflate(R.layout.itemdemolist, parent,

    * false); }

    *

    * TextView snam = (TextView) convertView.findViewById(R.id.stname); TextView

    * rolla = (TextView) convertView.findViewById(R.id.roll); TextView con =

    * (TextView) convertView.findViewById(R.id.contact); snam.setText(st.name);

    * rolla.setText(st.roll); con.setText(st.contact);

    *

    *

    * LayoutInflater linf= context.getLayoutInflater(); //LayoutInflater inflater =

    * (LayoutInflater)

    * getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v =

    * linf.inflate(R.layout.itemdemolist, null); TextView snam = (TextView)

    * v.findViewById(R.id.stname); TextView rolla = (TextView)

    * v.findViewById(R.id.roll); TextView con = (TextView)

    * v.findViewById(R.id.contact);

    *

    * menu_txt.setText(itemname[position]);

    * imageView.setImageResource(imgid[position]);

    *

    * return rowView;

    *

    * snam.setText(stname[position]); rolla.setText(roll[position]);

    * con.setText(contact[position]);

    *

    * return convertView;

    *

    * }

    *

    * }

    */

  • Koja

    Very bad practice to put IO on main thread… So bad that it will refuse to even run… Also “public class CustomizedListView extends Activity” in MainActivity.class cannot run because the class is MainActivity, not CustomizedListView one.

  • Ajzaja Patatajcev

    resp3kt specially for handling images from url … its awesome .. and safed me like a month of reserches ?? tnx dud

  • Massire Dia

    Thank you. I just needed the lit_row.xml file (y)

  • jim

    thanks.
    I am not able to view image with my xml file.its perfect working and same o/p as your(music.xml). but not fetch image, plz provide xml file.

  • Frans Appel

    Mainactivity: for (int I = 0; I < nl.getLength(); i++)
    I ?, really ???? No, it must be i !!! (all I or all i but not both !!)

  • Wes

    Can I use this custom list adapter with the json data from http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ <– THAT article?

  • Tendo

    Hi,

    Can you change the getXmlFromUrl function using HttpUrlConnection ?

  • Murtuza

    ArrayList<HashMap<String, String>> data;

    what is this cant understand plz explain thankyou

    • as

      Map<ImageView, String>

      • asd

        WeakHashMap<ImageView, String>

    • as

      width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE

  • sdd

    Map<String, SoftReference<Bitmap>>

  • asdsda

    ArrayList<HashMap<String, String>> d

  • Александр Сидоров

    Use AsyncTask.

    Edit XMLParser getXMLFromUrl method like this:

    public String getXmlFromUrl(String url) {
    String xml = null;

    try {
    xml = new RequestTask().execute(url).get();
    } catch (InterruptedException e) {
    e.printStackTrace();
    } catch (ExecutionException e) {
    e.printStackTrace();
    }
    return xml;
    }

    Add class RequestTask:

    class RequestTask extends AsyncTask {

    @Override
    protected void onPostExecute(String result) {
    super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    }

    @Override
    protected String doInBackground(String… params) {
    try {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(params[0]);
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
    return EntityUtils.toString(httpEntity);
    } else {
    return null;
    }
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return null;
    }
    }

  • Parwez KHan

    import android.os.Bundle;

    import android.support.design.widget.FloatingActionButton;

    import android.support.design.widget.Snackbar;

    import android.support.v7.app.AppCompatActivity;

    import android.support.v7.widget.GridLayoutManager;

    import android.support.v7.widget.LinearLayoutManager;

    import android.support.v7.widget.RecyclerView;

    import android.support.v7.widget.StaggeredGridLayoutManager;

    import android.support.v7.widget.Toolbar;

    import android.view.View;

    import android.view.Menu;

    import android.view.MenuItem;

    import android.widget.Toast;

    import java.util.ArrayList;

    public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView1;

    private String[] name = {“Parwez”, “Goutam”, “Priyam”, “Koushik”, “Hari Narayan”, “Hari Shankar”, “Surojit”, “Arindam”, “Tirtha”};

    private RecyclerView.Adapter adapter;

    private RecyclerView.LayoutManager mLayoutManager;

    private ArrayList nameArrayList = new ArrayList();

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View view) {

    Snackbar.make(view, “Replace with your own action”, Snackbar.LENGTH_LONG)

    .setAction(“Action”, new View.OnClickListener() {

    @Override

    public void onClick(View v) {

    Toast.makeText(getApplicationContext(), “SnackBar Click event”, Toast.LENGTH_LONG).show();

    }

    }).show();

    }

    });

    recyclerView1 = (RecyclerView) findViewById(R.id.recyclerView1);

    //Set the Layout Manager for RecyclerView

    mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);

    //mLayoutManager = new GridLayoutManager(this,3);

    //mLayoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.HORIZONTAL);

    recyclerView1.setLayoutManager(mLayoutManager);

    //Make the Arraylist from String array

    for (int i = 0; i < name.length; i++) {

    nameArrayList.add(name[i]);

    }

    //Make the adapter

    adapter = new MyAdapter(nameArrayList);

    //Set adapter in RecyclerView

    recyclerView1.setAdapter(adapter);

    }

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.menu_main, menu);

    return true;

    }

    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

    // Handle action bar item clicks here. The action bar will

    // automatically handle clicks on the Home/Up button, so long

    // as you specify a parent activity in AndroidManifest.xml.

    int id = item.getItemId();

    //noinspection SimplifiableIfStatement

    if (id == R.id.action_settings) {

    return true;

    }

    return super.onOptionsItemSelected(item);

    }

    }

  • Parwez KHan

    import android.support.design.widget.Snackbar;

    import android.support.v7.widget.RecyclerView;

    import android.view.LayoutInflater;

    import android.view.View;

    import android.view.ViewGroup;

    import android.widget.TextView;

    import java.util.ArrayList;

    /**

    * Created by simayaa on 10/30/2015.

    */

    public class MyAdapter extends RecyclerView.Adapter {

    //ArrayList to hold the fetched data from MainActivity

    private ArrayList mDataSet;

    //Constructor

    public MyAdapter(ArrayList mDataSet) {

    this.mDataSet = mDataSet;

    }

    //Return a new ViewHolder using you custom Layout

    @Override

    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_item,parent,false);

    ViewHolder vh = new ViewHolder(view);

    return vh;

    }

    //Set the content into the view in ViewHolder

    @Override

    public void onBindViewHolder(ViewHolder holder, final int position) {

    final String name = mDataSet.get(position);

    holder.textView.setText(name);

    holder.textView.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

    Snackbar.make(v, name+ “Deleted”, Snackbar.LENGTH_LONG).show();

    //Remove and item from RecyclerView

    mDataSet.remove(position);

    notifyItemRemoved(position);

    }

    });

    }

    //Get the size of arraylise

    @Override

    public int getItemCount() {

    return mDataSet.size();

    }

    //Implement ViewHolder Class

    public class ViewHolder extends RecyclerView.ViewHolder{

    public TextView textView;

    public ViewHolder(View itemView) {

    super(itemView);

    textView = (TextView) itemView.findViewById(R.id.textView);

    }

    }

    }

  • Santu Makur

    public String getJSONStringFromUrl(String url, HashMap map, String imageParam) {

    // Making HTTP request
    try {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();

    StrictMode.setThreadPolicy(policy);

    Log.v(“HttpMine”, map.toString());
    Log.v(“HttpMine”, imageParam);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Iterator it = map.keySet().iterator();
    while (it.hasNext()) {
    String key = it.next();
    if (imageParam.equals(“image”)) {// if (key.equals())
    if (key.equals(“image”)) {
    if (!map.get(key).equals(“”)) {
    reqEntity.addPart(“image”, new FileBody(new File(map.get(key))));
    }
    }else{
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }else if(imageParam.equals(“post_image”)) {
    if (key.equals(“post_image_1”)) {
    if (!map.get(key).equals(“”)) {
    reqEntity.addPart(“post_image_1”, new FileBody(new File(map.get(key))));
    }
    }else{
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }else if(imageParam.equals(“”)){
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(reqEntity);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }
    is.close();
    json = sb.toString();
    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

  • Santu Makur

    package com.marcel.headstrongperformance.httphandler;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;

    import javax.net.ssl.HttpsURLConnection;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import android.annotation.SuppressLint;
    import android.annotation.TargetApi;
    import android.content.Context;
    import android.os.Build;
    import android.os.StrictMode;
    import android.util.Log;

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public class HttpHandler /*extends DefaultHttpClient*/{

    InputStream is = null;
    JSONObject jObj = null;
    String json = “”;
    JSONArray jArray = null;
    private Context context;

    // constructor
    public HttpHandler() {

    }

    // constructor
    public HttpHandler(Context context) {
    this.context = context;
    }

    @SuppressLint(“LongLogTag”)
    public String getJSONStringFromUrl(String url) {

    // Making HTTP request
    try {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();

    StrictMode.setThreadPolicy(policy);
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “iso-8859-1”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }
    is.close();
    json = sb.toString();
    } catch (Exception e) {
    Log.e(“Buffer Error Goutam ———>”, “Error converting result ” + e.toString());
    }

    // return JSON String
    //Log.i(“RETURN JSON :————– > “,json);
    return json;

    }

    public String getJSONStringFromUrlT(String url,Map map) {

    // Making HTTP request
    try {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();

    StrictMode.setThreadPolicy(policy);

    ArrayList nameValuePair = new ArrayList();
    Iterator it = map.keySet().iterator();
    while (it.hasNext()) {
    String key = it.next();
    nameValuePair.add(new BasicNameValuePair(key, map.get(key)));
    }
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, “UTF-8”));

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }
    is.close();
    json = sb.toString();
    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getJSONStringFromUrl(String url, HashMap map, String imageParam) {

    // Making HTTP request
    try {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();

    StrictMode.setThreadPolicy(policy);

    Log.v(“HttpMine”, map.toString());
    Log.v(“HttpMine”, imageParam);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Iterator it = map.keySet().iterator();
    while (it.hasNext()) {
    String key = it.next();
    if (imageParam.equals(“image”)) {// if (key.equals())
    if (key.equals(“image”)) {
    if (!map.get(key).equals(“”)) {
    reqEntity.addPart(“image”, new FileBody(new File(map.get(key))));
    }
    }else{
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }else if(imageParam.equals(“post_image”)) {
    if (key.equals(“post_image_1”)) {
    if (!map.get(key).equals(“”)) {
    reqEntity.addPart(“post_image_1”, new FileBody(new File(map.get(key))));
    }
    }else{
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }else if(imageParam.equals(“”)){
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(reqEntity);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }
    is.close();
    json = sb.toString();
    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparams(String urlString,MultipartEntity reqEntity) {
    try {

    URL url = new URL(urlString);
    HttpsURLConnection urlConnection =
    (HttpsURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    ///////////////////////////////////////////////////////////////////////////////////////////////

    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparamsGoutam(String urlString,MultipartEntity reqEntity) {
    try {

    String attachmentName = “bitmap”;
    String attachmentFileName = “bitmap.bmp”;
    String crlf = “rn”;
    String twoHyphens = “–“;
    String boundary = “*****”;
    URL url = new URL(urlString);
    HttpURLConnection urlConnection =
    (HttpURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    ///////////////////////////////////////////////////////////////////////////////////////////////

    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }

    String renameFile = reqEntity.getContentType().getName();

    Log.v(“”, “renameFile:”+renameFile);
    Log.v(“”, ” reqEntity.getContentType().getValue():”+ reqEntity.getContentType().getValue());

    urlConnection.setRequestProperty(“Accept-Charset”, “UTF-8”);
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.setRequestProperty(“Cache-Control”, “no-cache”);
    urlConnection.setRequestProperty(“Content-Type”, “multipart/form-data;boundary=” + boundary);
    // urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
    urlConnection.setRequestProperty(“file”, reqEntity.getContentType().getValue());

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparamsGoutam(String urlString,MultipartEntity reqEntity,String renameFile) {
    try {

    String attachmentName = “bitmap”;
    String attachmentFileName = “bitmap.bmp”;
    String crlf = “rn”;
    String twoHyphens = “–“;
    String boundary = “*****”;
    /*// Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or …)
    CertificateFactory cf = CertificateFactory.getInstance(“X.509”);
    // From https://www.washington.edu/itconnect/security/ca/load-der.crt
    //InputStream caInput = new BufferedInputStream(new FileInputStream(“load-der.crt”));
    InputStream caInput = context.getResources().openRawResource(R.raw.epay_wild_card);
    Certificate ca;
    try {
    ca = cf.generateCertificate(caInput);
    System.out.println(“ca=” + ((X509Certificate) ca).getSubjectDN());
    } finally {
    caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry(“ca”, ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance(“TLS”);
    context.init(null, tmf.getTrustManagers(), null);*/

    // Tell the URLConnection to use a SocketFactory from our SSLContext
    URL url = new URL(urlString);
    HttpURLConnection urlConnection =
    (HttpURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    ///////////////////////////////////////////////////////////////////////////////////////////////

    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }

    // String renameFile = reqEntity.getContentType().getName();

    Log.v(“”, “renameFile:”+renameFile);
    //Log.v(“”, ” reqEntity.getContentType().getValue():”+ reqEntity.getContentType().getValue());

    urlConnection.setRequestProperty(“Accept-Charset”, “UTF-8”);
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.setRequestProperty(“Cache-Control”, “no-cache”);
    //urlConnection.setRequestProperty(“Content-Type”, “multipart/form-data;boundary=” + boundary);
    urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
    urlConnection.setRequestProperty(“image”, renameFile);

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    }

  • Tarez Khan

    package com.marcel.headstrongperformance.httphandler;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;

    import javax.net.ssl.HttpsURLConnection;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import android.annotation.SuppressLint;
    import android.annotation.TargetApi;
    import android.content.Context;
    import android.os.Build;
    import android.os.StrictMode;
    import android.util.Log;

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public class HttpHandler /*extends DefaultHttpClient*/{

    InputStream is = null;
    JSONObject jObj = null;
    String json = “”;
    JSONArray jArray = null;
    private Context context;

    // constructor
    public HttpHandler() {

    }

    // constructor
    public HttpHandler(Context context) {
    this.context = context;
    }

    @SuppressLint(“LongLogTag”)
    public String getJSONStringFromUrl(String url) {

    // Making HTTP request
    try {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();

    StrictMode.setThreadPolicy(policy);
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “iso-8859-1”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }
    is.close();
    json = sb.toString();
    } catch (Exception e) {
    Log.e(“Buffer Error Goutam ———>”, “Error converting result ” + e.toString());
    }

    // return JSON String
    //Log.i(“RETURN JSON :————– > “,json);
    return json;

    }

    public String getJSONStringFromUrlT(String url,Map map) {

    // Making HTTP request
    try {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();

    StrictMode.setThreadPolicy(policy);

    ArrayList nameValuePair = new ArrayList();
    Iterator it = map.keySet().iterator();
    while (it.hasNext()) {
    String key = it.next();
    nameValuePair.add(new BasicNameValuePair(key, map.get(key)));
    }
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, “UTF-8”));

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }
    is.close();
    json = sb.toString();
    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getJSONStringFromUrl(String url, HashMap map, String imageParam) {

    // Making HTTP request
    try {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();

    StrictMode.setThreadPolicy(policy);

    Log.v(“HttpMine”, map.toString());
    Log.v(“HttpMine”, imageParam);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Iterator it = map.keySet().iterator();
    while (it.hasNext()) {
    String key = it.next();
    if (imageParam.equals(“image”)) {// if (key.equals())
    if (key.equals(“image”)) {
    if (!map.get(key).equals(“”)) {
    reqEntity.addPart(“image”, new FileBody(new File(map.get(key))));
    }
    }else{
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }else if(imageParam.equals(“post_image”)) {
    if (key.equals(“post_image_1”)) {
    if (!map.get(key).equals(“”)) {
    reqEntity.addPart(“post_image_1”, new FileBody(new File(map.get(key))));
    }
    }else{
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }else if(imageParam.equals(“”)){
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(reqEntity);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }
    is.close();
    json = sb.toString();
    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparams(String urlString,MultipartEntity reqEntity) {
    try {

    URL url = new URL(urlString);
    HttpsURLConnection urlConnection =
    (HttpsURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    ///////////////////////////////////////////////////////////////////////////////////////////////

    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparamsGoutam(String urlString,MultipartEntity reqEntity) {
    try {

    String attachmentName = “bitmap”;
    String attachmentFileName = “bitmap.bmp”;
    String crlf = “rn”;
    String twoHyphens = “–“;
    String boundary = “*****”;
    URL url = new URL(urlString);
    HttpURLConnection urlConnection =
    (HttpURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    ///////////////////////////////////////////////////////////////////////////////////////////////

    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }

    String renameFile = reqEntity.getContentType().getName();

    Log.v(“”, “renameFile:”+renameFile);
    Log.v(“”, ” reqEntity.getContentType().getValue():”+ reqEntity.getContentType().getValue());

    urlConnection.setRequestProperty(“Accept-Charset”, “UTF-8”);
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.setRequestProperty(“Cache-Control”, “no-cache”);
    urlConnection.setRequestProperty(“Content-Type”, “multipart/form-data;boundary=” + boundary);
    // urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
    urlConnection.setRequestProperty(“file”, reqEntity.getContentType().getValue());

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparamsGoutam(String urlString,MultipartEntity reqEntity,String renameFile) {
    try {

    String attachmentName = “bitmap”;
    String attachmentFileName = “bitmap.bmp”;
    String crlf = “rn”;
    String twoHyphens = “–“;
    String boundary = “*****”;
    /*// Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or …)
    CertificateFactory cf = CertificateFactory.getInstance(“X.509”);
    // From https://www.washington.edu/itconnect/security/ca/load-der.crt
    //InputStream caInput = new BufferedInputStream(new FileInputStream(“load-der.crt”));
    InputStream caInput = context.getResources().openRawResource(R.raw.epay_wild_card);
    Certificate ca;
    try {
    ca = cf.generateCertificate(caInput);
    System.out.println(“ca=” + ((X509Certificate) ca).getSubjectDN());
    } finally {
    caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry(“ca”, ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance(“TLS”);
    context.init(null, tmf.getTrustManagers(), null);*/

    // Tell the URLConnection to use a SocketFactory from our SSLContext
    URL url = new URL(urlString);
    HttpURLConnection urlConnection =
    (HttpURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    ///////////////////////////////////////////////////////////////////////////////////////////////

    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }

    // String renameFile = reqEntity.getContentType().getName();

    Log.v(“”, “renameFile:”+renameFile);
    //Log.v(“”, ” reqEntity.getContentType().getValue():”+ reqEntity.getContentType().getValue());

    urlConnection.setRequestProperty(“Accept-Charset”, “UTF-8”);
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.setRequestProperty(“Cache-Control”, “no-cache”);
    //urlConnection.setRequestProperty(“Content-Type”, “multipart/form-data;boundary=” + boundary);
    urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
    urlConnection.setRequestProperty(“image”, renameFile);

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    }

  • Tarez Khan

    Part 1
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;

    import javax.net.ssl.HttpsURLConnection;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import android.annotation.SuppressLint;
    import android.annotation.TargetApi;
    import android.content.Context;
    import android.os.Build;
    import android.os.StrictMode;
    import android.util.Log;

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public class HttpHandler /*extends DefaultHttpClient*/{

    InputStream is = null;
    JSONObject jObj = null;
    String json = “”;
    JSONArray jArray = null;
    private Context context;

    // constructor
    public HttpHandler() {

    }

    // constructor
    public HttpHandler(Context context) {
    this.context = context;
    }

    @SuppressLint(“LongLogTag”)
    public String getJSONStringFromUrl(String url) {

    // Making HTTP request
    try {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();

    StrictMode.setThreadPolicy(policy);
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “iso-8859-1”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }
    is.close();
    json = sb.toString();
    } catch (Exception e) {
    Log.e(“Buffer Error Goutam ———>”, “Error converting result ” + e.toString());
    }

    // return JSON String
    //Log.i(“RETURN JSON :————– > “,json);
    return json;

    }

    public String getJSONStringFromUrlT(String url,Map map) {

    // Making HTTP request
    try {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();

    StrictMode.setThreadPolicy(policy);

    ArrayList nameValuePair = new ArrayList();
    Iterator it = map.keySet().iterator();
    while (it.hasNext()) {
    String key = it.next();
    nameValuePair.add(new BasicNameValuePair(key, map.get(key)));
    }
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, “UTF-8”));

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }
    is.close();
    json = sb.toString();
    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    Log.i(“RETURN JSON: “,json);
    return json;

    }

    /*public String getJSONStringFromUrlSsl(String url) {

    // Making HTTP request
    try {
    // Instantiate the custom HttpClient
    DefaultHttpClient httpClient = new CustomHttpClient(context);
    HttpGet get = new HttpGet(url);
    // Execute the GET call and obtain the response
    HttpResponse httpResponse = httpClient.execute(get);

    //DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

    // Set verifier
    //HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    // Example send http request
    //HttpPost httpPost = new HttpPost(url);
    //HttpResponse httpResponse = httpClient.execute(httpPost);

    //HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    }
    catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    }
    catch (ClientProtocolException e) {
    e.printStackTrace();
    }
    catch (IOException e) {
    e.printStackTrace();
    }
    catch (Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }
    is.close();
    json = sb.toString();
    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    Log.i(“RETURN JSON: “,json);
    return json;

    }*/

    public String getJSONStringFromUrl(String url, HashMap map, String imageParam) {

    // Making HTTP request
    try {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
    .permitAll().build();

    StrictMode.setThreadPolicy(policy);

    Log.v(“HttpMine”, map.toString());
    Log.v(“HttpMine”, imageParam);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Iterator it = map.keySet().iterator();
    while (it.hasNext()) {
    String key = it.next();
    if (imageParam.equals(“image”)) {// if (key.equals())
    if (key.equals(“image”)) {
    if (!map.get(key).equals(“”)) {
    reqEntity.addPart(“image”, new FileBody(new File(map.get(key))));
    }
    }else{
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }else if(imageParam.equals(“post_image”)) {
    if (key.equals(“post_image_1”)) {
    if (!map.get(key).equals(“”)) {
    reqEntity.addPart(“post_image_1”, new FileBody(new File(map.get(key))));
    }
    }else{
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }else if(imageParam.equals(“”)){
    reqEntity.addPart(key, new StringBody(map.get(key)));
    }
    }
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(reqEntity);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }
    is.close();
    json = sb.toString();
    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

  • Tarez Khan

    part 2
    public String getSslDoinbgPostwithparams(String urlString,MultipartEntity reqEntity) {
    try {
    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or …)
    /*CertificateFactory cf = CertificateFactory.getInstance(“X.509”);
    // From https://www.washington.edu/itconnect/security/ca/load-der.crt
    //InputStream caInput = new BufferedInputStream(new FileInputStream(“load-der.crt”));
    InputStream caInput = context.getResources().openRawResource(R.raw.epay_wild_card);
    Certificate ca;
    try {
    ca = cf.generateCertificate(caInput);
    System.out.println(“ca=” + ((X509Certificate) ca).getSubjectDN());
    } finally {
    caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry(“ca”, ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance(“TLS”);
    context.init(null, tmf.getTrustManagers(), null);*/

    // Tell the URLConnection to use a SocketFactory from our SSLContext
    URL url = new URL(urlString);
    HttpsURLConnection urlConnection =
    (HttpsURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    ///////////////////////////////////////////////////////////////////////////////////////////////

    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparamsGoutam(String urlString,MultipartEntity reqEntity) {
    try {

    String attachmentName = “bitmap”;
    String attachmentFileName = “bitmap.bmp”;
    String crlf = “rn”;
    String twoHyphens = “–“;
    String boundary = “*****”;
    /*// Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or …)
    CertificateFactory cf = CertificateFactory.getInstance(“X.509”);
    // From https://www.washington.edu/itconnect/security/ca/load-der.crt
    //InputStream caInput = new BufferedInputStream(new FileInputStream(“load-der.crt”));
    InputStream caInput = context.getResources().openRawResource(R.raw.epay_wild_card);
    Certificate ca;
    try {
    ca = cf.generateCertificate(caInput);
    System.out.println(“ca=” + ((X509Certificate) ca).getSubjectDN());
    } finally {
    caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry(“ca”, ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance(“TLS”);
    context.init(null, tmf.getTrustManagers(), null);*/

    // Tell the URLConnection to use a SocketFactory from our SSLContext
    URL url = new URL(urlString);
    HttpURLConnection urlConnection =
    (HttpURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    ///////////////////////////////////////////////////////////////////////////////////////////////

    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }

    String renameFile = reqEntity.getContentType().getName();

    Log.v(“”, “renameFile:”+renameFile);
    Log.v(“”, ” reqEntity.getContentType().getValue():”+ reqEntity.getContentType().getValue());

    urlConnection.setRequestProperty(“Accept-Charset”, “UTF-8”);
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.setRequestProperty(“Cache-Control”, “no-cache”);
    urlConnection.setRequestProperty(“Content-Type”, “multipart/form-data;boundary=” + boundary);
    // urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
    urlConnection.setRequestProperty(“file”, reqEntity.getContentType().getValue());

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparamsGoutam(String urlString,MultipartEntity reqEntity,String renameFile) {
    try {

    String attachmentName = “bitmap”;
    String attachmentFileName = “bitmap.bmp”;
    String crlf = “rn”;
    String twoHyphens = “–“;
    String boundary = “*****”;
    /*// Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or …)
    CertificateFactory cf = CertificateFactory.getInstance(“X.509”);
    // From https://www.washington.edu/itconnect/security/ca/load-der.crt
    //InputStream caInput = new BufferedInputStream(new FileInputStream(“load-der.crt”));
    InputStream caInput = context.getResources().openRawResource(R.raw.epay_wild_card);
    Certificate ca;
    try {
    ca = cf.generateCertificate(caInput);
    System.out.println(“ca=” + ((X509Certificate) ca).getSubjectDN());
    } finally {
    caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry(“ca”, ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance(“TLS”);
    context.init(null, tmf.getTrustManagers(), null);*/

    // Tell the URLConnection to use a SocketFactory from our SSLContext
    URL url = new URL(urlString);
    HttpURLConnection urlConnection =
    (HttpURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    ///////////////////////////////////////////////////////////////////////////////////////////////

    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }

    // String renameFile = reqEntity.getContentType().getName();

    Log.v(“”, “renameFile:”+renameFile);
    //Log.v(“”, ” reqEntity.getContentType().getValue():”+ reqEntity.getContentType().getValue());

    urlConnection.setRequestProperty(“Accept-Charset”, “UTF-8”);
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.setRequestProperty(“Cache-Control”, “no-cache”);
    //urlConnection.setRequestProperty(“Content-Type”, “multipart/form-data;boundary=” + boundary);
    urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
    urlConnection.setRequestProperty(“image”, renameFile);

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    }

  • Tarez Khan

    public String getSslDoinbgPostwithparams(String urlString,MultipartEntity reqEntity) {
    try {

    URL url = new URL(urlString);
    HttpsURLConnection urlConnection =
    (HttpsURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    ///////////////////////////////////////////////////////////////////////////////////////////////

    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparamsGoutam(String urlString,MultipartEntity reqEntity) {
    try {

    String attachmentName = “bitmap”;
    String attachmentFileName = “bitmap.bmp”;
    String crlf = “rn”;
    String twoHyphens = “–“;
    String boundary = “*****”;
    /*// Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or …)
    CertificateFactory cf = CertificateFactory.getInstance(“X.509”);
    // From https://www.washington.edu/itconnect/security/ca/load-der.crt
    //InputStream caInput = new BufferedInputStream(new FileInputStream(“load-der.crt”));
    InputStream caInput = context.getResources().openRawResource(R.raw.epay_wild_card);
    Certificate ca;
    try {
    ca = cf.generateCertificate(caInput);
    System.out.println(“ca=” + ((X509Certificate) ca).getSubjectDN());
    } finally {
    caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry(“ca”, ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance(“TLS”);
    context.init(null, tmf.getTrustManagers(), null);*/

    // Tell the URLConnection to use a SocketFactory from our SSLContext
    URL url = new URL(urlString);
    HttpURLConnection urlConnection =
    (HttpURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }

    String renameFile = reqEntity.getContentType().getName();

    Log.v(“”, “renameFile:”+renameFile);
    Log.v(“”, ” reqEntity.getContentType().getValue():”+ reqEntity.getContentType().getValue());

    urlConnection.setRequestProperty(“Accept-Charset”, “UTF-8”);
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.setRequestProperty(“Cache-Control”, “no-cache”);
    urlConnection.setRequestProperty(“Content-Type”, “multipart/form-data;boundary=” + boundary);
    // urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
    urlConnection.setRequestProperty(“file”, reqEntity.getContentType().getValue());

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparamsGoutam(String urlString,MultipartEntity reqEntity,String renameFile) {
    try {

    String attachmentName = “bitmap”;
    String attachmentFileName = “bitmap.bmp”;
    String crlf = “rn”;
    String twoHyphens = “–“;
    String boundary = “*****”;
    URL url = new URL(urlString);
    HttpURLConnection urlConnection =
    (HttpURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }
    Log.v(“”, “renameFile:”+renameFile);
    urlConnection.setRequestProperty(“Accept-Charset”, “UTF-8”);
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.setRequestProperty(“Cache-Control”, “no-cache”);
    //urlConnection.setRequestProperty(“Content-Type”, “multipart/form-data;boundary=” + boundary);
    urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
    urlConnection.setRequestProperty(“image”, renameFile);

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }
    return json;

    }

    }

  • Tarez Khan

    public String getSslDoinbgPostwithparams(String urlString,MultipartEntity reqEntity) {
    try {

    URL url = new URL(urlString);
    HttpsURLConnection urlConnection =
    (HttpsURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);

    ///////////////////////////////////////////////////////////////////////////////////////////////

    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparamsGoutam(String urlString,MultipartEntity reqEntity) {
    try {

    String attachmentName = “bitmap”;
    String attachmentFileName = “bitmap.bmp”;
    String crlf = “rn”;
    String twoHyphens = “–“;
    String boundary = “*****”;
    URL url = new URL(urlString);
    HttpURLConnection urlConnection =
    (HttpURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }

    String renameFile = reqEntity.getContentType().getName();

    Log.v(“”, “renameFile:”+renameFile);
    Log.v(“”, ” reqEntity.getContentType().getValue():”+ reqEntity.getContentType().getValue());

    urlConnection.setRequestProperty(“Accept-Charset”, “UTF-8”);
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.setRequestProperty(“Cache-Control”, “no-cache”);
    urlConnection.setRequestProperty(“Content-Type”, “multipart/form-data;boundary=” + boundary);
    // urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
    urlConnection.setRequestProperty(“file”, reqEntity.getContentType().getValue());

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();

    /////////////////////////////////////////////////////////////////////////////////////////////
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }

    // return JSON String
    //Log.i(“RETURN JSON: “,json);
    return json;

    }

    public String getSslDoinbgPostwithparamsGoutam(String urlString,MultipartEntity reqEntity,String renameFile) {
    try {

    String attachmentName = “bitmap”;
    String attachmentFileName = “bitmap.bmp”;
    String crlf = “rn”;
    String twoHyphens = “–“;
    String boundary = “*****”;
    URL url = new URL(urlString);
    HttpURLConnection urlConnection =
    (HttpURLConnection)url.openConnection();

    //urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setUseCaches(false);
    urlConnection.setDoInput(true);
    if(reqEntity==null)
    {
    Log.v(“”, “pagla main e fault”);
    }
    Log.v(“”, “renameFile:”+renameFile);
    urlConnection.setRequestProperty(“Accept-Charset”, “UTF-8”);
    urlConnection.setRequestProperty(“Connection”, “Keep-Alive”);
    urlConnection.addRequestProperty(“Content-length”, reqEntity.getContentLength()+””);
    urlConnection.setRequestProperty(“Cache-Control”, “no-cache”);
    //urlConnection.setRequestProperty(“Content-Type”, “multipart/form-data;boundary=” + boundary);
    urlConnection.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
    urlConnection.setRequestProperty(“image”, renameFile);

    OutputStream os = urlConnection.getOutputStream();
    reqEntity.writeTo(urlConnection.getOutputStream());
    os.close();
    urlConnection.connect();
    is = urlConnection.getInputStream();
    //copyInputStreamToOutputStream(in, System.out);

    }
    catch(Exception e) {
    e.printStackTrace();
    }

    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, “UTF-8”), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “n”);
    }

    Log.e(“Sesponse String”, sb.toString());

    is.close();

    json = sb.toString();

    } catch (Exception e) {
    Log.e(“Buffer Error”, “Error converting result ” + e.toString());

    }
    return json;

    }

    }

  • Tarez Khan

    import org.json.JSONObject;

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.util.Log;

    import com.marcel.headstrongperformance.httphandler.HttpHandler;

    public class GeneralAsynctask extends AsyncTask{

    private Context context;
    public ProgressDialog pdspinnerGeneral;
    public JSONObject jObj;
    private int noProgressDialog = 1;

    public GeneralAsynctask(Context context) {
    // TODO Auto-generated constructor stub
    this.context = context;
    }

    public GeneralAsynctask(Context context, int noProgressDialog) {
    // TODO Auto-generated constructor stub
    this.context = context;
    this.noProgressDialog = noProgressDialog;
    }

    @Override
    protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    if(noProgressDialog == 1) {
    //pdspinnerGeneral=new CustomProgressDialog(context);
    pdspinnerGeneral=new ProgressDialog(context);
    pdspinnerGeneral.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    pdspinnerGeneral.setMessage(“Please Wait!!”);
    pdspinnerGeneral.setCancelable(true);
    pdspinnerGeneral.show();
    }
    }

    @Override
    protected String doInBackground(String… params) {
    // TODO Auto-generated method stub
    Log.v(“GeneralUrl url —— >”, params[0]);
    HttpHandler json = new HttpHandler();
    String result = json.getJSONStringFromUrl(params[0]);
    int i = 0;

    if(this.isCancelled())
    {
    return null;
    }

    return result;
    }

    }

  • Sohail

    import org.json.JSONObject;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.util.Log;

    import com.marcel.headstrongperformance.httphandler.HttpHandler;
    public class GeneralAsynctask extends AsyncTask{
    private Context context;
    public ProgressDialog pdspinnerGeneral;
    public JSONObject jObj;
    private int noProgressDialog = 1;

    public GeneralAsynctask(Context context) {
    // TODO Auto-generated constructor stub
    this.context = context;
    }
    public GeneralAsynctask(Context context, int noProgressDialog) {
    // TODO Auto-generated constructor stub
    this.context = context;
    this.noProgressDialog = noProgressDialog;
    }
    @Override
    protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    if(noProgressDialog == 1) {
    //pdspinnerGeneral=new CustomProgressDialog(context);
    pdspinnerGeneral=new ProgressDialog(context);
    pdspinnerGeneral.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    pdspinnerGeneral.setMessage(“Please Wait!!”);
    pdspinnerGeneral.setCancelable(true);
    pdspinnerGeneral.show();
    }
    }
    @Override
    protected String doInBackground(String… params) {
    // TODO Auto-generated method stub
    Log.v(“GeneralUrl url —— >”, params[0]);
    HttpHandler json = new HttpHandler();
    String result = json.getJSONStringFromUrl(params[0]);
    int i = 0;

    if(this.isCancelled())
    {
    return null;
    }

    return result;
    }
    }

  • Ruksher

    //General Async Task
    import org.json.JSONObject;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.util.Log;

    import com.marcel.headstrongperformance.httphandler.HttpHandler;
    public class GeneralAsynctask extends AsyncTask{
    private Context context;
    public ProgressDialog pdspinnerGeneral;
    public JSONObject jObj;
    private int noProgressDialog = 1;

    public GeneralAsynctask(Context context) {
    // TODO Auto-generated constructor stub
    this.context = context;
    }
    public GeneralAsynctask(Context context, int noProgressDialog) {
    // TODO Auto-generated constructor stub
    this.context = context;
    this.noProgressDialog = noProgressDialog;
    }
    @Override
    protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    if(noProgressDialog == 1) {
    //pdspinnerGeneral=new CustomProgressDialog(context);
    pdspinnerGeneral=new ProgressDialog(context);
    pdspinnerGeneral.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    pdspinnerGeneral.setMessage(“Please Wait!!”);
    pdspinnerGeneral.setCancelable(true);
    pdspinnerGeneral.show();
    }
    }
    @Override
    protected String doInBackground(String… params) {
    // TODO Auto-generated method stub
    Log.v(“GeneralUrl url —— >”, params[0]);
    HttpHandler json = new HttpHandler();
    String result = json.getJSONStringFromUrl(params[0]);
    int i = 0;

    if(this.isCancelled())
    {
    return null;
    }

    return result;
    }
    }

  • Ruksher

    //General Async Task
    import org.json.JSONObject;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.util.Log;

    import com.marcel.headstrongperformance.httphandler.HttpHandler;
    public class GeneralAsynctask extends AsyncTask{
    private Context context;
    public ProgressDialog pdspinnerGeneral;
    public JSONObject jObj;
    private int noProgressDialog = 1;

    public GeneralAsynctask(Context context) {
    // TODO Auto-generated constructor stub
    this.context = context;
    }
    public GeneralAsynctask(Context context, int noProgressDialog) {
    // TODO Auto-generated constructor stub
    this.context = context;
    this.noProgressDialog = noProgressDialog;
    }
    @Override
    protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    if(noProgressDialog == 1) {
    //pdspinnerGeneral=new CustomProgressDialog(context);
    pdspinnerGeneral=new ProgressDialog(context);
    pdspinnerGeneral.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    pdspinnerGeneral.setMessage(“Please Wait!!”);
    pdspinnerGeneral.setCancelable(true);
    }
    }
    @Override
    protected String doInBackground(String… params) {
    // TODO Auto-generated method stub
    Log.v(“GeneralUrl url —— >”, params[0]);
    HttpHandler json = new HttpHandler();
    String result = json.getJSONStringFromUrl(params[0]);
    int i = 0;

    if(this.isCancelled())
    {
    return null;
    }

    return result;
    }
    }

  • Suresh Babu

    Hey ther ..i have a doubt on ..how to filter the items ..i mean to say how do i search the items being listed in list view above…i would like to use the search functionality for the list items …any suggestions …???

  • Hey ravi, i have some friend request for continuing your tutorial, missing step on click in listview to passing data from main to detail activity. When some people need it too… this is nice one https://github.com/CreatorB/AndroidVolleyImageListView i have added little code to pass some data to detail activity so when someone clicked one item in listview main their will go to detail item in detail activity, hope it can help many people, thanks for great tutorial ravi.

  • vinod

    your code is awesome. can we load the image and text from mysql database!!!!!!!!

  • Osnat Dafrush

    thank you for the wonderful post

    • You are welcome.

      • Sunusi Salisu Abubakar

        Please…Can we load the image and text from mysql database.

  • kushagra
  • Ho YuanHou

    This tutorial is cool, very useful, added the click item and open new activity in the APP and works great.
    This is newer than “Android Custom ListView with Image and Text using Volley”? or “Volly” is recommended?

    Thanks

  • vinod

    ravi sir, this tutorial is wonderful, can we get the songs in listview from mysql database using php. is there any possible.!!!!!!!

  • naveen

    Hello Ravi sir, I am doing an android project and everything is fine but I want to make very small change ,but I am unable to do that . I need your help sir . I am looking forward to your reply sir

  • Paolo Pini

    Very nice, but create and edit almost 14 files for a simple list, give me back my visual basic!.

  • Vikas

    Hi Ravi,
    How can you increase the heights of List View for the corresponding items in side scroll view?

    • You can add padding top and bottom in list item xml.

  • Jimmy

    Hello ravi
    jimmy here, I am new in android & I am working on eclipse.Amazing tutorials u have. thanks 4 that. now I use this custom listview programme & its working fine. but now my problem is I want to passed that selectd listview item’s image + text to next activity. so how can I do this.?? I am able to passed text but not image. here is my code for send text one activity to another one. Thank you in advance.

    list.setOnItemClickListener(new OnItemClickListener() {

    //FOR LISTONCLICK AND GO TO NEXT ACTIVITY
    @Override
    public void onItemClick(AdapterView arg0, View arg1,
    int arg2, long arg3) {
    // TODO Auto-generated method stub
    HashMap song = new HashMap();
    song = songsList.get(arg2);

    ti=song.get(CustomizedListView.KEY_TITLE);
    ar=song.get(CustomizedListView.KEY_ARTIST);

    Intent i= new Intent(CustomizedListView.this,Next.class);

    i.putExtra(“a”,ti);
    i.putExtra(“b”,ar);

    startActivity(i);

    }
    });

  • Jimmy

    hello.. no rply from your side..!!!

  • Arvind Sharma

    Easy to understand each and every single line… Wow, this is wonderful post.

  • Vrunda Vyas

    So many errors!!!

  • Luis Leitão

    thank you for the wonderful post

  • Luis Leitão

    for (int I = 0; I < nl.getLength(); i++)
    for (int i = 0; i < nl.getLength(); i++)

  • Jimmy

    hello
    all work wonderfully in android studio, but only image is not work properly. only show “no_image” in place of image

  • anmol gandhi

    Hello Sir,
    I am developing an android project and using a chatbot client in it which i built before.The problem is i am not able to place buttons in a layout, because as that layout is inflated again and again for every message so buttons are coming in every message i want to fix them for a particular message or when a condition occur then only the buttons should come, not in every message.
    It would be grateful if you can help with something, I have been googling for around 10 days but not got something fruitful.
    Thanks in advance.

  • Ashish Verma

    my app crashes everytime i start it .Any possible reasons

  • preeti agarwal

    How can do same thing using GridView?

  • Dharmesh Patel

    ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

    this line showing an error.
    how to solve it?

    • Dharmesh Patel

      ok, it is solved now.

  • Jayshree Bohra

    https://uploads.disquscdn.com/images/5a559984ec446603506eefac6cc564b68b84bcbdb26d60e04deab4990784c8f6.png

    sir
    me ek list view bna rha hu jisme image or text dono chahiy
    mere pass blank image hai jo list view me show ho
    or jo me text input kru wo image ke upar ki tarf show mtlb or image uske niche show like jese photo frame hota hai bich me image hoti h or charo tarf uski bordr
    is trah se listview possible h kya

    sample image niche di hai mene ese try kiya but text image k sath hi h wo ise use kiya to ye sahi se show nahi hua me chahta hu ki jo secnd imiage hai uske upr nam show ho https://uploads.disquscdn.com/images/7583a866c742942a978f5800d35819f2e5835a344e91cf222292c25aa55c3491.png

  • Sivanesh Ganesh

    whenever i open the app it crashes

  • Alka Uruskan

    Moruq yavaş ol ciğerimi söktün.