In this tutorial i will be demonstrating how to build simple android ListView. This article is about creating listview and launching new activity on selecting single list item.

Download Code

Below is screenshot of final output

Android List View

Let’s get start by creating a project in Eclipse IDE.

1. Create a new project by going to File ⇒ New Android Project. Fill all the details and name your activity as AndroidListViewActivity.
2. Once the project is created open your main activity java file (in this case AndroidListViewActivity.java) and extend the class from ListActivity.

public class AndroidListViewActivity extends ListActivity {

3. Now we need a string resources file to store all list item labels. So create an XML file under values folder and name it as list_data.xml and paste the following code.
( Right Click on res/values ⇒ New ⇒ Android XML File)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="adobe_products">
    	<item>Adobe After Effects</item>
    	<item>Adobe Bridge</item>
    	<item>Adobe Dreamweaver</item>
    	<item>Adobe Edge</item>
    	<item>Adobe Fireworks</item>
    	<item>Adobe Flash</item>
        <item>Adobe Photoshop</item>
        <item>Adobe Premiere</item>
        <item>Adobe Reader</item>
        <item>Adobe Illustrator</item>
    </string-array>
</resources>

4. In ListView each list item will be an xml layout, so we can customize each list item. Create an XML file under res/layout folder and name it as list_item.xml and type the following code. This xml layout will be single list item row.
( Right Click on res/layout ⇒ New ⇒ Android XML File)


<?xml version="1.0" encoding="utf-8"?>
<!--  Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="10dip"
        android:textSize="16dip"
        android:textStyle="bold" >
</TextView>

5. Now open your main activity java file (AndroidListViewActivity.java) and type the following code. In the following code i am importing all xml resources data and storing them in an Array. On the next step i am binding array to ListAdapter.

package com.androidhive.androidlistview;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class AndroidListViewActivity extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // storing string resources into Array
        String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
        
        // Binding resources Array to ListAdapter
        this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
        
    }
}

6. Now run your project you can see listview with list of array items. But on clicking single list item you can see no action. So we need to start new activity on selecting single list item.

Launching new Activity on selecting single list item

In my previous article i had explained how to switch between screens. Here i am going to show single list item details in new screen.

7. Now create new activity class under src folder. Right Click on src/package folder ⇒ New ⇒ Class and name it as SingleListItem. (SingleListItem.java)
8. Open your AndroidListViewActivity.java and modify the code to following. In the following code i am getting the selected list item string(product name) and sending it to new Activity.

package com.androidhive.androidlistview;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class AndroidListViewActivity extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // storing string resources into Array
        String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
        
        // Binding resources Array to ListAdapter
        this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
        
        ListView lv = getListView();

        // listening to single list item on click
        lv.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
              int position, long id) {
        	  
        	  // selected item 
        	  String product = ((TextView) view).getText().toString();
        	  
        	  // Launching new Activity on selecting single List Item
        	  Intent i = new Intent(getApplicationContext(), SingleListItem.class);
        	  // sending data to new activity
        	  i.putExtra("product", product);
        	  startActivity(i);
        	
          }
        });
    }
}

Now in new activity we need to display the received from listview activity.

9. Create a new xml file under res/layout and name it as single_list_item_view.xml and type the following code. This XML file will be layout for SingleListItem.java

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <TextView android:id="@+id/product_label"
  			android:layout_width="fill_parent"
  			android:layout_height="wrap_content"
  			android:textSize="25dip"
  			android:textStyle="bold"
  			android:padding="10dip"
  			android:textColor="#ffffff"/>    
</LinearLayout>

10. Now open your second activity file i.e SingleListItem.java and paste the following code.

package com.androidhive.androidlistview;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class SingleListItem extends Activity{
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.single_list_item_view);
        
        TextView txtProduct = (TextView) findViewById(R.id.product_label);
        
        Intent i = getIntent();
        // getting attached intent data
        String product = i.getStringExtra("product");
        // displaying selected product name
        txtProduct.setText(product);
        
	}
}

11. The final step is to add an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.androidhive.androidlistview"
      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=".AndroidListViewActivity"
                  android:label="Android List View">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <activity android:name=".SingleListItem"
        			android:label="Single Item Selected"></activity>
    </application>
</manifest>

12. Finally run your project by right clicking on your project folder ⇒ Run As ⇒ 1 Android Application.

