Wednesday, September 25, 2013

Android Custom GridView Example

Creating a custom  GridView with Text and Image is as easy as Using a Simple GridView.
We need to just have a custom adapter and populate the GridView elements with custom adapter. It is similar to populating a ListView with Custom Adapter.

If you are not familiar with these two concepts follow my blog

Using Android GridView
ListView with  Custom Adapter

In this example I have explained how to  how to make a custom grid with Text and Image and poipulate it's content through Custom Adapter.

Steps:
  • Create Layout
  • Create Cutom Adapter and override it's getView() method.
  • Set the adapter to GridView


Custom GridView

main.xml


<RelativeLayout 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"
    tools:context=".MainActivity" >

   <GridView
        android:id="@+id/gridViewCustom"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:columnWidth="80dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth" />


</RelativeLayout>

grid_row.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="5dp" >

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textSize="15sp" >
    </TextView>

</LinearLayout>

CustomGridViewMainActivity.java

public class CustomGridViewMainActivity extends Activity
{

   
            GridView gridView;
            GridViewCustomAdapter grisViewCustomeAdapter;
           
          
            @Override
            protected void onCreate(Bundle savedInstanceState)
            {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                   
                   
                    gridView=(GridView)findViewById(R.id.gridViewCustom);
                    // Create the Custom Adapter Object
                    grisViewCustomeAdapter = new GridViewCustomAdapter(this);
                    // Set the Adapter to GridView
                    gridView.setAdapter(grisViewCustomeAdapter);
                     
                    // Handling touch/click Event on GridView Item

                      gridView.setOnItemClickListener(new OnItemClickListener() {

                       @Override
                       public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
                           String selectedItem;
                           if(position%2==0)
                               selectedItem="Facebook";
                           else
                               selectedItem="Twitter";
                        Toast.makeText(getApplicationContext(),"Selected Item: "+selectedItem, Toast.LENGTH_SHORT).show();
                       
                       }
                      });


               }

}


 GridViewCustomAdapter.java


public class GridViewCustomAdapter extends ArrayAdapter
{
         Context context;
      
   

     public GridViewCustomAdapter(Context context)
     {
             super(context, 0);
             this.context=context;
            
     }
   
     public int getCount()
        {
                     return 24;
        }

     @Override
     public View getView(int position, View convertView, ViewGroup parent)
     {
             View row = convertView;
            
             if (row == null)
             {
                     LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                     row = inflater.inflate(R.layout.grid_row, parent, false);


                     TextView textViewTitle = (TextView) row.findViewById(R.id.textView);
                     ImageView imageViewIte = (ImageView) row.findViewById(R.id.imageView);
                    
                     if(position%2==0)
                     {
                             textViewTitle.setText("Facebook");
                             imageViewIte.setImageResource(R.drawable.facebook);
                     }
                     else
                     {
                             textViewTitle.setText("Twitter");
                             imageViewIte.setImageResource(R.drawable.twitter);
                     }
             }

   
     
      return row;

     }

}
    


Friday, September 20, 2013

Android WebView Example

WebView is a View that displays web pages. Using his class we can display some online content within our Activity.

If you want to deliver a web application (or just a web page) as a part of a client application, you can do it using WebView. The WebView class is an extension of Android's View class that allows you to display web pages as a part of your activity layout.

In this Example you will see how to use WebView in your activity.

Do not forget to add the Internet permission in your manifest file.
 <uses-permission android:name="android.permission.INTERNET" />

main.xml 


<RelativeLayout 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"
    tools:context=".MainActivity" >

    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>
   
</RelativeLayout>

WebViewActivity

public class MainActivity extends Activity
{
   
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        WebView  webView = (WebView) findViewById(R.id.webView1);
        webView.loadUrl("http://www.google.com");

           
    }
}

Wednesday, September 11, 2013

Android MediaPlayer Example

MediaPlayer class is  used to control playback of audio/video files and streams.
Using MediaPlayer class we can control the behavioyr of player like volume control, whether to repeat the current tarck or not, stop or pause the playback etc.

Steps:

  1. Initialize the Media Player with media to play.
  2. Prepare the Media Player for playback.
  3. Start the playback. 
  4. Pause or stop the playback prior to its completing.
  5. Playback complete.
To play a media resource you need to create a new MediaPlayer object, initialize it with a media
source, and prepare it for playback.

When you have finished playing , call the release method on your Media Player object to free the resources associated with the MediaPlayer

