Showing posts with label Listview. Show all posts
Showing posts with label Listview. Show all posts

Android Wear: How to send data from Android Wear to Mobile Device ?

Android Wear or Let say Smart Watches are new and trending technology. Android apps are updating and they all comes with Android wear support. if you want it is in your app you can find simple Helloworld wear app tutorials easily on Google. but what if you want to explore it more let say you want to display a List view in android wear or get some kind of input from android wear app. so these tutorial is for you. In this tutorial i have created simple list in android wear app in which user click on list item and an app in mobile device gets open. for example you want to display list of songs in android wear app and on the click of that you want to change song in your device or let say you can display to do list on android wear and on the click of list item you can open to do item details inside your mobile app. this list can be infinite and its totally depends on you and apps in android.

Android Wear sample


Steps

Step - 1
First of let i start with adding a android wear module in development. If you have already added android wear module in you app you can skip this step. To add right click on your app root folder (name of your app folder) and go to New > Module. Select Android Wear Module and click on next. Give same name in Application name (Mobile app name) and in Module Name write wear. so you can differentiate them. Make sure you give same package name also. because when you send some data through mobile app or wear app MessageApi will check for the same package and pass that data. so if you give different name you won't be able to send or receive data. On the next screen select Blank Wear Activity and on the next screen give proper name to it.

Note - Above steps are for Android studio wizard. Sorry for eclipse developers (Please migrate to AS)

Step - 2
So our android wear module is added. I hope you have no issue in above steps. in the main activity or launcher activity i have created a List (basically list of my tutorials). For learning purpose you can start with same and after that you can change it is as you want. so put below code in appropriate layout files.

wear/layout/activity_list.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.wearable.view.WatchViewStub 
   xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/watch_view_stub"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#e4e5e5"
    app:rectLayout="@layout/rect_activity_list"
    app:roundLayout="@layout/round_activity_list"
    tools:context=".ListActivity"
    tools:deviceIds="wear">

</android.support.wearable.view.WatchViewStub>



wear/layout/rect_activity_list.xml & wear/layout/round_activity_list.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.wearable.view.BoxInsetLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".ListActivity"
    tools:deviceIds="wear_round">

        <android.support.wearable.view.WearableListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:overScrollMode="never" />

        <TextView
            android:id="@+id/tv_header"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_gravity="top|center"
            android:textSize="30sp"
            android:layout_marginTop="10dp"
            android:textColor="#52bf90"
            android:fontFamily="sans-serif-light"
            android:text="@string/app_name"/>

</android.support.wearable.view.BoxInsetLayout>




Step - 3
List layout is done in Step -2. now let's jump to coding part where i have initialize WearableListView with Array adapter. Using GoogleApiClient i have checked if there is a connection to a android wear from an app or not. we can get all connected nodes or devices using Wearable.NodeApi.getConnectedNodes method. check below code and make sure you understand or go through it for one time so you know what is actually going on. otherwise you will get confused.

wear/java/ListActivity.java

package com.androprogrammer.tutorials;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.support.wearable.view.WearableListView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;

import java.util.ArrayList;

public class ListActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,WearableListView.ClickListener {

    private WearableListView mListView;

    private ArrayList<String> listItems;

    Node mNode; // the connected device to send the message to
    GoogleApiClient mGoogleApiClient;
    private boolean mResolvingError=false;

    public static String SERVICE_CALLED_WEAR = "WearListClicked";
    public static String TAG = "WearListActivity";


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