android listview single list item selected
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.
  • Pingback: Android XML Parsing Tutorial | AndroidHive | Tutorials, Games, Apps, Tips()

  • Pingback: Android Tutorials | Explicit()

  • Pingback: Android JSON Parsing Tutorial | AndroidHive | Tutorials, Games, Apps, Tips()

  • Pingback: Android Building Audio Player Tutorial()

  • Pingback: Android Custom ListView with Image and Text | AndroidHive | Tutorials, Games, Apps, Tips()

  • Pingback: Android Combining Tab Layout and List View | Hackster's Lab()

  • Pingback: Android JSON Parsing Tutorial « Ekonugrha's Blog()

  • Ahmed IBRAHIM

    If you use a ListActivity/Fragment, the id for your ListView in your layout should be @android:id/list, so: In your whitelist_list.xml (whatever_activityname.xml) in your ListView change the id to android:id=”@android:id/list”

  • Ahmed IBRAHIM

    ListView listview = (ListView)findViewById(R.id.gridview);

    listview.setAdapter(new MyAdapter(this));
    /**to make the items clickable :
    * In this case, is an Activity object that you must send to the Intent constructor. By doing this, you are telling your Intent object that you want to open the ActivityToCall activity when clicking on an item.

    simply telling the intent that the currentActivity wants to open ActivityToCall activity
    * */
    listview.setOnItemClickListener(new OnItemClickListener()
    {
    public void onItemClick(AdapterView parent, View v, int position, long id)
    {
    Intent i = new Intent(CurentActivity.this, SecondActivity.class);

    Toast.makeText(MainActivity.this, “you clicke”+position, Toast.LENGTH_SHORT).show();

    startActivity(i);
    }
    });

    Note that : the above code will case all the items in the list to open the same activity. In order to make every item open its own activity, you will have to create a different activity for every item and modify your code to be something like this:

    Intent x = new Intent(MainActivity.this, SecondActivity.class);
    Intent y = new Intent(MainActivity.this, SecondActivity.class);
    Intent z = new Intent(MainActivity.this, SecondActivity.class);
    //… and so on

    if (position == 1){
    startActivity(x);
    }

    elseif (position == 2){
    startActivity(y);
    }

    elseif (position == 3){
    startActivity(z);
    }
    //….. and so on.

    • Zael

      Is there really no way to do this dynamically? (What if the list loses some items, gets others changed and gets some new ones from the users actions? ie. if/else is not sufficient.)

      • Ahmed IBRAHIM

        As far as I know (1 year dusty knowledge), the answer is no. I am sorry but you will have to search around to see if this changed or not.

  • joubin

    The app lunches okay, however, it crashes when I select one of the rows.

    any ideas?
    Here is how it happens: http://puu.sh/5ZZ3i.mp4
    PS: I was not able to use the provided “AndroidManifest” instead im using the one that was auto generatord:

  • Apurva Agrawal

    hey did you got d ansr bcs i am working on somthing same and i am facing the same problem pls help me..

  • apurva agrawal

    hey I have similar problm wat mia have so pls help me out with this.

    i am using tab host..and in the last tab, i want to display a simple lisIt view filled from array string in values,not database..so i did the first part of your tutorial which doesn’t do the work for me..and I don’t know why. the code is simple, and i don’t believe I made any mistakes. Do you maybe know if there is something special that I need to do because it’s tab host.

    Thanks in advance

  • Syrine92

    Hi

    I have this Error (“R cannot be resolved to a variable”) in these instructions:

    String[] adobe_products = getResources().getStringArray(R.array.adobe_products);

    this.setListAdapter(new ArrayAdapter(this, R.layout.list_item, R.id.label, adobe_products));

    Someone can help me please ?

  • Muhammad Shehzad Arshad Virk

    hi i have java server i want to get data from TCP java and want to show in listview please suggest me a nice tutorial thanks

  • george

    Hello. I need someone
    to develop a simple app. will use java , php and sql. please reply to george.celsie@gmail.com
    if you can help me. I will share the
    credits :). Thanks

    • Ganesh Ghodake

      Hello George. What kind of app you want to develop?

      • Muri

        Hi Ganesh,
        I also need help developing an app. I am new to java and I need to create a Listview which holds some amount of data. I did try create one for myself for it always crash. I think I am doing something wrong. So if you think you can help pls get in touch and we can talk more.

  • joaquindev

    Great tutorial. I´ve created a github repo with the code. It may be useful to someone: https://github.com/joaquindev/android-listview.git Keep up the good work!

  • arpit

    thanks for the tutorial,
    but how can i show scroll-able text after selecting an item from above list.
    For example:
    if i select “Adobe Edge” then a new screen should show me “It is a product of Adobe Company developed by…, , etc, etc,…..”.
    for doing this i can’t make new activity, because doing so will increase my .class files, and it is not a good programming practice in i have 50 items in a listview.
    So please suggest me the way with code, thank you.

  • Jabs

    While we extending Activity class in our coding and another side we extends arrayadapter class than how we get selected item from Listview?

  • Surabhi Sugandha

    i have dyanamic arraylist…now how should i connect it to next activity

    • seçkin

      I try your problem, listview1 in listview2 [tree model] than listview2 next activty

  • Ben Tong

    If I want to add a subtext under the text, how should i add it?

  • RIdwan F.

    hello ravi, this tutorial is work in my eclipse and i want to add a picture when i choose one of the list. can you tell me how it?
    i’m sorry if my english so bad.

  • nana

    hello ravi, i would like to disable the whole selection of a list item and make buttons and links inside the list item clickable

  • Prashanth

    Hi ravi, i have followed first step same as you mentioned but when i run the application i get a message the application has stopped unexpectedly

    • Please check your Logcat for errors

      • Prashanth

        thanks for reply sorry i only made mistake i solved it i ve one more doubt the main activity bar is not showing in 2.3.3 gingerbird(API 10) but it’s showing in jellybean

        • If you mean to say Action Bar, ActionBar was introduced in API11. In older versions it won’t be displayed. If you want to display in older versions, here is the help
          https://developer.android.com/training/basics/actionbar/setting-up.html

          • Prashanth

            Thank u very much any tutorial i can get data’s from excel or notepad

          • Rishil Bhatt

            How do I display simple action bar (having a textview) on List view page??

            Please help..

  • Dipak

    Hi , Thanks for awesome tutorial…..

    Question:

    At the bottom of your post you have attached two image files. In the first image file, “adobe fireworks” is highlighted.

    Do you know how I can change the color for my lisview item onClick to orange and then when user takes their finger off screen it goes back to default black colour?

    All the tutorial files online sugget writing code inside a drawable folder but I do not have a single drawable folder. I have 4 drawable folders i.e. drawable mdpi, drawable ldpi etc

    My code in Activity.java file looks like this:

    list.setOnItemClickListener(new OnItemClickListener(){

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

    }

    });

    Thank you for your help

    • You can create a new folder with the name ‘drawable’ and add the xml files. Use the gradient_bg.xml, gradient_bg_hover.xml, list_selector.xml files from below tutorial.
      http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/

      • Dipak

        Thank you very much….Can I please double check with you that the “drawable” folder most online tutorials speak about creating is to created under the “res” directory where the other drawable folders are?? pls kindly clarify for me….

        Thank you for the link to tutorial. My mp3 files are stores on SQL server database where I have stored the web links to the mp3.

        Thanks alot, i appreciate your time and am grateful for your response.

        • Yeah, drawable folder used to create under res folder when a new project is created when using older build tools(May be you are reading the articles written in those days). Now in recent build tools this folder is not creating by default. We have to create it manually whenever required.

  • Spike

    Very useful tutorial.
    How do I alter the code to add details of each product, for display on the second screen?

  • Aurino Jr

    Great tutorial

  • MuscleAche

    I have a very long list, how can i make it so that the list will only update when i scrolled till the end?

  • Eric Balcon

    first part doesn’t work for me while I try binding resources array to listAdapter: the setListAdapter causes an error

  • alvin

    I want have the list only appear when i type something in the search box,how would you do this?

  • alvin

    opps!!sorryy my question was for another page

  • Thanks a lot.this is very useful!

  • Nishant Jaisinghani

    Hi Ravi, Thank you for your tutorials they are really helpfull….i have created a basic listview app….all coding is done….but when i try to run the app its showing error ” app has stopped working”.

    thank you

  • Dear Sir, Thank you Great help.
    Ravi In addition to this tutorial I want to ask If I want to Write something or add some text or images in Adobe Fireworks Page/new screen. How can I do that? Thank you

  • Rishil Bhatt

    @ravi8x:disqus : Thank you for the tutorial….I would like to add the background image to the listview.

    I tried with lv.setBackgroundColor(R.drawable.sample);
    It’s not working.
    Could you help me out ?

    And Thanks again for the great work….Cheers

    • Nitesh

      in your xml write
      android:background=”@drawable/your-image”

  • Ajlinda Cerdaku

    Thank you very much for the Tutorial! I would like to add a stream, when i click on the item…
    can u help? Thank you

  • palsu

    when i click the item, in single_list_item.class not display the item, only blank layout
    helpv:)

    • khalil b

      It works Perfectly for me, Believe me If you follow this tuto step by step you can get it, may be Mr ravi tamada work with Holo dark, change the TextColor to Black like #000000 on single_list_item.xml and its done 😉

  • Guest

    God Bless you Mr.Ravi tamada you and your family and all person like you,

  • ali

    hi

    i have a big problem

    i use this site to make a search engine !

    but when activity start , occur Force Close.

    error log is :

    12-03 16:07:50.879: E/AndroidRuntime(4330): FATAL EXCEPTION: main
    12-03 16:07:50.879: E/AndroidRuntime(4330): Process: ir.korang.powerelectron.AndroidTrainingReference, PID: 4330
    12-03 16:07:50.879: E/AndroidRuntime(4330): java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.korang.powerelectron.AndroidTrainingReference/ir.korang.powerelectron.AndroidTrainingReference.Contact}: java.lang.NullPointerException
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread.access$800(ActivityThread.java:135)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.os.Handler.dispatchMessage(Handler.java:102)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.os.Looper.loop(Looper.java:136)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread.main(ActivityThread.java:5001)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at java.lang.reflect.Method.invokeNative(Native Method)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at java.lang.reflect.Method.invoke(Method.java:515)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at dalvik.system.NativeStart.main(Native Method)
    12-03 16:07:50.879: E/AndroidRuntime(4330): Caused by: java.lang.NullPointerException
    12-03 16:07:50.879: E/AndroidRuntime(4330): at ir.korang.powerelectron.AndroidTrainingReference.Contact.onCreate(Contact.java:52)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.Activity.performCreate(Activity.java:5231)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    12-03 16:07:50.879: E/AndroidRuntime(4330): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
    12-03 16:07:50.879: E/AndroidRuntime(4330): … 11 more
    12-03 16:07:58.475: I/Process(4330): Sending signal. PID: 4330 SIG: 9
    12-03 16:18:16.691: D/dalvikvm(4442): GC_FOR_ALLOC freed 45K, 3% free 3543K/3652K, paused 4ms, total 5ms
    12-03 16:18:16.691: I/dalvikvm-heap(4442): Grow heap (frag case) to 9.010MB for 5760012-byte allocation
    12-03 16:18:16.723: D/dalvikvm(4442): GC_FOR_ALLOC freed <1K, 2% free 9168K/9280K, paused 25ms, total 25ms
    12-03 16:18:16.947: D/(4442): HostConnection::get() New Host Connection established 0xb7f36090, tid 4442
    12-03 16:18:20.867: D/dalvikvm(4442): GC_FOR_ALLOC freed 5K, 1% free 9201K/9280K, paused 3ms, total 4ms
    12-03 16:18:20.875: I/dalvikvm-heap(4442): Grow heap (frag case) to 12.671MB for 3804812-byte allocation
    12-03 16:18:20.883: D/dalvikvm(4442): GC_FOR_ALLOC freed <1K, 1% free 12916K/12996K, paused 8ms, total 8ms
    12-03 16:18:21.011: D/dalvikvm(4442): GC_FOR_ALLOC freed 1K, 1% free 15952K/16036K, paused 3ms, total 3ms
    12-03 16:18:29.923: D/AndroidRuntime(4442): Shutting down VM
    12-03 16:18:29.923: W/dalvikvm(4442): threadid=1: thread exiting with uncaught exception (group=0xa4caeb20)
    12-03 16:18:29.931: E/AndroidRuntime(4442): FATAL EXCEPTION: main
    12-03 16:18:29.931: E/AndroidRuntime(4442): Process: ir.korang.powerelectron.AndroidTrainingReference, PID: 4442
    12-03 16:18:29.931: E/AndroidRuntime(4442): java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.korang.powerelectron.AndroidTrainingReference/ir.korang.powerelectron.AndroidTrainingReference.Search}: java.lang.NullPointerException
    12-03 16:18:29.931: E/AndroidRuntime(4442): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at android.app.ActivityThread.access$800(ActivityThread.java:135)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at android.os.Handler.dispatchMessage(Handler.java:102)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at android.os.Looper.loop(Looper.java:136)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at android.app.ActivityThread.main(ActivityThread.java:5001)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at java.lang.reflect.Method.invokeNative(Native Method)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at java.lang.reflect.Method.invoke(Method.java:515)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at dalvik.system.NativeStart.main(Native Method)
    12-03 16:18:29.931: E/AndroidRuntime(4442): Caused by: java.lang.NullPointerException
    12-03 16:18:29.931: E/AndroidRuntime(4442): at ir.korang.powerelectron.AndroidTrainingReference.Search.onCreate(Search.java:34)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at android.app.Activity.performCreate(Activity.java:5231)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    12-03 16:18:29.931: E/AndroidRuntime(4442): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
    12-03 16:18:29.931: E/AndroidRuntime(4442): … 11 more

    please help me.

    • kunal kumar

      TextView tv=(TextView)findViewById(R.id.label);

      define id of the textview
      and then
      tv.getText().toString();
      like this

      public void onItemClick(AdapterView parent, View view, int position,
      long id) {
      // TODO Auto-generated method stub
      @SuppressWarnings(“unused”)
      //TextView tv;
      TextView tv=(TextView)findViewById(R.id.label);
      String product=tv.getText().toString();
      String pos=””+position;

      Intent i=new Intent(getApplicationContext(),SingleListItem.class);
      i.putExtra(“product”,product);
      i.putExtra(“position”, pos);
      startActivity(i);
      }

  • Nam

    Thank you so much for the Tutorial, Mr.Ravi. It’s really helpful !

  • jabeelee

    how to put search engine in your code?

  • Mohammad Janbein

    Thank u ,but how to make every item open a text view.

  • mani

    i want play video list pls gie me a code

  • mani

    how can play number of video from my hard disk

  • Kira

    I can’t download your examples 🙁

    • Kira

      works now 🙂

  • Sam

    Hello sir,Thx for this great tutorial.I’m a beginner in android development.
    I have one que. sir,when i click on any item its showing only item name.What should i do if i want to show some text,paragraphs and images in specific item like Adobe After Effects.

  • namo

    hi rav. very nice tutorial. But please how do i make each item e.g adobe to launch a new activitys very very i when clicked? please it is very very urgent. thanks a lot sir.

  • stelios

    Hi Ravi. This is a amazing turtorial. Well done. Its very helpfull. I have one question. After copy paste and test this project its missing from my device the text on top “Android List view”. Why is that happening? Is something missing from the codes?

    Thank you very much

  • qudsia

    any one can help me please. i want to make list items clickable .but it doesn’t work.

  • विनय सोमवंशी

    how to create a seperate screen for every list item…..???

    • PrakashK Gowin

      Hi Vinay, Create a separate Activity or Fragment for loading each of your lists

  • Our Dear sir , same exact article we need But data will be from json array or mysql database

  • I think my question is not following by anyone

  • Please where can i find a tutorial on how to convert a wordpress website into an andriod app.. i don’t want to use appresser they are very expensive.

  • Hammayun Raza

    A-o-A everyone .,.,My question is “I want to create Listview with Image and text ,,but this tutorial is only for textview.please help me “?

  • tuan roy

    thank you sir
    your doing very good job
    its help me a lot
    thank you very much sir

  • manivel

    android interview question plz

  • manivel

    android fresher interview question plz

  • ratansingh

    Nice Tutorial
    Question :
    How insert web link in each List item

    • chaitanya

      ratansingh, you can initialize an intent for that respective and give permission in android_manifest.xml. IT works, if you need source code, then ping me back

    • Jonas Wahlberg

      you shouldn’t.

  • kavindu

    sir,
    i wanna to add image before each list name. but
    single_list_item_view.xml cannot easily edit. can u help me?

  • Vishal Kurapati

    Nice one but have a question
    sir, I just want to start a new activity instead of sending the data to next page? can you help me out?

    • Rohit Kumar

      In the listener method remove the putExtra Method
      Simply say
      startActivity(new Intent(this, YourActivityName.class));

  • Kartik Jain

    Thanxx for ur tutorial sir,
    a doubt – what if I have 5 different activities already defined and I just want the 5 list items to lead to these 5 diff activities? please do reply Sir.. its important

    • Rohit Kumar

      Hi Kartik,

      I believe the code in the AndroidListViewActivity class would change as following

      lv.setOnItemClickListener(new OnItemClickListener() {

      public void onItemClick(AdapterView parent, View view,

      int position, long id) {
      Intent i = null;

      if(position == 0)

      i = new Intent(getApplicationContext(), openClass0here.class);

      if(position == 1)

      i = new Intent(getApplicationContext(), openClass!here.class);

      startActivity(i);
      }

  • Venkatesh Nani

    Thanks for tutorial sir,
    i have a doubt sir single item have some details how can i include and display that sir

  • kazim kirmani

    Not Working 🙁

    • Jonas Wahlberg

      Very good.

  • jeevan

    can u plz share the information from where did you learn about android development
    is it from the internet books or anything

    secondly there is no options for starting as a fresher

    • Jonas Wahlberg

      No

  • Ehtesham Danish (Dex)

    Hello,
    Admin why every code of ours does not run in android studio.

  • Anne Fernandez

    i downloaded your code and everything works fine thanks
    but if i try to follow the guide, in the mainactivity there is a java file R.java and u dont mention it in the guide? anyone can help me?

    • R.java file will be generated each time you build the project. No need to worry about it.

  • fahmi saad

    Hi Ravi. based on this tutorial, can u show how to display two text in one column listview?

  • Pranav

    my intent is not working .I have created a new android activity. Is it necessary to declare in manifest file.

    • Jonas Wahlberg

      You should stop making android app :/

  • Pranaw Lal

    06-06 17:56:47.386: D/OpenGLRenderer(19117): Enabling debug mode 0

    06-06 17:56:50.116: D/AndroidRuntime(19117): Shutting down VM

    06-06 17:56:50.116: W/dalvikvm(19117): threadid=1: thread exiting with uncaught exception (group=0x41ed9c08)

    06-06 17:56:50.126: E/AndroidRuntime(19117): FATAL EXCEPTION: main

    06-06 17:56:50.126: E/AndroidRuntime(19117): Process: example.myapp, PID: 19117

    06-06 17:56:50.126: E/AndroidRuntime(19117): java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView

    06-06 17:56:50.126: E/AndroidRuntime(19117): at example.myapp.MainActivity$1.onItemClick(MainActivity.java:29)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at
    android.widget.AdapterView.performItemClick(AdapterView.java:308)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.widget.AbsListView.performItemClick(AbsListView.java:1510)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.widget.AbsListView$PerformClick.run(AbsListView.java:3472)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.widget.AbsListView$3.run(AbsListView.java:4835)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.os.Handler.handleCallback(Handler.java:733)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.os.Handler.dispatchMessage(Handler.java:95)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.os.Looper.loop(Looper.java:146)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.app.ActivityThread.main(ActivityThread.java:5511)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at java.lang.reflect.Method.invokeNative(Native Method)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at java.lang.reflect.Method.invoke(Method.java:515)06-06 17:56:47.386: D/OpenGLRenderer(19117): Enabling debug mode 0

    06-06 17:56:50.116: D/AndroidRuntime(19117): Shutting down VM

    06-06 17:56:50.116: W/dalvikvm(19117): threadid=1: thread exiting with uncaught exception (group=0x41ed9c08)

    06-06 17:56:50.126: E/AndroidRuntime(19117): FATAL EXCEPTION: main

    06-06 17:56:50.126: E/AndroidRuntime(19117): Process: example.myapp, PID: 19117

    06-06 17:56:50.126: E/AndroidRuntime(19117): java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView

    06-06 17:56:50.126: E/AndroidRuntime(19117): at example.myapp.MainActivity$1.onItemClick(MainActivity.java:29)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.widget.AdapterView.performItemClick(AdapterView.java:308)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.widget.AbsListView.performItemClick(AbsListView.java:1510)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.widget.AbsListView$PerformClick.run(AbsListView.java:3472)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.widget.AbsListView$3.run(AbsListView.java:4835)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.os.Handler.handleCallback(Handler.java:733)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.os.Handler.dispatchMessage(Handler.java:95)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.os.Looper.loop(Looper.java:146)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at android.app.ActivityThread.main(ActivityThread.java:5511)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at java.lang.reflect.Method.invokeNative(Native Method)

    06-06 17:56:50.126: E/AndroidRuntime(19117): at java.lang.reflect.Method.invoke(Method.java:515)
    my application stops when i click on list item

  • Rachana Mk

    how to implement this code in sliding menu ie,http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/ for this application please guide me to implement

  • Tang Weiming

    hi, MR.Ravi, thanks for the tutorial, one question how can i do this when i click the listview item it will show in another listview activity

  • Krutarth Doshi

    https://uploads.disquscdn.com/images/ca0bcba0fa9f6f30f851092cf6f23f8a12cb94667dfe9c9f60a2857fd8ba0532.jpg Hello Mr. Ravi I am getting the error as shown in photo.. What should I do?

    • Remove onAttach() method from your fragment.

  • How can i start list-view as my second screen? I tried as other second screen but list-view is not working

  • pgdroid

    Nice tuts it really helped me. 🙂

  • Adrian

    Error:Unsupported type ‘TextView’
    Kindly help

    • Jonas Wahlberg

      hahahaha xD
      you should stop making apps xD

  • Marija Beatriz Tuble

    hello does this only work for eclipse? or can i use android studio to do the codings too?

    • Mujeebulla Rahaman

      Hi Marija, yes you can also use in Android Studio.

      • Marija Beatriz Tuble

        Hello thank you so much for the speedy reply. My listview is actually a refreshing one as it’s synced to the phone’s inbox. So everytime a new message comes, the listview gets updated. Do you by any chance know how to go about this? Cuz for this example, its a fixed listview. So im not sure how to store the contents of my listview.

        • Mujeebulla Rahaman

          Hi Marija

          Broadcast Receiver, this is dependent on the apps installed on the phone
          but you can give your app priority for listening to messages. Although,
          when a notification is shown, the message won’t be in the SMS Database
          yet, so you will need to use abortBroadcast() to stop other apps being
          notified. See example below:

          public class MessageReceiver extends BroadcastReceiver {
          public void onReceive(Context context, Intent intent) {
          Bundle pudsBundle = intent.getExtras();
          Object[] pdus = (Object[]) pudsBundle.get(“pdus”);
          SmsMessage messages =SmsMessage.createFromPdu((byte[]) pdus[0]);
          Log.i(TAG, messages.getMessageBody());
          if(messages.getMessageBody().contains(“Hi”)) {
          abortBroadcast();

          Update or add Your new Messages to ListAdapter then notify

          mListAdapter.notifyDataSetChanged(); //It Updated your list.

          }
          }

          And you would need to declare the receiver in the manifest, like so:

          Finally, make sure you have the permission to RECEIVE_SMS in the manifest,

          Second : Updating List Adapter.
          mListAdapter.notifyDataSetChanged();

          Finally iam week in communication, please forgive me.

          • Marija Beatriz Tuble

            Hello I actually already made it work the part about syncing my inbox to the listview of the app. Now my problem is how do store the contents of my listview in the xml (step no. 3). Im so sorrr if I have a lot of qns. I am quite new to android studio and this is for my final year project in school. Im kind of in a rush to finish this project as I have a deadline soon. Thank you so much for your help though, I really appreciate it.

          • Mujeebulla Rahaman

            Hi marija,

            Two options you can store messages in sqlite database, or you can write XML data to texfile and store.

            This simple.

          • Marija Beatriz Tuble

            Yeah i heard that i need to use sqlite database. The thing is this android studio is my plan B cuz my plan a didnt work. My supervisor asked me to change and learn android studio and develop this app in such a short time. Ive been learning and trying my luck with forums and video tutorials and so far ive managed to do it but for this part im stuck. My deadline is this jan 5 and im nowhere near to finishing my app. Androis studio is very new to me and im not very good at my programming.

          • Mujeebulla Rahaman

            Hi marija,
            OK then tell me u need help for textfile or SQL database.

            I will try to help.

          • Marija Beatriz Tuble

            I think ill use SQL database. Right now i dont have any code for that. Right now the only thing my app can do is syncing and receiving msgs from the phone inbox. Then when i click the listview it goes to another page. For the pictures attached, i need the coordinates from the listview to be passed to the next activity below the label “coordinates:” https://uploads.disquscdn.com/images/9000ee4125fac8942a3447a9bd117e0fda4592ffffb61e2aa086d1d0339e4d67.jpg https://uploads.disquscdn.com/images/94ad58e76008e83a304cfe95c37cd5fa8ac403d18d4f1afd0d70cf559220a928.jpg

          • Marija Beatriz Tuble

            these are my codes for my main activity

            package com.example.marijabeatriz.fetchinbox4;

            import android.content.Intent;
            import android.support.v7.app.AppCompatActivity;
            import android.os.Bundle;
            import android.app.Activity;
            import android.content.ContentResolver;
            import android.database.Cursor;
            import android.net.Uri;
            import android.os.Bundle;
            import android.view.View;
            import android.view.View.OnClickListener;
            import android.widget.AdapterView;
            import android.widget.Button;
            import android.widget.ListView;
            import android.widget.SimpleCursorAdapter;
            import android.widget.TextView;

            public class MainActivity extends AppCompatActivity implements OnClickListener {

            // GUI Widget
            Button btnSent, getSmsButton, btnDraft;
            TextView lblMsg, lblNumber;
            ListView messageListView;

            // Cursor Adapter
            SimpleCursorAdapter adapter;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            // Init GUI Widget
            getSmsButton = (Button) findViewById(R.id.getSmsButton);
            getSmsButton.setOnClickListener(this);

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

            messageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {

            Intent GetCoordinates = new Intent(MainActivity.this, GetCoordinates.class);
            startActivity(GetCoordinates);
            }
            });

            }

            @Override
            public void onClick(View v) {

            if (v == getSmsButton) {

            // Create Inbox box URI
            Uri inboxURI = Uri.parse(“content://sms/inbox”);

            // List required columns
            String[] reqCols = new String[] { “_id”, “address”, “body” };

            // Get Content Resolver object, which will deal with Content Provider
            ContentResolver cr = getContentResolver();

            // Fetch Inbox SMS Message from Built-in Content Provider
            Cursor c = cr.query(inboxURI, reqCols, null, null, null);

            // Attached Cursor with adapter and display in listview
            adapter = new SimpleCursorAdapter(this, R.layout.row, c,
            new String[] { “body”, “address” }, new int[] {
            R.id.lblMsg, R.id.lblNumber });
            messageListView.setAdapter(adapter);

            }
            }

          • Mujeebulla Rahaman

            Hi Marina

            OK then send me wt r the fields u need in database I will send u the code that’s very simple.

          • Marija Beatriz Tuble

            hello what are fields? im sorry… i want to store the coordinates in the database… like you see he picture for my first activity below the phone number there;s numbers like “1.335060….” i want to store those

          • Mujeebulla Rahaman

            Hi marina

            Database fields required, example.
            Table Name.

            Record_I’d, Phone_No, Longitude, Latitude, Message

            Any more database fields required.

          • Marija Beatriz Tuble

            i think thats about it… for the table name it can just be coordinates… or maybe you can just help me to put whatever name you think is good and ill just refer from it and change… thank you so much i really appreciate your help

          • Mujeebulla Rahaman

            Hi Marija

            OK I will send u the code. Wait for 2hrs iam out now, I will get back to work.

          • Marija Beatriz Tuble

            no worries thank you so much, youre doing me such a huge favor… thank you thank you… i will get back to you asap.. its late in my country and im gonna go get some sleep first, ill check again first thing in the morning

          • Mujeebulla Rahaman

            Hi Marija

            r u there how can i send you the java files, can u send me ur mail id.

          • Marija Beatriz Tuble

            Hello my email is marija_beatriz@live.com

          • Mujeebulla Rahaman

            Ok then, i am uploading the source code to my server you can download from it, and follow the instructions.

            http://www.techiworld.com/Source.zip

            click the above link to download the source code.

          • Marija Beatriz Tuble

            Hello these codes will help to store the coordinates inside the database and pass it to the next activity and display it there right?

          • Marija Beatriz Tuble

            i have already put your codes with mine… now i need to fetch and display the longitude and latitude from the database to my next activity… i need to do coding for my second activity also? You put latitude and longitude right, but Can you show me an example of how to store a set of latitude and longitude and retrieve it from the database in a new activity…

  • Ashish

    Hello , I am Use This code , But I am Use List view In The Place Of Text View . I am Not Getting Result . I have Got a Proble Please Share me the Problem Solution.

    Code are Given Below:
    String item = ((TextView) view).getText().toString();
    i.putExtra(“item”,item);

    • Jonas Wahlberg

      problem is your english xD

  • Sandeep Genno

    How to change the typeface of font on above Tutorial Thank you

  • code bug

    Hello sir i wanted to ask what all changes we hv to do if we r making it in a fragment coz my app is crasing
    plzz do reply its urgent!!!!!

  • Suvashish Das

    Hi, i have 2 listview in same activity. i want to change 2nd listview item as per 1st listview value.

  • Venkatesh Kardas

    can anyone suggest me how to convert user entered data into excel format

  • yilber esteban flor orozco

    How to add each item, in a new ListView, something like list of favorites?