mediaPlayer.release();

Preparing Audio for Playback


To play back audio content using the Media Player, we need to create a new Media Player object and
set the data source of the audio (pass as paarmeter).

  • A resource identifier
  • A URI to a local file using the file
  • A URI to an online audio resource as a URL 
  • A URI to a local Content Provider row
MediaPlayer filePlayer = MediaPlayer.create(appContext,
Uri.parse("file:///sdcard/localfile.mp3"));


MediaPlayer urlPlayer = MediaPlayer.create(appContext,
Uri.parse("http://site.com/audio/audio.mp3"));


MediaPlayer contentPlayer = MediaPlayer.create(appContext,
Settings.System.DEFAULT_RINGTONE_URI)



we can also use setDataSource method to specify the resource
like

myMediaPlayerObject.setDataSource("/sdcard/music/tarck1.mp3");


Controlling The PlayBack

Skip for a particular time

mediaPlayerObject.start();
int pos = mediaPlayerObject.getCurrentPosition();
int duration = mediaPlayerObject.getDuration();
mediaPlayerObject.seekTo(pos + (duration-pos)/10);

Repeating the Audio Playback track

We can use the isLooping and setLooping methods to specify if the media being played should repeat or loop when it completes.

if (!mediaPlayer.isLooping())
mediaPlayer.setLooping(true);

Controlling the Volume of Media Player


We acn also  control the volume for each channel during playback using the setVolume method. It takes
a scalar float value between 0 and 1 for both the left and right channels (where 0 is silent and 1 is
maximum volume).

mediaPlayer.setVolume(1f, 0.5f);


MediaPlayer Example:


public class MediaPalyerActivity  extends Activity
{
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
                super.onCreate(savedInstanceState);
               
                MediaPlayer  myMediaPlayer=new MediaPlayer();
               
                try
                {
                    myMediaPlayer.setDataSource("/sdcard/music/tarck1.mp3");
                    myMediaPlayer.prepare();
                    myMediaPlayer.start();
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
        }
}

Tuesday, September 10, 2013

Android Text To Speech Example

In Android 1.6 (SDK API level 4) the text to speech (TTS) engine was introduced. We can use this API to
produce speech synthesis from within our applications, allowing the application to ‘‘talk’’ to your users.

 Before using the TTS engine, it’s good practice to confirm the language packs are installed or not, if not installed we must install the language pack.

Once you’ve confirmed the voice data is available, you need to create and initialize a new TextToSpeech
instance. Note that you cannot use the new Text To Speech object until initialization is complete.

 public void onInit(int status)
            {
               
                    if (status == TextToSpeech.SUCCESS)
                    {

                               // ready to Speak
                    }
          }

When Text To Speech has been initialized you can use the speak method to synthesize voice using the
default device audio output.

tts.speak("Text to Speak", TextToSpeech.QUEUE_FLUSH, null)


Android Text To Speech Example:


In the example we have an EditText , in which user enters the text and  when clicks on Button  we c all speakTheText() method to speak the entered Text.


main.xml


Android TextToSpeech


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D1FFFF"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView1"
        android:layout_marginTop="120dp"
        android:gravity="center_horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="34dp"
        android:textStyle="bold"
        android:text="Text To Speech Tutorial" />

    <EditText
        android:id="@+id/editTextToSpeech"
         android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:hint="Enter the text to speak"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/buttonSpeak"
        android:layout_marginTop="30dp"
        android:textSize="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Speak Now" />
   
   
  </LinearLayout>







MainActivity.java


public class MainActivity extends Activity  implements TextToSpeech.OnInitListener
{
            EditText editText;
            Button buttonSpeak;
          
            TextToSpeech tts ;
           
            @Override
            protected void onCreate(Bundle savedInstanceState)
            {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.main);
                       
                        tts = new TextToSpeech(this, this);
                       