        //Connect the GoogleApiClient
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Wearable.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        initializeListItems();
        final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
        stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
            @Override
            public void onLayoutInflated(WatchViewStub stub) {
                mListView = (WearableListView) stub.findViewById(R.id.listView1);

                mListView.setAdapter(new MyAdapter(ListActivity.this, listItems));
                mListView.setClickListener(ListActivity.this);

            }
        });
    }

    private void initializeListItems() {

        listItems = new ArrayList<>();
        listItems.add("Async File Read");
        listItems.add("Battery Status");
        listItems.add("Volume Setting");
        listItems.add("Frame Animation");
        listItems.add("Video Player");
        listItems.add("Circular Image View");
        listItems.add("Track User Location");
        listItems.add("Take Image");
        listItems.add("Image Grid View");
        listItems.add("Image Switcher");
        listItems.add("Tabs with Toolbar");
        listItems.add("Icon Tabs with Toolbar");
        listItems.add("Push Notification");


    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!mResolvingError) {
            mGoogleApiClient.connect();
        }
    }

    /**
     * Resolve the node = the connected device to send the message to
     */
    private void resolveNode() {

        Wearable.NodeApi.getConnectedNodes(mGoogleApiClient)
                .setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
                    @Override
                    public void onResult(NodeApi.GetConnectedNodesResult nodes) {
                        for (Node node : nodes.getNodes()) {
                    mNode = node;
                }
            }
        });
    }

    @Override
    public void onConnected(Bundle bundle) {
        resolveNode();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    /**
     * Send message to mobile handheld
     */
    private void sendMessage(String Key) {

        if (mNode != null && mGoogleApiClient!= null && mGoogleApiClient.isConnected()) {
            Log.d(TAG, "-- " + mGoogleApiClient.isConnected());
            Wearable.MessageApi.sendMessage(
                    mGoogleApiClient, mNode.getId(), SERVICE_CALLED_WEAR + "--" + Key, null).setResultCallback(

                    new ResultCallback<MessageApi.SendMessageResult>() {
                        @Override
                        public void onResult(MessageApi.SendMessageResult sendMessageResult) {

                            if (!sendMessageResult.getStatus().isSuccess()) {
                                Log.e(TAG, "Failed to send message with status code: "
                                        + sendMessageResult.getStatus().getStatusCode());
                            }
                        }
                    }
            );
        }

    }

    @Override
    public void onClick(WearableListView.ViewHolder viewHolder) {
        TextView view = (TextView) viewHolder.itemView.findViewById(R.id.row_tv_name);
        String Key = view.getText().toString();
        Log.d(TAG, Key);
        sendMessage(Key);
    }

    @Override
    public void onTopEmptyRegionClick() {
        Toast.makeText(this, "You tapped on Top empty area", Toast.LENGTH_SHORT).show();
    }


    private class MyAdapter extends WearableListView.Adapter {
        private final LayoutInflater mInflater;
        private ArrayList<String> data;

        private MyAdapter(Context context, ArrayList<String> listItems) {
            mInflater = LayoutInflater.from(context);
            data = listItems;
        }

        @Override
        public WearableListView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new WearableListView.ViewHolder(
                    mInflater.inflate(R.layout.row_wear_list, null));
        }

        @Override
        public void onBindViewHolder(WearableListView.ViewHolder holder, int position) {
            TextView view = (TextView) holder.itemView.findViewById(R.id.row_tv_name);
            view.setText(data.get(position));
            holder.itemView.setTag(position);
        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }
}



wear/layout/row_wear_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:orientation="horizontal"
    android:padding="8dp"
    android:gravity="center">

    <TextView
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:textStyle="bold"
        android:ellipsize="end"
        android:maxEms="15"
        android:padding="10dp"
        android:ems="15"
        android:background="@android:color/white"
        android:textColor="@android:color/black"
        android:fontFamily="sans-serif-condensed-light"
        android:gravity="center"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:textSize="16sp"
        android:id="@+id/row_tv_name" />

</LinearLayout>


wear/AndroidManifest.xml
<meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />


Please add above lines of code in manifest file of wear module. because we are using google play service to communicate. otherwise it will give error.

Step - 4
Now android wear module is ready. you can run it separately on emulator and check it. now we require a bridge which can pass android wear message to android mobile app. so when user click on list item in android wear a service get some sort of message and on the basis of that message we start appropriate activity. Using WearableListenerService we will create service which will do same for our app.

mobile/java/WearListCallListenerService.java

package com.androprogrammer.tutorials.services;

import android.content.Intent;
import android.util.Log;

import com.androprogrammer.tutorials.activities.Listactivity;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.WearableListenerService;

/**
 * Created by Wasim on 08-05-2015.
 */
public class WearListCallListenerService extends WearableListenerService {

    public static String SERVICE_CALLED_WEAR = "WearListClicked";


    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
        super.onMessageReceived(messageEvent);

        String event = messageEvent.getPath();

        Log.d("Listclicked", event);

        String [] message = event.split("--");

        if (message[0].equals(SERVICE_CALLED_WEAR)) {

            startActivity(new Intent((Intent) Listactivity.getInstance().tutorials.get(message[1]))
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        }
    }
}



Step - 5
In Mobile app put below code to register your service.

mobile/AndroidManifest.xml

<service android:name=".services.WearListCallListenerService">
            <intent-filter>
                <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
            </intent-filter>
        </service>


That's it...
Now run wear module in android wear emulator and mobile module in device. make sure you are connected. I hope you understand the full tutorial. you can get full source code from my Github repo. if you find it helpful please share this tutorial.

Keep coding...

Data Adapters in android

Adapters are like magician. In android if you want to display block of data in List view or Grid view or any other android widget you have to implement some kind of adapter class in your application. It can be Base adapter or Array adapter or any. So in this class you perform some ugly or magical work. Like creating view for each row of list or grid and then assign data and even you can write some business logic also in that adapter class.

Types of adapters in android are as follows
  1. Base Adapter
  2. Simple Adapter 
  3. Array Adapter
  4. Simple Cursor Adapter
  5. List Adapter
  6. Cursor Adapter
  7. Resource Cursor Adapter
  8. Spinner Adapter
  9. Simple Cursor Tree Adapter
  10. Cursor Tree Adapter
  11. Header View List Adapter
  12. Wrapper List Adapter

Well some of them are totally new for me and i hope for you also. Because they are less known and less used by developers. They consist lots of complexity but for different uses it may help you. just check it out in android documentation. These are the list of adapters till android v 4.4 Kitkat. it may happen android team will add new adapters in next version of android named as android L or in future . So from above all the adapters which are mostly used in android and easy to implement. 