                        editText =(EditText)findViewById(R.id.editTextToSpeech);
                        buttonSpeak =(Button)findViewById(R.id.buttonSpeak);
                       
           
                        buttonSpeak.setOnClickListener(new View.OnClickListener() {
                           
                            public void onClick(View v) {
                                // TODO Auto-generated method stub
                                speakTheText();
                               
                            }
                        });
            }

           
           
           
            @Override
            public void onDestroy()
            {
                // Do Not forget to Stop the TTS Engine when you do not require it       
                    if (tts != null)
                    {
                        tts.stop();
                        tts.shutdown();
                    }
                    super.onDestroy();
            }

            public void onInit(int status)
            {
               
                    if (status == TextToSpeech.SUCCESS)
                    {

                            int result = tts.setLanguage(Locale.GERMAN);

                            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
                            {
                                   Toast.makeText(this, "This Language is not supported", Toast.LENGTH_LONG).show();
                            }
                            else
                            {
                                Toast.makeText(this, "Ready to Speak", Toast.LENGTH_LONG).show();
                                speakTheText();
                            }

                    }
                    else
                    {
                         Toast.makeText(this, "Can Not Speak", Toast.LENGTH_LONG).show();
                    }

            }

            private void speakTheText()
            {
                        String textToSpeak = editText.getText().toString();
                        tts.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null);
            }


}






Wednesday, September 4, 2013

PreferenceActivity In Android Example

PreferenceActivity  is the base class for an activity to show a hierarchy of preferences to the user.
It is generally used for saving the setting/preference of  User. Android provides excellent framework to save and mange the User preferences.
We just need to use the class and specify some resources , and it automatically creates GUI for that itself.

PreferenceActivity  Example In Android:


In this example I have created a Page/Screen with user can save his password, and other choices/details.

Steps:


1: Create xml resource for Preference:  create an xml file inside xml folder (if xml folder is not there inside res folder, create xml folder inside res folder. In the example I have created user_settings.xml file inside xml folder.

2: Create a Class which extends PreferenceActivity class , and inflate the created xml using addPreferencesFromResource() method.

3: Call/Start the PreferenceActivity (created in 2nd steps) from where you want. In the example I have called from MainActivity using startActivityForResult()   method.

Now lets go Step by Step:

Step1: Create XML resource inside xml folder: 


user_settings.xml

This file defines user interface for setting page. We have created 3 different categories here.

1: EditTextPreference  is used to define an editable text property. In this example used this field to enter the Password
2:CheckBoxPreference  allows you to define a boolean value in preference screen.
3: ListPreference   display choices from which user can select one.. In this examplewe have used ListPreference to choose the frequency when user should be reminded.


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

    <PreferenceCategory android:title="Settings" >
        <EditTextPreference
                android:title="Password"
                android:summary="Set Your Password"
                android:key="prefUserPassword"/>
    </PreferenceCategory>
    
    <PreferenceCategory android:title="Security Settings" >
        <CheckBoxPreference
            android:defaultValue="false"
            android:key="prefLockScreen"
            android:summary="Lock The Screen With Password"
            android:title="Screen Lock" >
        </CheckBoxPreference>

        <ListPreference
            android:key="prefUpdateFrequency"
            android:title="Reminder for Updation"
            android:summary="Set Update Reminder Frequency"
            android:entries="@array/updateFrequency"
            android:entryValues="@array/updateFrequencyValues"
            />
    </PreferenceCategory>

</PreferenceScreen>

Since we have used arrays here, We need to define it inside array.xml file.
Create an arrays.xml file  inside values folder and write following

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="updateFrequency">
        <item name="1">Daily</item>
        <item name="7">Weekly</item>
        <item name="3">Yearly</item>
        <item name="0">Never(I will Myself) </item>
    </string-array>
    <string-array name="updateFrequencyValues">
        <item name="1">1</item>
        <item name="7">7</item>
        <item name="30">30</item>
        <item name="0">0</item>
    </string-array>
    
</resources>


2: Create a Class which extends PreferenceActivity class


public class UserSettingActivity extends PreferenceActivity
{
            
             @Override
             public void onCreate(Bundle savedInstanceState)
             {
                     super.onCreate(savedInstanceState);
                      // add the xml resource                     addPreferencesFromResource(R.xml.user_settings);
                    

             }

}

3: Call/Start the PreferenceActivity.

We have called  UserSettingActivity from MainActivity

xml for MainActivity

main.xml   contains two things

1: Button: We start  UserSettingActivity when user clicks on this buttons.
2: TextView:   To show the User data like password etc.

<RelativeLayout 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:background="#CCCCFF"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/buttonSettings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="150dp"
        android:textSize="25dp"
        android:text="Settings" />

    <TextView
        android:id="@+id/textViewSettings"
        android:textSize="21dp"
        android:textColor="#0000FF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/buttonSettings"
        android:layout_marginTop="66dp"
        android:text="No Settings"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

MainActivty

public class MainActivity extends Activity
{
            private static final int SETTINGS_RESULT = 1;
            Button settingButton;

              @Override
              protected void onCreate(Bundle savedInstanceState)
              {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.main);
                       
                        Button btnSettings=(Button)findViewById(R.id.buttonSettings);
                        // start the UserSettingActivity when user clicks on Button
                        btnSettings.setOnClickListener(new View.OnClickListener() {
                           
                            public void onClick(View v) {
                                // TODO Auto-generated method stub
                                Intent i = new Intent(getApplicationContext(), UserSettingActivity.class);
                                startActivityForResult(i, SETTINGS_RESULT);
                            }
                        });
              }



                @Override
                protected void onActivityResult(int requestCode, int resultCode, Intent data)
                {
                            super.onActivityResult(requestCode, resultCode, data);

                                if(requestCode==SETTINGS_RESULT)
                                {
                                    displayUserSettings();
                                }

                }

               
                private void displayUserSettings()
                {
                        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

                        String  settings = "";

                        settings=settings+"Password: " + sharedPrefs.getString("prefUserPassword", "NOPASSWORD");

                        settings=settings+"\nRemind For Update:"+ sharedPrefs.getBoolean("prefLockScreen", false);

                        settings=settings+"\nUpdate Frequency: "
                                + sharedPrefs.getString("prefUpdateFrequency", "NOUPDATE");


                        TextView textViewSetting = (TextView) findViewById(R.id.textViewSettings);

                        textViewSetting.setText(settings);
                 }

}



How to fetch the User Saved data:


 sharedPrefs.getString("prefUserPassword", "NOPASSWORD");
we need to provide the key , that was given in xml ( android:key="prefUserPassword" in user_settings.xml file  )
We need to pass key as first argument and default value as second argumment.


PreferenceActivity In Android

PreferenceActivity In Android

PreferenceActivity In Android


Saturday, August 24, 2013

Android RatingBar Example

A Rating Bar is used to show rating in Stars.The user can touch/drag or use arrow keys to set the rating when using the default size RatingBar.

RatingBar Example.

Android RatingBar


main.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="match_parent"
    android:orientation="vertical"
    android:background="#C2C2A3">

    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_marginTop="50dp"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="OK" />
</LinearLayout>
    
How to change the Number of Stars
Use  android:numStars   attribute to set the number of stars you want.

MainActivity.java


public class MainActivity extends Activity
{
        RatingBar ratingBar;
        Button btn;
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   
    ratingBar=(RatingBar)findViewById(R.id.ratingBar1);
    btn=(Button)findViewById(R.id.button1);
   
    // Set ChangeListener to Rating Bar
    ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
        public void onRatingChanged(RatingBar ratingBar, float rating,
        boolean fromUser) {

        Toast.makeText(getApplicationContext(),"Your Selected Ratings  : " + String.valueOf(rating),Toast.LENGTH_LONG).show();
        
        }
        });
     
    btn.setOnClickListener(new View.OnClickListener() {
     
   
public void onClick(View arg0) {
// TODO Auto-generated method stub
float rating=ratingBar.getRating();
Toast.makeText(getApplicationContext(),"Your Selected Ratings  : " + String.valueOf(rating),Toast.LENGTH_LONG).show();
}
});
   
    }
   
    
}


How to Set The Rating at Run time
use method
ratingBar.setRating(4);   or pass any number like 3.5, 4.5 etc.


Android RatingBar

Android Custom Adapter Example

The Android Development Tutorials blog contains Basic as well as Advanced android tutorials.Go to Android Development Tutorials to get list of all Android Topics.


Populate ListView with Custom Adapter

ListView can be populated by ArrayAdapter, Database, ArrayList etc
In this post I will describe how to populate ListView using a Custom Adapter.

Have a look at my previous post
Populating ListView with Database
Populating ListView with ArrayList

ListView with Custom Adapter Example


In this example I have created a listView  and populated it with Custom Adapter.
Each of the ListView item contain two views
TextView SMS Sender : to show SMS Sender Number
TextView SMSBody : to show the SMS Body/content

Here the ListView shows the all the SMSes with Sender Number and SMSBody.

What we need to do ..
Create a Custom Adapter
and add/set  the adapter to ListView.

Add the following permission in your manifest file to read the SMS..
   <uses-permission android:name="android.permission.READ_SMS"/>
   <uses-permission android:name="android.permission.WRITE_SMS"/>