Base Adapter
As name suggest it is base class for all adapter class and interface. Base adapter is abstract class.Base Adapter is a very generic adapter that allows you to do pretty much whatever you want. However, you have to do a bit more coding yourself to get it working.using this class you can define custom view for each row and also you can perform task on object click event also. getView method is basically implemented in this class and you can override it and define your layout in this method. using this class you can bind data with list view and spinner. this is the most used adapter class for binding data in any view. even you can write business logic also in this class. in base adapter class you have to implement even getcount method because on the basis of that adapter will call getview method. Read more

Simple Adapter
when you want to bind static data set to list view you can use simple adapter. you can define xml layout for each row and data can be in array list or in map. each row represent single record of array list. simple adapter class extends Base Adapter class so you have all those methods so you can override even in simple adapter class. data binding is done using view Binder method. Read more

Array Adapter
Second is Array Adapter. Array Adapter is a class which can work with array of data. you need to override only getview method. you can override getview method with different types of parameter. but the main use of array adapter when you want to display a single text view in each row of list. then it is batter to use this adapter. you have to pass data layout or resource file id and text view id in getview method. you can even use image view and other object but for that Base adapter class is perfect. Read more

Simple Cursor Adapter
If your application requires data from local database then you can use simple cursor adapter class to bind data. this is class like simple adapter if you require to display data from database in listview then it is best practice to extend this class. it also works as simple adapter class. different between both is in simple adapter data is in array list and static and in this class data is in cursor and comes from database. data binding in this also done using view Binder method. Read more

Cursor Adapter
if you want to implement this class make sure your table consist one column named as "_id". because cursor traverse data using this column in cursor adapter. and if you want to perform some filtration or swipe cursor then only use this class. it is quite complex so if you are new in android don't try this try some other adapters. one more thing in cursor adapter you have to implement or override new view and bind view method. in which you can define view for each row and bind data also. cursor view already implement getview method so it is better to not to override this method. Read more

Simple Cursor Tree Adapter
last but not list simple cursor tree adapter is useful when you have nested view like nested list view or grid view.  the class provide you method to define layout for child view or group view so if you have data from database and even it is complex (two / three table data) then you can use this adapter class to display data in nested view. Read more

Well there are other adapters also in the list but they are less used and i just covered few details of each adapter class you can find more details about it. click on read more and it will redirect you to documentation where you can find more about it. one more thing, in android View Holder pattern is most famous and use full pattern of saving row layout before it get recycled by garbage collector. so before implementing look after this pattern.

I hope these details help you to understand about adapters. and if it is helpful to you please share this article with your friends. and if you have any thing to say about this article write down in below comment box. new things and suggestion always welcome.
Keep coding...

Add Searching in List View.

Search Functionality the best thing we use to find information fast and easy. well in your application if you have long list of information and you want provide search function in your application. it may affect your application credits. user get bored after so much scroll in list. So to add search functionality you have two option One is using Action bar search functionality and Second is alert box that ask for query and then you search on the basis of that. one main thing about this Search function is you have to use in built layout of list view in order to work it (My opinion). 

Steps
  • Create New Application and give name it ListViewSearch and Do next. 
    • minSdkVersion="17” 
    • targetSdkVersion="17". 
  • Give activity name – Main.java and main.xml. 
  • Go to main.xml and paste the below code.
Main.xml



    
    



Now Go to menu > main.xml file and put below code in it.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        app:showAsAction="always|collapseActionView"
        android:icon="@android:drawable/ic_menu_search"
        android:id="@+id/menu_item_search"
        android:actionViewClass="android.widget.SearchView"
        android:title="Search"
        android:iconifiedByDefault="true"/>
</menu>

Action bar was introduce in Android 3.0 version so if you are creating app that works on gingerbread and all version you have to add search view above list view or you can use action bar sherlock. you can check out my tutorial on action bar sherlock for more.now go to your class file and put below code.
Main.java

package com.androprogrammer.app3;

import android.os.Bundle;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.text.TextUtils;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

public class Main extends Activity implements OnQueryTextListener{

 ListView lv;
 CustomAdapter adapter;
 String temp[] = {"Gplus","Facebook","Instagram","Linkdin","Pintrest","Twitter","Snapchat","Skype"};
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  lv = (ListView) findViewById(R.id.listView1);
  lv.setAdapter(new ArrayAdapter < string >(getApplicationContext(),android.R.layout.simple_list_item_1,temp));
  lv.setTextFilterEnabled(true);
  
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
        SearchView searchView = (SearchView) menu.findItem(R.id.menu_item_search).getActionView();

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setSubmitButtonEnabled(true);
        searchView.setOnQueryTextListener(this);

        return super.onCreateOptionsMenu(menu);
 }

 @Override
 public boolean onQueryTextChange(String newText)
 {
  // this is your adapter that will be filtered
      if (TextUtils.isEmpty(newText))
      {
            lv.clearTextFilter();
        }
      else
      {
            lv.setFilterText(newText.toString());
        }
        
      return true;
 }

 @Override
 public boolean onQueryTextSubmit(String query) {
  // TODO Auto-generated method stub
  return false;
 }

}