listview_activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#D1FFFF"
    android:orientation="vertical">
   
   
    <ListView
        android:id="@+id/listViewSMS"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:dividerHeight="0.1dp"
        android:divider="#0000CC"
        >
    </ListView>
   
  </LinearLayout>



listview_each_item.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="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textViewSMSSender"
        android:paddingLeft="2dp"
        android:textSize="20dp"
        android:textStyle="bold"
        android:textColor="#0000FF"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textViewMessageBody"
        android:paddingLeft="5dp"
        android:textColor="#5C002E"
        android:textSize="17dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>
   
  </LinearLayout>





ListViewMainActivity.java



public class ListViewMainActivity extends Activity
{
            ListView listViewSMS;
            Cursor cursor;
            SMSListAdapter smsListAdapter;
            Context context;
            @Override
            protected void onCreate(Bundle savedInstanceState)
            {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.listview_activity_main);
                   
                    context=this;
                    listViewSMS=(ListView)findViewById(R.id.listViewSMS);

                    cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
                   
                    // Create the Adapter
                    smsListAdapter=new SMSListAdapter(this,cursor);
                   
                    // Set The Adapter to ListView
                    listViewSMS.setAdapter(smsListAdapter);
                    

                    // to handle click event on listView item
                    listViewSMS.setOnItemClickListener(new OnItemClickListener()
                    {
                            public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3)
                            {
                                // when user clicks on ListView Item , onItemClick is called
                                // with position and View of the item which is clicked
                                // we can use the position parameter to get index of clicked item

                                TextView textViewSMSSender=(TextView)v.findViewById(R.id.textViewSMSSender);
                                TextView textViewSMSBody=(TextView)v.findViewById(R.id.textViewMessageBody);
                                String smsSender=textViewSMSSender.getText().toString();
                                String smsBody=textViewSMSBody.getText().toString();
                               
                                // Show The Dialog with Selected SMS
                                AlertDialog dialog = new AlertDialog.Builder(context).create();
                                dialog.setTitle("SMS From : "+smsSender);
                                dialog.setIcon(android.R.drawable.ic_dialog_info);
                                dialog.setMessage(smsBody);
                                dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",
                                        new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                   
                                            dialog.dismiss();
                                            return;
                                }   
                                });
                                dialog.show();
                            }
                        });
       
            }
}



SMSListAdapter.java : The Custom Adapter


public class SMSListAdapter  extends BaseAdapter
{
   
    private Context mContext;
    Cursor cursor;
    public SMSListAdapter(Context context,Cursor cur)
    {
            super();
            mContext=context;
            cursor=cur;
          
    }
      
    public int getCount()
    {
        // return the number of records in cursor
        return cursor.getCount();
    }

    // getView method is called for each item of ListView
    public View getView(int position,  View view, ViewGroup parent)
    {
                    // inflate the layout for each item of listView
                    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    view = inflater.inflate(R.layout.listview_each_item, null);
           
                    // move the cursor to required position
                    cursor.moveToPosition(position);
                   
                    // fetch the sender number and sms body from cursor
                    String senderNumber=cursor.getString(cursor.getColumnIndex("address"));
                    String smsBody=cursor.getString(cursor.getColumnIndex("body"));
                  
                    // get the reference of textViews
                    TextView textViewConatctNumber=(TextView)view.findViewById(R.id.textViewSMSSender);
                    TextView textViewSMSBody=(TextView)view.findViewById(R.id.textViewMessageBody);
                   
                    // Set the Sender number and smsBody to respective TextViews
                    textViewConatctNumber.setText(senderNumber);
                    textViewSMSBody.setText(smsBody);
                   
       
                    return view;
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
}

ListView with Custom Adapter


 

New Advance Topics:                   Android LiveWallpaer Tutorial
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swipe Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation
Android AlarmManager                 Android BootReceiver                       Vibrate Phone In a Desirable Pattern    
Developing for Different Screen Sizes           Showing Toast for Longer Time       Publishing your App
How to publish Android App on Google Play
Android TextWatcher                               Android ExpandableListView

 Beginning With Android
      Android : Introduction(What is Android)                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views


Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Advance Views
Android Spinner                                                                           Android GalleryView
Android TabWidget                                                                      Android ExpandableListView

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time


TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage

Working With Incoming Calls                                       DataBase :  Introduction of SQLiteDataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android


Miscellaneous
Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog
How to Hide Title Bar In Android
How to show an Activity in Landscape or Portrait Mode only.
How to Set an Image as Wallpaper.