Screen Shot

As you can see your query display in below Box and it also filter your list view adapter. that's it now run your application and see it works with your tweak or not. if you have any query or problem with it post it in below comment box. i have solved many problems that are still on stack overflow and many forums. you can suggest or share this link with your friends.
if you like the blog subscribe to our blog or like us on facebook or Google+.
Keep coding..

Download Code

List view with Check box Using Custom Adapter class

List view is Great and useful component of Android Application. I have already tech you Simple List view with custom adapter class. you can learn about Custom Adapter Class from that tutorial. you can combine many components like Text View , Check Box, Image View, Image Button etc. and can make List view as you require. so Today i am gone create List view with custom layout which consist of Text view and Check box.

There is an issue with list view when you are using check box within list view is that the checked state of check box will not maintain by android because when you scroll list view it will generate new view for each row using getView() method and garbage collector will remove all above View to make space so check box state will also destroy or garbage by garbage collector. but don't worry i have solved that problem and make this tutorial for you so you can use it.
Main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">


    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:divider="#000"
        android:dividerHeight="0.8dp"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Check Selected"/>

</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp"
        android:singleLine="true"
        android:ellipsize="end"
        android:maxLines="1"
        android:padding="5dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignParentRight="true"
        android:layout_marginRight="15dp"
        android:focusable="false"
        android:focusableInTouchMode="false"/>

</RelativeLayout>

Main.java
package com.androprogrammer.app1;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity implements OnItemClickListener{

 ListView apps;
 PackageManager packageManager;
 ArrayList <String> checkedValue;
 Button bt1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bt1 = (Button) findViewById(R.id.button1);
        apps = (ListView) findViewById(R.id.listView1);
        packageManager = getPackageManager();
  final List <PackageInfo> packageList = packageManager
    .getInstalledPackages(PackageManager.GET_META_DATA); // all apps in the phone
  final List <PackageInfo> packageList1 = packageManager
    .getInstalledPackages(0);

    try {
      packageList1.clear();
      for (int n = 0; n < packageList.size(); n++) 
      {

       PackageInfo PackInfo = packageList.get(n);
       if (((PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true) 
        //check weather it is system app or user installed app
       {
        try 
        {
         
          packageList1.add(packageList.get(n)); // add in 2nd list if it is user installed app 
           Collections.sort(packageList1,new Comparator <PackageInfo>() 
             // this will sort App list on the basis of app name
           {
            public int compare(PackageInfo o1,PackageInfo o2) 
            {
             return o1.applicationInfo.loadLabel(getPackageManager()).toString()
               .compareToIgnoreCase(o2.applicationInfo.loadLabel(getPackageManager())
                   .toString());// compare and return sorted packagelist.
            }
           });
           
         
        } catch (NullPointerException e) {
         e.printStackTrace();
        }
       }
      }
     } catch (Exception e) {
      e.printStackTrace();
     }
    Listadapter Adapter = new Listadapter(this,packageList1, packageManager);
    apps.setAdapter(Adapter);
    apps.setOnItemClickListener(this);
    bt1.setOnClickListener(new View.OnClickListener() {
     
     @Override
     public void onClick(View v) {
      // TODO Auto-generated method stub
      Toast.makeText(Main.this,"" + checkedValue,Toast.LENGTH_LONG).show();
     }
    });
        
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


 @Override
 public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
  // TODO Auto-generated method stub
  CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);
  TextView tv = (TextView) v.findViewById(R.id.textView1);
  cb.performClick();
  if (cb.isChecked()) {
   
   checkedValue.add(tv.getText().toString());
  } else if (!cb.isChecked()) {
   checkedValue.remove(tv.getText().toString());
  }

   
  
 }
    
}
Listadapter.java
package com.androprogrammer.app1;

import java.util.List;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

public class Listadapter extends BaseAdapter{

 List <PackageInfo> packageList;
 Activity context;
 PackageManager packageManager;
 boolean[] itemChecked;

 public Listadapter(Activity context, List <PackageInfo> packageList,
   PackageManager packageManager) {
  super();
  this.context = context;
  this.packageList = packageList;
  this.packageManager = packageManager;
  itemChecked = new boolean[packageList.size()];
 }

 private class ViewHolder {
  TextView apkName;
  CheckBox ck1;
 }

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

 public Object getItem(int position) {
  return packageList.get(position);
 }

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

 @Override
 public View getView(final int position, View convertView, ViewGroup parent) {
  final ViewHolder holder;
  
  LayoutInflater inflater = context.getLayoutInflater();

  if (convertView == null) {
   convertView = inflater.inflate(R.layout.list_item, null);
   holder = new ViewHolder();

   holder.apkName = (TextView) convertView
     .findViewById(R.id.textView1);
   holder.ck1 = (CheckBox) convertView
     .findViewById(R.id.checkBox1);

   convertView.setTag(holder);

  } else {
   
   holder = (ViewHolder) convertView.getTag();
  }

  PackageInfo packageInfo = (PackageInfo) getItem(position);

  Drawable appIcon = packageManager
    .getApplicationIcon(packageInfo.applicationInfo);
  String appName = packageManager.getApplicationLabel(
    packageInfo.applicationInfo).toString();
  appIcon.setBounds(0, 0, 40, 40);
  holder.apkName.setCompoundDrawables(appIcon, null, null, null);
  holder.apkName.setCompoundDrawablePadding(15);
  holder.apkName.setText(appName);
  holder.ck1.setChecked(false);

  if (itemChecked[position])
   holder.ck1.setChecked(true);
  else
   holder.ck1.setChecked(false);

  holder.ck1.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    if (holder.ck1.isChecked())
     itemChecked[position] = true;
    else
     itemChecked[position] = false;
   }
  });

  return convertView;

 }



}


Screen Shots

List view with Check box
  List view with Check box

In this project i am not concern about design of layout. you can explore or style it as you require. in the above project i have taken boolean array which stores Status of check box weather it is checked or not. when user click on List view Item it will call Perfom Click method of check box which is equal to call onclick of check box. And on button click i have called Toast message with all checked item of the list.

I have taken Packagelist as list view item but you can take any value like String, integer or both. i hope this will help you. if you have any error or query then comment in below comment box.
Keep coding...

Download Code

Database Demo : Database Operations with Cursor Adapter Class Part-2

In this tutorial I will display inserted record and  update and delete row.  To display all records in list view you have to use Cursor Adapter class which allow you to set layout of your list item (Row) layout. When user click on list item it will redirect to update activity and onItemLongclick method.  it will ask for delete the row from database and also update list view. In Database Demo : Database Operations with Cursor Adapter Class Part-1 i have already done insert into the database. I hope you have seen that tutorial so you can understand this tutorial. On update and delete you have to do two simultaneous work update database and also update list view. 

Cursoradapter.java

package com.example.dbdemo;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.RatingBar;
import android.widget.TextView;

public class Cursoradapter extends CursorAdapter {

 public Cursoradapter(Context context, Cursor c) {
  super(context, c);
  // TODO Auto-generated constructor stub
 }
 @Override
 public View newView(Context con, Cursor c, ViewGroup arg2) {
  // TODO Auto-generated method stub
  
  LayoutInflater inflater = (LayoutInflater) con.getSystemService(con.LAYOUT_INFLATER_SERVICE);

        View retView = inflater.inflate(R.layout.list_item, null);
 
        return retView;
 }

 @Override
 public void bindView(View v, Context con, Cursor c) {
  // TODO Auto-generated method stub
  TextView id = (TextView) v.findViewById(R.id.row_tv0);
  TextView pname = (TextView) v.findViewById(R.id.row_tv1);
  TextView des = (TextView) v.findViewById(R.id.row_tv2);
  RatingBar rb = (RatingBar) v.findViewById(R.id.row_rating);
  TextView qty = (TextView) v.findViewById(R.id.row_tv3);
  
  id.setText(c.getString(c.getColumnIndex(c.getColumnName(0))));
  pname.setText(c.getString(c.getColumnIndex(c.getColumnName(1))));
  des.setText(c.getString(c.getColumnIndex(c.getColumnName(2))));
  rb.setRating(c.getFloat(c.getColumnIndex(c.getColumnName(3))));
  rb.setIsIndicator(true);
  qty.setText(c.getString(c.getColumnIndex(c.getColumnName(4))));
  
 }
 
 @Override
 protected void onContentChanged() {
  // TODO Auto-generated method stub
  super.onContentChanged();
  notifyDataSetChanged();
 }

}


list_item.xml


    

    

    

    

    



display.xml

androprogrammer.com



    


    
    


display.java
package com.example.dbdemo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

public class Display extends Activity implements OnItemClickListener  {

 ListView lv;
 Cursoradapter adapt;
 Cursor c;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_display);
  
  lv = (ListView) findViewById(R.id.listView1);
  final DbHelper helper = new DbHelper(this);
  helper.open();

  new Handler().post(new Runnable() {
            @Override
            public void run() {
             c = helper.getAllData();
             adapt = new Cursoradapter(Display.this, c);
          lv.setAdapter(adapt);
            }
        });
  
  
  lv.setOnItemClickListener(this);
  lv.setOnItemLongClickListener(new OnItemLongClickListener() {

   @Override
   public boolean onItemLongClick(AdapterView arg0, View v,
     int position, long arg3) {
    // TODO Auto-generated method stub
    TextView id = (TextView) v.findViewById(R.id.row_tv0);
    final int ids = Integer.parseInt(id.getText().toString());
    AlertDialog.Builder ad = new AlertDialog.Builder(Display.this);
    //ad.setTitle("Notice");
    ad.setMessage("Sure you want to delete item ?");
    ad.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
     
     @Override
     public void onClick(DialogInterface dialog, int which) {
      //Delete of record from Database and List view.
      helper.delete(ids);
      c.requery();
      adapt.notifyDataSetChanged();
      lv.setAdapter(adapt);
     }
    });
    ad.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
     
     @Override
     public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
     dialog.dismiss();
     }
    });
    ad.show();
    return false;
   }
  }); 
    
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.display, menu);
  return true;
 }


 @Override
 public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
  // TODO Auto-generated method stub
  TextView id = (TextView) v.findViewById(R.id.row_tv0);
  TextView pname = (TextView) v.findViewById(R.id.row_tv1);
  TextView des = (TextView) v.findViewById(R.id.row_tv2);
  RatingBar rb = (RatingBar) v.findViewById(R.id.row_rating);
  TextView qty = (TextView) v.findViewById(R.id.row_tv3);
  
  int ids = Integer.parseInt(id.getText().toString());
  String pn = pname.getText().toString();
  String d = des.getText().toString();
  float r = rb.getRating();
  int q = Integer.parseInt(qty.getText().toString());
  
  Intent updat = new Intent(Display.this,Updatedata.class);
  
  updat.putExtra("id", ids);
  updat.putExtra("pname", pn);
  updat.putExtra("desc",d);
  updat.putExtra("rat",r);
  updat.putExtra("qty",q);
  
  
  startActivityForResult(updat,101);
  
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  super.onActivityResult(requestCode, resultCode, data);
  
  if (resultCode == RESULT_OK) {
   switch (requestCode) {
   case 101:
    
    c.requery();
    adapt.notifyDataSetChanged();
    lv.setAdapter(adapt);
    break;
   }
  }
 }

}

Now if user just click on list view item it will be redirect to the update activity. so check out onItemClick method code. it will send clicked item information to update activity so user won't require to enter all data again.
update_data.xml

androprogrammer.com



    


    

    

    

    

        

        

    

    

    

    




Updatedata.java
package com.example.dbdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;

public class Updatedata extends Activity {

 Button update,cancel;
 EditText pname,desc,qty;
 RatingBar rb;
 DbHelper helper;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.update_data);
  
  update = (Button) findViewById(R.id.update_save);
  cancel = (Button) findViewById(R.id.update_cancel);
  pname = (EditText) findViewById(R.id.update_et1);
  desc = (EditText) findViewById(R.id.update_et2);
  qty = (EditText) findViewById(R.id.update_et3);
  rb = (RatingBar) findViewById(R.id.update_rb);
  
  Intent dis = getIntent();
  Bundle data = dis.getExtras();
  final int id = data.getInt("id");
  String pn = data.getString("pname");
  String d = data.getString("desc");
  float r = data.getFloat("rat", 0);
  int q = data.getInt("qty");
  
  pname.setText(pn);
  desc.setText(d);
  rb.setRating(r);
  qty.setText(""+ q);
helper = new DbHelper(Updatedata.this);
    helper.open();
  
  update.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    
    
    String name = pname.getText().toString();
    String des = desc.getText().toString();
    int quan = Integer.parseInt(qty.getText().toString());
    
    helper.update(id,name,des,quan);
    
    helper.close();
    Intent display = new Intent(Updatedata.this,Display.class);
    setResult(RESULT_OK, display);
    finish();
   }
  });

  cancel.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    helper.close();
    finish();
   }
  });
  
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.updatedata, menu);
  return true;
 }

}
Now Add this below code in DbHelper class before close method.
public void update(int id, String name, String des, int quan) {
  // TODO Auto-generated method stub
  ContentValues values = new ContentValues();
  values.put(pname, name);
  values.put(desc, des);
  values.put(quantity, quan);
  
  ourdb.update(product_table, values, order_id +" = "+ id , null);
 }

And Last Operation delete i have wrriten delete logic in List view OnItemLongClick method. so when user(Admin) Long press on List item. Alert dialog will popup to confirm delete operation. so now add this below code in DbHelper class for deleting row from Database after Update Method. delete method get id from list item and perform delete operation on the bases of it.
public void delete(int ids) {
  // TODO Auto-generated method stub
  ourdb.delete(product_table, order_id + " = " + ids, null);
 }
androprogrammer.com

After update or delete you have to update view of list also. so to update you have to requery cursor object.like this
c.requery(); adapt.notifyDataSetChanged();
One more thing you have to take consider is when you use rating bar in list view list view onItemClick method won't work so if you are facing this you have to setthis property.
rb.setIsIndicator(true);
So,that's lots of coding out require for all these operation. i know this is somehow confusing but when you do by yourself you will get this. if you have any query or problem then comment in below comment box.
You can download code from here.
Keep Coding and cheers.....

Database Demo : Database Operations with Cursor Adapter Class Part-1

         SQLite is best and lite weight database in mobile operating system. you can do all operation in SQLite like in all other database. If you have Lots of Records and want to display all detail of database you can use list view using different component of android like Text view ,Rating bar, Button etc .You can do main 4 types of operation on database like Select, update, delete and display. I will do all these operation but it having too much coding so I am gone break this in 2 part. So this is part-1 of database operation and I am gone cover insert and database helper class which is for connection between application and database. i have written all methods in this class so if i want any method like insert or update or create i can use this in all activity. This is re-usability of code so you don't have to write code in each activity. in this tutorial and in part-2 display, update and delete operation will be explain. In this tutorial I have used Product table in which user(Admin) can add product detail like name, description , rating or star to the product and available quantity.

Main.xml

androprogrammer.com



    
Main.java
package com.example.dbdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class Main extends Activity {

 Button insert,view;
 public static boolean isDbCreated = false;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
    
  insert = (Button) findViewById(R.id.button1);
  view = (Button) findViewById(R.id.button4);
  
  insert.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent insert = new Intent(getApplicationContext(),InsertActivity.class);
    startActivity(insert);
   }
  });
  
  view.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent view = new Intent(Main.this,Display.class);
    startActivity(view);
   }
  });
  
 }
 
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}

activity_Insert.xml

androprogrammer.com



   

    

    

    


    

    

    

    

    

    

    

        



InsertActivity.java
package com.example.dbdemo;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;

public class InsertActivity extends Activity {

 Button save,cancel;
 EditText name,desc,quantity;
 RatingBar rb;
 float ratings;
 int quan = 0;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_insert);
  
  save = (Button) findViewById(R.id.btsave);
  cancel = (Button) findViewById(R.id.btcancel);
  
  name = (EditText) findViewById(R.id.editText1);
  desc = (EditText) findViewById(R.id.editText2);
  quantity = (EditText) findViewById(R.id.editText3);
  rb = (RatingBar) findViewById(R.id.ratingBar1);
  
  rb.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
   
   @Override
   public void onRatingChanged(RatingBar ratingBar, float rating,
     boolean fromUser) {
    // TODO Auto-generated method stub
    ratings = rating;
   }
  });
  
  final DbHelper helper = new DbHelper(InsertActivity.this);
  
  save.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    boolean inserted = true;
    try {
      String pname = name.getText().toString();
      String des = desc.getText().toString();
      quan = Integer.parseInt(quantity.getText().toString());
      
      helper.open();
      helper.insert(pname , des , ratings , quan);
      
    } catch (Exception e) {
     // TODO: handle exception
     inserted = false;
     e.printStackTrace();
    }
    finally
    {
     if(inserted)
     {
      Dialog d = new Dialog(InsertActivity.this);
      d.setTitle("Success..");
      d.show();
     }
     helper.close();
     name.setText("");
     desc.setText("");
     quantity.setText("");
    }
   }
  });
  cancel.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    finish();
   }
  });
  
  
   
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.insert, menu);
  return true;
 }

}

DbHelper.java
package com.example.dbdemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper {

 public static final String DB_NAME = "mydb.db";
 public static final int version = 1;
 public static final String product_table = "tblproduct";
 public static final String Emp_table = "Employee";
 public static final String order_id = "_id";
 public static final String pname = "pname";
 public static final String desc = "desc";
 public static final String quantity = "quantity";
 public static final String rating = "rating";
 
 private SQLiteDatabase ourdb;
 private databaseHelper ourHelper;
 public Context ourContext;
 
 public DbHelper(Context c)
 {
  ourContext = c;
 }
 
 private class databaseHelper extends SQLiteOpenHelper 
 {

  public databaseHelper(Context context) {
   // TODO Auto-generated constructor stub
   super(context, DB_NAME, null, version);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
   // TODO Auto-generated method stub
   db.execSQL("create table " + product_table +" ( "+ order_id + " INTEGER PRIMARY KEY AUTOINCREMENT , " + pname + " TEXT NOT NULL ," + desc + " TEXT ," 
      + rating + " INTEGER ," + quantity +" INTEGER );");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   // TODO Auto-generated method stub
   
  }
  
 }
 
 public DbHelper open() throws SQLException
 {
  databaseHelper ourHelper = new databaseHelper(ourContext);
  ourdb = ourHelper.getWritableDatabase();
  return this;
  
 }
 
 public void close() 
 {
  ourdb.close();
 }

 public long insert(String name, String des, Float ratings, int quan) throws SQLException
 {
  // TODO Auto-generated method stub
  ContentValues cv = new ContentValues();
  cv.put(pname, name);
  cv.put(desc, des);
  cv.put(rating, ratings);
  cv.put(quantity, quan);
  return ourdb.insertOrThrow(product_table, null, cv);
  
  
 }
 
}


In this tutorial I have used only one table but you can take any number of table. one thing you have to consider is cursor require “_id” field as per android document. Cursor will fetch record on the basis of “_id” column so you have to add this field in your table. if you have any query or problem then post in below comment box.

Keep coding and cheers ... =D 

Styles for List view in Android

In the previous examples i have shown you how to make list view with with custom adapter class and  list view with check box and also solved check box issue with list view. but in both tutorial my list view is simple i mean no styles on it to give it elegant look.  To make List view more attractive and funky or simple and sharp like Google now you can apply your imagination on it. In this tutorial I will show you how to apply styles for each row item of list view and how to apply different styles for alternative row of list view. 


1. Simple style for List view


Styles for List view in Android

item_bg.xml


    



2.Alternative layout for List item



Styles for List view in Android


item_bg2.xml

    
        

    
    



3.Round Corner Style for List item


Styles for List view in Android


item_bg3.xml


     

    

    
    



In the above three diffrent styles i have only upload code for xml file of background. you have to set these xml file as background property of your root layout. as i have told you earlier it is based on your imagination and try and error bases. so you have to explore it as per your requirement. hope this code will help you.
if you have any doubts or query then comment in below comment section.
Keep coding and cheers .....

Download Code

Get Installed Application in List view using Custom Adapter

          Some Times you may require user installed application in Android to perform certain task like Lock application or you may working on project which hide application or application like Task manager so this tutorial will help you to get all user installed application and sort them to display it. There are may ways to Display all application or only user installed apps with list view or Table view or you can use different layout for each Application to be display.
In this tutorial i am gone use following concept,
  1. List 
  2. PackageManager 
  3. Collections 
  4. BaseAdapter 
  5. PackageInfo


Main.java

package com.androprogrammer.app1;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;

public class Main extends Activity {

 ListView apps;
 PackageManager packageManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        apps = (ListView) findViewById(R.id.listView1);
        packageManager = getPackageManager();
  final List <packageinfo> packageList = packageManager
    .getInstalledPackages(PackageManager.GET_META_DATA); // all apps in the phone
  final List <packageinfo> packageList1 = packageManager
    .getInstalledPackages(0);

    try {
      packageList1.clear();
      for (int n = 0; n < packageList.size(); n++) 
      {

       PackageInfo PackInfo = packageList.get(n);
       if (((PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true) 
        //check weather it is system app or user installed app
       {
        try 
        {
         
          packageList1.add(packageList.get(n)); // add in 2nd list if it is user installed app 
           Collections.sort(packageList1,new Comparator <packageinfo >() 
             // this will sort App list on the basis of app name
           {
            public int compare(PackageInfo o1,PackageInfo o2) 
            {
             return o1.applicationInfo.loadLabel(getPackageManager()).toString()
               .compareToIgnoreCase(o2.applicationInfo.loadLabel(getPackageManager())
                   .toString());// compare and return sorted packagelist.
            }
           });
           
         
        } catch (NullPointerException e) {
         e.printStackTrace();
        }
       }
      }
     } catch (Exception e) {
      e.printStackTrace();
     }
    Listadapter Adapter = new Listadapter(this,packageList1, packageManager);
    apps.setAdapter(Adapter);
        
    }
}
Listadapter.java
package com.androprogrammer.app1;

import java.util.List;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class Listadapter extends BaseAdapter{

 List <packageinfo> packageList;
 Activity context;
 PackageManager packageManager;
 

 public Listadapter(Activity context, List <packageinfo> packageList,
   PackageManager packageManager) {
  super();
  this.context = context;
  this.packageList = packageList;
  this.packageManager = packageManager;
  
 }

 private class ViewHolder {
  TextView apkName;
 }

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

 public Object getItem(int position) {
  return packageList.get(position);
 }

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

 @Override
 public View getView(final int position, View convertView, ViewGroup parent) {
  final ViewHolder holder;
  
  LayoutInflater inflater = context.getLayoutInflater();

  if (convertView == null) {
   convertView = inflater.inflate(R.layout.list_item, null);
   holder = new ViewHolder();

   holder.apkName = (TextView) convertView
     .findViewById(R.id.textView1);

   convertView.setTag(holder);

  } else {
   
   holder = (ViewHolder) convertView.getTag();
  }
  
  PackageInfo packageInfo = (PackageInfo) getItem(position);

  Drawable appIcon = packageManager
    .getApplicationIcon(packageInfo.applicationInfo);
  String appName = packageManager.getApplicationLabel(
    packageInfo.applicationInfo).toString();
  appIcon.setBounds(0, 0, 40, 40);
  holder.apkName.setCompoundDrawables(appIcon, null, null, null);
  holder.apkName.setCompoundDrawablePadding(15);
  holder.apkName.setText(appName);
  
  return convertView;

 }


}
main.xml


    
    



list_item.xml


    



You can directly copy and paste above code in your project and it will give you all user installed apps in sorted order. This will look like this. Image of Application will be fetch and display dynamically so you are not require to take image view in list_item.xml. for this
Drawable appIcon = packageManager.getApplicationIcon(packageInfo.applicationInfo);
This will fetch icon from Packageinfo object and it will store in Drawable object.


i hope you may know some basic concept of java like List,collection etc. but in list view adapter android call Listadapter.getview() method each time and create view and then display it. if you scroll list view it will create view for next few elements of the list and garbage collector will clean old created views every time you scroll list view.

I hope this may be helpful to you and share it so it can be helpful to the others. if you have any doubts or any error then let me know.