Thursday, April 19, 2012

Getting the MD5 Fingerprint of the SDK Debug Certificate

type command in windows


C:\Program Files\Java\jdk1.6.0\bin>keytool -list -alias androiddebugkey -keystor
e "C:\Documents and Settings\sys143\.android\debug.keystore" -storepass android
-keypass android
androiddebugkey, Mar 27, 2012, PrivateKeyEntry,
Certificate fingerprint (MD5): CD:9B:AF:B4:D8:81:64:A3:7D:42:F4:3B:12:F0:90:A0

Thursday, March 29, 2012

installing jad plugin in eclipse

Integrated Java Decompiler (Jad) with Eclipse

See following steps to integrate Java Decompiler (Jad) with Eclipse IDE.

1. Download Jad

Download the Jad executable file.
Official Jad website seem not working any more, try mirror download links instead.
Jad Official website
  1. http://www.kpdus.com/jad.html
Jad mirror download
  1. http://www.softpedia.com/get/Programming/Debuggers-Decompilers-Dissasemblers/JAD.shtml
  2. http://www.varaneckas.com/jad

2. Download Jad Eclipse plugin

Download the Jad Eclipse plugin named “Jabclipse (net.sf.jadclipse_x.x.x.jar)
http://sourceforge.net/projects/jadclipse/

3. Copy it to Eclipse plugin folder

Copy the downloaded Jad Eclipse plugin – Jabclipse(jadclipse_x.x.x.jar) to Eclipse plugin folder.
For example,
D:\eclipse\plugins\net.sf.jadclipse_3.3.0.jar
P.S No need to extract it, just copy the whole jar file.

4. Restart Eclipse

Restart Eclipse to make the plugin take effect.

5. Configure Jadclipse in Eclipse

In Eclipse, Click Window –> Preference –> Java –> Jadclipse , Key in Jad’s path in “Path to Decompiler” field
jadEclipse

6. Done

Wednesday, March 28, 2012

convertion to xml

public String toXML() {
        StringBuilder buf = new StringBuilder();
        buf.append("<iq ");
        if (getPacketID() != null) {
            buf.append("id=\"" + getPacketID() + "\" ");
        }
        if (getTo() != null) {
            buf.append("to=\"").append(StringUtils.escapeForXML(getTo())).append("\" ");
        }
        if (getFrom() != null) {
            buf.append("from=\"").append(StringUtils.escapeForXML(getFrom())).append("\" ");
        }
        if (type == null) {
            buf.append("type=\"get\">");
        }
        else {
            buf.append("type=\"").append(getType()).append("\">");
        }
        // Add the query section if there is one.
        String queryXML = getChildElementXML();
        if (queryXML != null) {
            buf.append(queryXML);
        }
        // Add the error sub-packet, if there is one.
        XMPPError error = getError();
        if (error != null) {
            buf.append(error.toXML());
        }
        buf.append("</iq>");
        return buf.toString();
    }

creating and destroying byte stream object

// Otherwise, it's a generic Serializable object. Serialized objects are in
                // a binary format, which won't work well inside of XML. Therefore, we base-64
                // encode the binary data before adding it.
                else {
                    ByteArrayOutputStream byteStream = null;
                    ObjectOutputStream out = null;
                    try {
                        byteStream = new ByteArrayOutputStream();
                        out = new ObjectOutputStream(byteStream);
                        out.writeObject(value);
                        buf.append("java-object\">");
                        String encodedVal = StringUtils.encodeBase64(byteStream.toByteArray());
                        buf.append(encodedVal).append("</value>");
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                    finally {
                        if (out != null) {
                            try {
                                out.close();
                            }
                            catch (Exception e) {
                                // Ignore.
                            }
                        }
                        if (byteStream != null) {
                            try {
                                byteStream.close();
                            }
                            catch (Exception e) {
                                // Ignore.
                            }
                        }
                    }
                }

Monday, March 26, 2012

android with xm

when user logs in your projects call for signup for xmpp.

public void SignIn(String userid,String password){
                        Log.e(TAG,"ctx"+ctx);
                                    //         mConnection1 =ctx.getXMPPConnection();
                        mPassword=password;
                        Log.e(TAG,"mPassword"+mPassword);
                        mSigninTask = new SigninTask();
                        mSigninTask.execute(getBaseContext());         
            }


protected class SigninTask extends AsyncTask<Context, Integer, String>
            {
                        // -- run intensive processes here
                        // -- notice that the datatype of the first param in the class definition matches the param passed to this method
                        // -- and that the datatype of the last param in the class definition matches the return type of this mehtod
                        @Override
                        protected String doInBackground( Context... params )
                        {


                                    try {
                                                //ConnectionConfiguration class if provided by Smack lib
                                                //ConnectionConfig class is user defined class for defining host,portno,service.
                                                ConnectionConfiguration config = new ConnectionConfiguration(ConnectionConfig.getHost(),ConnectionConfig.getPort());
                                                mConnection1=new XMPPConnection(config);
                                               
                                                            mConnection1.connect();
                                                    Log.i(TAG, "[SettingsDialog] Connected to " + mConnection1.getHost());
                                               
                                                 
                                   

                                                mConnection1.login(mUser,mPassword);
                                                Log.i(TAG, "Logged in as " + mConnection1.getUser());

                                                // Set the status to available
                                                Presence presence = new Presence(Presence.Type.available);
                                                presence.setStatus("am in hyderabad");

                                                mConnection1.sendPacket(presence);

                                    } catch (XMPPException ex) {
                                                Log.e(TAG, "[SettingsDialog] Failed to log in as " +mUser);
                                                  Log.e(TAG, "[SettingsDialog] Failed to connect to " + mConnection1.getHost());
                                                Log.e(TAG, ex.toString());
                                                return RET_LOGIN_FAILED;
                                    }

                                    return "COMPLETE!";
                        }
                        @Override
                        protected void onPreExecute()
                        {
                                    Log.i( TAG, "onPreExecute()" );
                                    super.onPreExecute();

                        }

                        // -- called from the publish progress
                        // -- notice that the datatype of the second param gets passed to this method
                        @Override
                        protected void onProgressUpdate(Integer... values)
                        {
                                    super.onProgressUpdate(values);
                                    Log.i( TAG, "onProgressUpdate(): " +  String.valueOf( values[0] ) );

                        }

                        // -- called if the cancel button is pressed
                        @Override
                        protected void onCancelled()
                        {
                                    super.onCancelled();
                                    Log.i(TAG, "onCancelled()" );

                        }

                        // -- called as soon as doInBackground method completes
                        // -- notice that the third param gets passed to this method
                        @Override
                        protected void onPostExecute( String result )
                        {
                                    ctx.setXmppConnection(mConnection1);
                                    ctx.setRoster();
                                    Log.i(TAG, "onPostExecute(): " + result );
                                    //setConnection();
                                   
                                   
                                    startService(new Intent(LoginInfo.this, MessageAlertService.class));
                                    dialog.dismiss();
                        }


            }
           


ConnectionConfig.java
public class ConnectionConfig {
            private static String host = "50.28.26.182" ;
            private static int port = 5222;
            private static String service;

            public static String getHost() {
                        return host;
            }
            public static int getPort() {
                        return port;
            }
            public static String getService() {
                        return service;
            }

}

MyAppContext.java

public class MyAppContext extends Application {
            private String mySessionId;
XMPPConnection mConnection;
            public HashMap<String,UserChatSession> UserChatSessionList=new HashMap<String,UserChatSession>();
            HashMap<String,Integer> notificationslist=new HashMap<String,Integer>();
            private int id;
            private int  mNotificationId=0;

            private Roster mRoster;
            private String mLoginName;
            public Cookie getMySessionCookie() {
                        return mySessionCookie;
            }

            public void setMySessionCookie(Cookie mySessionCookie) {
                        this.mySessionCookie = mySessionCookie;
            }

            public String getSessionId() {
                        return mySessionId;
            }

            public void setSessionId(String mySessionId) {
                        Log.e(TAG,"Session ID set in app context "+mySessionId);
                        this.mySessionId = mySessionId;
            }
            public String getmLoginName() {
                        Log.e(TAG,"mLoginName"+mLoginName);
                        return mLoginName;
            }

            public void setmLoginName(String mLoginName) {
                        this.mLoginName = mLoginName;
            }

            String mProfileid;
            public void setXmppConnection(XMPPConnection connection){


                        mConnection = connection;
                        Log.e("TAG","mConnection"+mConnection);
            }

            public XMPPConnection getXMPPConnection(){

                        return mConnection;
            }
            public void setLoginprofileid(String profileid){
                        mProfileid=profileid;
                        Log.e(TAG,"mProfileid"+mProfileid);
            }
            public String getLoginprofileid(){
                        Log.e(TAG,"mProfileid"+mProfileid);
                        return mProfileid;

            }
            public void setRoster(){
                        mRoster  = mConnection.getRoster();
                        Log.e(TAG,"mRoster "+mRoster);
            }

            public int getNotificationId(String fromName){
                        if(notificationslist.containsKey(fromName)){
                                    id=notificationslist.get(fromName);
                                    Log.e(TAG,"mNotificationId"+id);
                                    return id;
                        }
                        else{
                                    notificationslist.put(fromName, ++mNotificationId);
                                    Log.e(TAG,""+mNotificationId);
                                    return mNotificationId;
                        }

            }
            public Roster getRoster1(){
                        return mRoster;
            }
            public void logout(){          
                        mConnection.disconnect();
            }

            public UserChatSession getUserChatSeesion(String chatid){
                        UserChatSession userChatSession;
                        if(UserChatSessionList.containsKey(chatid)){
                                    userChatSession=UserChatSessionList.get(chatid);
                                    Log.e(TAG,"UserChatSessionList.size()"+UserChatSessionList.size());
                                    return userChatSession;
                        }
                        else{
                                    userChatSession=new UserChatSession();         
                                    UserChatSessionList.put(chatid,userChatSession);
                                    Log.e(TAG,"UserChatSessionList.size()"+UserChatSessionList.size());
                                    return userChatSession;

                        }

            }
}

MessageAlertService.java


package com.inception.network;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.DefaultMessageEventRequestListener;
import org.jivesoftware.smackx.MessageEventManager;
import org.jivesoftware.smackx.OfflineMessageManager;

import com.ServiceMessenger.R;
import com.inception.dataparser.UserChatSession;
import com.inception.dataprovider.DatabaseHelper;
import com.inception.sm.ApplicationManager;
import com.inception.sm.Globals;
import com.inception.sm.MyAppContext;
import com.inception.smui.Chat;
import com.inception.smui.ChatClient;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;

import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class MessageAlertService extends Service{

            private Handler mHandler = new Handler();
            private XMPPConnection mConnection1;
            String TAG="MessageAlertService";
            SharedPreferences mRowid;
            private ArrayList<String> messages = new ArrayList<String>();
            ChatClient chatClient;
            private static boolean isRunning = false;
            private int SIMPLE_NOTFICATION_ID;
            Boolean flag;
            ArrayList<ChatClient> mClients = new ArrayList<ChatClient>(); // Keeps track of all current registered clients.
            int mValue = 0; // Holds last value set by a client.
            MyAppContext ctx;
            private static ApplicationManager mAppMgr;
            private DatabaseHelper mDBHelper;
            String formattedDate;
            public static final int MSG_GET_SERVERMSG=10;
            public static final int MSG_AVAILABLE_SERVERMSG =27;
            private  SharedPreferences.Editor mRowidEditor;
            final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.
            int code=0;
            UserChatSession userChatSession;
            @Override
            public IBinder onBind(Intent intent) {
                        return mMessenger.getBinder();
            }
            class IncomingHandler extends Handler { // Handler of incoming messages from clients.
                        @Override
                        public void handleMessage(android.os.Message msg) {

                                    switch (msg.what) {
                                    case NetworkService.MSG_REGISTER_CLIENT:
                                                chatClient=new ChatClient();
                                                chatClient.setmMessenger(msg.replyTo);
                                                chatClient.setFilter(msg.getData().getString("filter"));
                                                //if(!(c.getFilter().equals("one")))
                                                //{
                                                Log.e(TAG,"am in incoming handler if");
                                                chatClient.setId(msg.getData().getString("id"));
                                                //         }
                                                mClients.add(chatClient);
                                                break;
                                    case NetworkService.MSG_UNREGISTER_CLIENT:


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

                                                            if(msg.replyTo.equals(mClients.get(i).getmMessenger())){
                                                                        mClients.remove(mClients.get(i));
                                                            }
                                                }

                                                break;

                                    default:
                                                super.handleMessage(msg);
                                    }
                        }
            }

            /** method to send messages to chat window class*/
            private void sendMessageToUI(int intvaluetosend,String msgfrom,String msgbody) {
                        for (int i=mClients.size()-1; i>=0; i--) {
                                    try {

                                                //Send data as a String

                                                android.os.Message msg = android.os.Message.obtain(null,MessageAlertService.MSG_AVAILABLE_SERVERMSG);
                                                Bundle b = new Bundle();
                                                b.putString("msgfrom",msgfrom);
                                                b.putString("msgbody",msgbody);
                                                b.putString("time", "received at"+formattedDate);
                                                msg.setData(b);

                                                mClients.get(i).getmMessenger().send(msg);

                                    } catch (RemoteException e) {
                                                // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
                                                mClients.remove(i);
                                    }
                        }
            }
            /** service life cycle method that gets called when sevice is invoked for first time*/
            @Override
            public void onCreate() {
                        super.onCreate();
                        mDBHelper = new DatabaseHelper(this);
                        mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());

            }

            /** service life cycle method that gets called when service is invoked every time*/
            @Override
            public int onStartCommand(Intent intent, int flags, int startId) {
                        Log.i(TAG, "onStartCommand entered");


                        ctx = (MyAppContext)getApplicationContext();
                        mConnection1=ctx.getXMPPConnection();
                        Log.e(TAG,"line no 112"+ mConnection1);
                        Log.i(TAG, "MyService Service Started.");
                        PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
                        /**
                         * packet listener to get in coming mesages from XMPP server
                         */
                        PacketListener MessageLis = new PacketListener(){

                                    public void processPacket(Packet packet) {
                                                Log.i(TAG, "Got packet");
                                                flag =false;        /** flag to track current chating person*/

                                                /** code to to find for the current chating person */
                                                final Message message = (Message) packet;
                                                if (message.getBody() != null) {
                                                            final String fromName = StringUtils.parseBareAddress(message.getFrom());
                                                            Log.i(TAG, "Got text [" + message.getBody() + "] from [" + fromName + "]");
                                                            messages.add(message.getBody());
                                                            Log.e(TAG,"mClients.size()"+mClients.size());
                                                            for (int i=mClients.size()-1; i>=0; i--) {
                                                                        chatClient=mClients.get(i);
                                                                        // Add the incoming message to the list view
                                                                        Log.e(TAG,"chatClient..getId()"+chatClient.getId());
                                                                        if(fromName.equals(chatClient.getId())){
                                                                                    sendMessageToUI(MSG_AVAILABLE_SERVERMSG,message.getFrom(),message.getBody());
                                                                                    flag=true;
                                                                        }


                                                            }
                                                            /**
                                                             * code to store data in incoming message in database(164-182)  
                                                             */
                                                            SQLiteDatabase database = mDBHelper.getWritableDatabase(); 
                                                            ContentValues values = new ContentValues();
                                                            values = new ContentValues();
                                                            values.put("username",ctx.getmLoginName());
                                                            String buddyname1=fromName.replaceAll("@50.28.26.182","").trim();
                                                            values.put("buddyname",buddyname1);

                                                            values.put("message",fromName+""+message.getBody());
                                                            Calendar c = Calendar.getInstance();
                                                            System.out.println("Current time => "+c.getTime());

                                                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                                            formattedDate = df.format(c.getTime());


                                                            Log.e(TAG,"System.currentTimeMillis()"+formattedDate);
                                                            values.put("time","received at"+formattedDate);
                                                            database.insert("ChatHistory", null,values);
                                                            /**
                                                             * code to delete rows that exceed maximum no of rows in table(184-223)
                                                             */
                                                            String rowid=null;

                                                            mRowid=getSharedPreferences(Globals.PREFS_NAME, 0);/** getting the row id value stored in shared preference to find deleting row*/
                                                            mRowidEditor=mRowid.edit();

                                                            String deleterowid=mRowid.getString("firstrowid","1");
                                                            Log.e(TAG,"mRowid"+mRowid.getString("firstrowid","1"));
                                                            Cursor data4 = database.rawQuery("select rowid from ChatHistory",null);
                                                            if(data4.getCount()>50){
                                                                        int noofdeletedrows=data4.getCount()-50;
                                                                        int daletedrow=Integer.parseInt(deleterowid);
                                                                        Log.e(TAG,"noofdeletedrows"+noofdeletedrows);
                                                                        for(int i=1;i<=noofdeletedrows;i++){
                                                                                    database.delete("ChatHistory","rowid= "+ deleterowid,null);
                                                                                    Log.e(TAG,"daletedrow"+daletedrow);
                                                                                    daletedrow++;
                                                                        }

                                                            }
                                                            Log.e(TAG,"mRowid"+mRowid.getString("firstrowid","1"));
                                                            Cursor data3 = database.rawQuery("select rowid,time from ChatHistory limit 1",null);
                                                            if (data3!= null)
                                                            {



                                                                        if (data3.moveToFirst()){
                                                                                    do{
                                                                                                rowid= data3.getString(data3.getColumnIndex("rowid"));
                                                                                                Log.e(TAG,"rowid"+rowid);
                                                                                    }while(data3.moveToNext());
                                                                        }
                                                            }

                                                            Log.e(TAG,"rowid out of if"+rowid);
                                                            mRowidEditor.putString("firstrowid",rowid);
                                                            mRowidEditor.commit();
                                                            Log.e(TAG,"mRowid"+mRowid.getString("firstrowid","1"));
                                                            /** code generate notification when */

                                                            if(!flag){
                                                                        userChatSession =ctx.getUserChatSeesion(fromName);
                                                                        NotificationManager mNotificationManager;
                                                                        mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
                                                                        final Notification notifyDetails =
                                                                                    new Notification(R.drawable.android,
                                                                                                            "You've got a new notification!",System.currentTimeMillis());
                                                                        Intent notifyIntent=new Intent(MessageAlertService.this,Chat.class);
                                                                        Context context = getApplicationContext();
                                                                        CharSequence contentText = "incoming chat  "+message.getBody()+"From  "+fromName;
                                                                        CharSequence contentTitle = "Notification Details...";
                                                                        SIMPLE_NOTFICATION_ID=ctx.getNotificationId(fromName);
                                                                        Log.e(TAG,fromName);
                                                                        notifyIntent.putExtra("name",fromName);
                                                                        Log.e(TAG,message.getBody());
                                                                        notifyIntent.putExtra("msg", message.getBody());
                                                                        notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
                                                                        PendingIntent intent =
                                                                                    PendingIntent.getActivity(MessageAlertService.this,SIMPLE_NOTFICATION_ID,
                                                                                                            notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);


                                                                        notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
                                                                        mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);

                                                            }


                                                }
                                    }

                        };
                        Log.e(TAG,"line no 151"+mConnection1);
                        mConnection1.addPacketListener(MessageLis, filter);

                        Log.i(TAG, "Received start id " + startId + ": " + intent);

                        return START_STICKY; // run until explicitly stopped.
            }

            public static boolean isRunning()
            {
                        return isRunning;
            }




}
ChatClient.java

package com.inception.smui;

import android.os.Messenger;

public class ChatClient {
           
            Messenger mMessenger;
            String filter;
            String id;
           
            public Messenger getmMessenger() {
                        return mMessenger;
            }
            public void setmMessenger(Messenger mMessenger) {
                        this.mMessenger = mMessenger;
            }
            public String getFilter() {
                        return filter;
            }
            public void setFilter(String filter) {
                        this.filter = filter;
            }
            public String getId() {
                        return id;
            }
            public void setId(String id) {
                        this.id = id;
            }

}
UserChatSession.java

package com.inception.dataparser;

import java.util.ArrayList;

public class UserChatSession {
           
            String chatid;
            public String getChatid() {
                        return chatid;
            }
            public void setChatid(String chatid) {
                        this.chatid = chatid;
            }
            public ArrayList<String> getChattext() {
                        return chattext;
            }
            public void setChattext(String chattext1) {
                        chattext.add(chattext1);
            }
            ArrayList<String> chattext=new ArrayList<String>();
           

}
NetworkService.java

public class NetworkService extends Service {

private static ApplicationManager mAppMgr;
            RegistrationRes res1;
            NetworkManager mntmngr;
// Target we publish for clients to send messages to IncomingHandler.
            final Messenger mMessenger = new Messenger(new IncomingHandler());

            //constants
            public static final int MSG_REGISTER_CLIENT = 1;
            public static final int MSG_UNREGISTER_CLIENT = 2;
            @Override
            public IBinder onBind(Intent intent) {
                        mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());
                        mntmngr=mAppMgr.getNetworkManager();
                        Log.e("Nareshg", "OnBind is called for intent" + intent.describeContents());
                        return mMessenger.getBinder();
            }

            /**
             * Class Name :IncomingHandler
             *
             * Parent Class :Handler
             *
             * Interfaces: None
             *
             * Description:Handler class for handling
             *
             *  incoming messages from client

             */
            class IncomingHandler extends Handler {
                        // Handler of incoming messages from clients.
                        /**
                         * Callback method to handle messages coming from client
                         *
                         */
                        @Override
                        public void handleMessage(Message msg) {
                                    switch (msg.what) {
                                    case MSG_REGISTER_CLIENT:
                                                mClients.add(msg.replyTo);
                                                Log.e(TAG+"client","added");
                                                break;
                                    case MSG_UNREGISTER_CLIENT:
                                                mClients.remove(msg.replyTo);
                                                Log.e(TAG+"client","removed");
                                                break;
                                    default:
                                                super.handleMessage(msg);
                                    }
                        }
            }

Chat.java     




package com.inception.smui;
/**
 * Class Name : Chat
 *
 * Parent Class :BaseClass
 *
 * Interfaces: None
 *
 * Description:This class displays chat window where users of app
   can chat.

 */

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.DefaultMessageEventRequestListener;
import org.jivesoftware.smackx.MessageEventManager;
import org.jivesoftware.smackx.MessageEventNotificationListener;
import org.jivesoftware.smackx.OfflineMessageManager;
import org.jivesoftware.smackx.workgroup.settings.OfflineSettings;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ServiceMessenger.R;
import com.inception.dataparser.UserChatSession;
import com.inception.dataprovider.DatabaseHelper;
import com.inception.network.MessageAlertService;
import com.inception.network.NetworkService;
import com.inception.sm.ApplicationManager;
import com.inception.sm.Globals;
import com.inception.sm.MyAppContext;


public class Chat extends BaseClass
{
            TextView mBuddynameTextView;
            ImageView mOnlinestatus;
            EditText mChatMsg;
            ListView mChatList;
            private ArrayList<String> mChatMsgList = new ArrayList<String>();
            private String TAG="Chat";
            private ArrayAdapter<String> mAdapter;
            private ArrayList<String> mTime=new ArrayList<String>();;
            final Messenger mMessenger = new Messenger(new IncomingHandler());
            Messenger mService = null;
           
            MyAppContext mCtx;

            SharedPreferences mRowid;
            public  SharedPreferences.Editor mRowidEditor;

            private ProgressDialog mProgDlg;
            private static final int INDETERMINATE = 0;
            private ArrayList<String> mStrings = new ArrayList<String>();
            boolean mIsBound;
            String mChatingPersonName;
            private Handler mHandler = new Handler();
            private XMPPConnection mConnection1;
            String mIncomingMsg;
            private Roster mRoster;

            private static ApplicationManager mAppMgr;
            private DatabaseHelper mDBHelper;
            Button mSend;
            int mChatHistoryCount=1;
            SQLiteDatabase mDataBase;
            UserChatSession mUserChatSession;
            String mFormattedDate;
            class IncomingHandler extends Handler {

                        /**
                         * Callback method to handle messages coming from server
                         *
                         */

                        @Override
                        public void handleMessage(android.os.Message msg) {
                                    Log.e(TAG,"UIAct handleMessage");
                                    switch (msg.what) {


                                    case MessageAlertService.MSG_AVAILABLE_SERVERMSG:
                                                Bundle b5=msg.getData();
                                                String from=b5.getString("msgfrom");
                                                Log.e(TAG,"from"+from);
                                                mIncomingMsg=b5.getString("msgbody");
                                                String timestamp=b5.getString("time");
                                                Log.e(TAG,"incomingmsg"+mIncomingMsg);
                                                if(mIncomingMsg!=null){
                                                           
                                                            mStrings.add(from +":"+mIncomingMsg);
                                                            mTime.add(timestamp);
                                                            mAdapter.notifyDataSetChanged();
                                                }
                                               
                                                break;
                                    default:
                                                super.handleMessage(msg);

                                    }
                        }
            }
            private ServiceConnection mConnection;
            /**
             * Callback method to get connection from server
             *
             */

            /** Acitivity life cycle method */

            @Override
            protected void onPause(){
                        super.onPause();

                        doUnbindService();
                        finish();
            }
            /** Acitivity life cycle method */

            @Override
            protected void onResume(){
                        super.onResume();

                        doBindService();
            }
            /** Called when the activity is first created. */
            @Override
            public void onCreate(Bundle savedInstanceState)
            {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.chat);
                        mDBHelper = new DatabaseHelper(this);
                        mDataBase = mDBHelper.getWritableDatabase();    
                        mAppMgr = ApplicationManager.getApplicationMgrInstance(this.getApplicationContext());
                        // chattitle= (TextView) findViewById(R.id.chatname);
                        mCtx = (MyAppContext)getApplicationContext();
                        mConnection1=mCtx.getXMPPConnection();

                        mSend=(Button)findViewById(R.id.send);
                        mChatMsg=(EditText) findViewById(R.id.userText);
                        mChatList=(ListView) findViewById(R.id.list);
                        mBuddynameTextView=(TextView) findViewById(R.id.tv);
                        mOnlinestatus=(ImageView) findViewById(R.id.status);
                        Intent i=getIntent();
                        mRowid=getSharedPreferences(Globals.PREFS_NAME, 0);


                        mChatingPersonName=i.getStringExtra("name");
                        Log.e(TAG,"name"+mChatingPersonName);
                        mUserChatSession =mCtx.getUserChatSeesion(mChatingPersonName);

                        Log.e(TAG,"userChatSession.getChattext()"+mUserChatSession.getChattext());
                        mIncomingMsg=i.getStringExtra("msg");

                        if(mIncomingMsg!=null){
                                    Log.e(TAG,mIncomingMsg);
                        }



                        Presence presence;
                        mRoster  = mCtx.getRoster1();
                        /** Roster listener that gets called when presence in roster buddy list is changed */
                       
                        RosterListener rl=new RosterListener(){               

                                    public void entriesAdded(Collection<String> arg0) {
                                                // TODO Auto-generated method stub
                                                mRoster.reload();
                                    }

                                    public void entriesDeleted(Collection<String> arg0) {
                                                // TODO Auto-generated method stub

                                    }

                                    public void entriesUpdated(Collection<String> arg0) {
                                                // TODO Auto-generated method stub

                                    }

                                    public void presenceChanged(Presence presence) {
                                                // TODO Auto-generated method stub
                                                //mListData.clear();
                                               
                                                Log.e(TAG,"AM IN PRESENCE CHANGE LISTENER");
                                                mRoster.reload();
                                                Collection<RosterEntry> entries = mRoster.getEntries();
                                                Log.e(TAG,"no of entries:"+entries.size());
                                                String entry=presence.getFrom();
                                                String user=entry.replaceAll("/Smack","").trim();
                                                presence = mRoster.getPresence(entry);

                                                Log.e(TAG,"entry.getName()"+entry+"presence.getType()"+presence.getType());

                                                if(presence.getType() == Presence.Type.available){
                                                            mOnlinestatus.refreshDrawableState();
                                                           
                                                            Bitmap bm= BitmapFactory.decodeResource(getResources(),R.drawable.online);
                                                            mOnlinestatus.setImageBitmap(bm);
                                                           
                                                }
                                                else if(presence.getType() == Presence.Type.unavailable){
                                                            mOnlinestatus.refreshDrawableState();
                                                            Bitmap bm= BitmapFactory.decodeResource(getResources(),R.drawable.offline);
                                                            mOnlinestatus.setImageBitmap(bm);
                                                }



                                    }
                        };
                       
                        //adding Roster listener to Roster
                       
                        mRoster.addRosterListener(rl);
                        mRoster.reload();
                        presence = mRoster.getPresence(mChatingPersonName);

                        mBuddynameTextView.setText(mChatingPersonName.replaceAll("@50.28.26.182","").trim());
                        Log.e(TAG,"presence.getType()"+presence.getType());
                        if(presence.getType() == Presence.Type.available){
                                    Bitmap bm= BitmapFactory.decodeResource(getResources(),R.drawable.online);
                                    mOnlinestatus.setImageBitmap(bm);
                        }
                        else if(presence.getType() == Presence.Type.unavailable)
                        {
                                    Bitmap bm= BitmapFactory.decodeResource(getResources(),R.drawable.offline);
                                    mOnlinestatus.setImageBitmap(bm);
                        }
                       
                       
                        /** Button onclick listener for sending sending message that is typed in edit text view */
                       
                        mSend.setOnClickListener(new View.OnClickListener(){

                                    @Override
                                    public void onClick(View v) {

                                                sendText();


                                    }


                        });
                        mAdapter = new MyCustomAdapter(this, R.layout.chattext, mStrings,mTime);
                        Log.e(TAG,"name"+mChatingPersonName.replaceAll("@50.28.26.182","").trim());
                        Log.e(TAG,"ctx.getmLoginName()"+mCtx.getmLoginName());
                       
                        /** DataBase Quering logic to retrieve chat history  */
                       
                        Cursor data3 = mDataBase.rawQuery("select *from ChatHistory",null);
                        int count= data3.getCount();
                        Log.e(TAG,"count"+count);
                        int noofrows=0;
                        if(count!=0){
                                    Cursor data2 = mDataBase.rawQuery("select message, time from ChatHistory where username="+"?"+"AND buddyname="+"?"+"order by rowid desc limit 10",new String[]{mCtx.getmLoginName().toString(),mChatingPersonName.replaceAll("@50.28.26.182","").trim()});
                                    if (data2!= null)
                                    {

                                                noofrows=data2.getCount();

                                                if (data2.moveToLast()){
                                                            do{
                                                                        String msg= data2.getString(data2.getColumnIndex("message"));
                                                                        String time1=data2.getString(data2.getColumnIndex("time"));
                                                                        Log.e(TAG,"msg"+msg);
                                                                        Log.e(TAG,"time"+time1);
                                                                        mTime.add(time1);
                                                                        mStrings.add(msg);
                                                                        mAdapter.notifyDataSetChanged();
                                                            }while(data2.moveToPrevious());
                                                }
                                    }
                                    data2.close() ;
                        }
                        data3.close() ;
                        Log.e(TAG,"mStrings.size()"+ mStrings.size());
                        /*         if(userChatSession.getChattext().size()!=0){
            for( int j=0;j<userChatSession.getChattext().size();j++){
                        mStrings.add(userChatSession.getChattext().get(j));
                         mAdapter.notifyDataSetChanged();
                         Log.e(TAG," mAdapter.add(userChatSession.getChattext().get(j))"+ userChatSession.getChattext().get(j));
            }

        }*/
                        /* if(incomigmsg!=null)
        userChatSession.setChattext(name+":"+ incomigmsg);
        if(incomigmsg!=null){
        mAdapter.add(name +":"+incomigmsg);
        }*/
                        Button loadMoreButton=new Button(Chat.this);
                        if(noofrows!=0)
                                    mChatList.addHeaderView(loadMoreButton,null,true);
                        loadMoreButton.setText("Load More");

                        /** Button onclick listener for LoadMore option to load more chat history form local db*/
                        loadMoreButton.setOnClickListener(new View.OnClickListener(){

                                    @Override
                                    public void onClick(View v) {
                                                Log.e(TAG,"BUTTON CLICKED");
                                                ((Button) v).setText("Load More");

                                                Cursor data3 = mDataBase.rawQuery("select *from ChatHistory",null);
                                                int count= data3.getCount();
                                                data3.close();

                                                Log.e(TAG,"count"+count);
                                                Cursor data4 = mDataBase.rawQuery("select rowid from ChatHistory",null);
                                                if (data4!= null)
                                                {



                                                            if (data4.moveToFirst()){
                                                                        do{
                                                                                    String rowid= data4.getString(data4.getColumnIndex("rowid"));
                                                                                    Log.e(TAG,"rowid"+rowid);
                                                                        }while(data4.moveToNext());
                                                            }
                                                }
                                                data4.close();
                                                if(count!=0){

                                                            Cursor data2 = mDataBase.rawQuery("select message, time from ChatHistory where username="+"?"+"AND buddyname="+"?"+"order by rowid desc  limit 10 offset "+(mChatHistoryCount*10),new String[]{mCtx.getmLoginName().toString(),mChatingPersonName.replaceAll("@50.28.26.182","").trim()});

                                                            int rowcount= data2.getCount();

                                                            Log.e(TAG,"rowcount"+rowcount);
                                                            if(rowcount!=0){
                                                                        //mStrings.clear();
                                                                        //mAdapter.notifyDataSetChanged();
                                                                        if (data2!= null)
                                                                        {



                                                                                    if (data2.moveToFirst()){
                                                                                                do{
                                                                                                            String msg= data2.getString(data2.getColumnIndex("message"));
                                                                                                            mFormattedDate=data2.getString(data2.getColumnIndex("time"));
                                                                                                            Log.e(TAG,"msg in load more"+msg);
                                                                                                            Log.e(TAG,"time"+mFormattedDate);

                                                                                                            mStrings.add(0,msg);
                                                                                                            mTime.add(0,mFormattedDate);
                                                                                                            mAdapter.notifyDataSetChanged();
                                                                                                }while(data2.moveToNext());
                                                                                    }
                                                                        }
                                                                        mChatHistoryCount++;
                                                                        Log.e(TAG,"row val"+mChatHistoryCount);
                                                                        data2.close() ;
                                                            }
                                                            else
                                                                        ((Button) v).setText("No More");
                                                }
                                                data3.close() ;
                                    }

                        });

                        mChatList.setAdapter(mAdapter);
                        mChatList.setDivider(null);
                        mChatList.setDividerHeight(0);


                        /*  PacketListener MessageLis = new PacketListener(){
                                    public void processPacket(Packet packet) {
                                final Message message = (Message) packet;
                                if (message.getBody() != null) {
                                    final String fromName = StringUtils.parseBareAddress(message.getFrom());
                                    Log.i(TAG, "Got text [" + message.getBody() + "] from [" + fromName + "]");
                                    //messages.add(fromName + ":");
                                    messages.add(message.getBody());
                                    // Add the incoming message to the list view
                                    mHandler.post(new Runnable() {
                                        public void run() {
                                           // setListAdapter();
                                        //     for(int i=0;i<messages.size();i++){
                                                mAdapter.add(fromName +":"+message.getBody());
                                                //}
                                        }
                                    });
                                }
                            }

                };
                PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
        mConnection1.addPacketListener(MessageLis, filter);*/

            }

            /** Method that gets called when user click on send button after  he enters text in edittext view */

            private void sendText() {

                        String to =mChatingPersonName;
                        String text = mChatMsg.getText().toString();

                        if(mConnection1==null || mConnection1.isConnected()==false || mConnection1.isAuthenticated() == false)
                                    return;

                        Message msg = new Message(to, Message.Type.chat);


                        //
                        ContentValues values = new ContentValues();
                        values = new ContentValues();
                        values.put("username",mCtx.getmLoginName());
                        String buddyname1=mChatingPersonName.replaceAll("@50.28.26.182","").trim();
                        values.put("buddyname",buddyname1);
                        values.put("message","me: "+text);
                        values.put("time","sent at"+mFormattedDate);
                        mDataBase.insert("ChatHistory", null,values);
                        Cursor data3 = mDataBase.rawQuery("select rowid from ChatHistory",null);
                        String rowid=null;

                        String deleterowid=mRowid.getString("firstrowid","1");
                        Log.e(TAG,"mRowid"+mRowid.getString("firstrowid","1"));
                        if(data3.getCount()>50){
                                    int noofdeletedrows=data3.getCount()-50;
                                    Log.e(TAG,"noofdeletedrows"+noofdeletedrows);
                                    int daletedrow=Integer.parseInt(deleterowid);
                                    for(int i=1;i<=noofdeletedrows;i++){

                                                mDataBase.delete("ChatHistory","rowid= "+daletedrow ,null);
                                                Log.e(TAG,"daletedrow"+daletedrow);
                                                daletedrow++;

                                    }
                        }
                        Cursor data4 = mDataBase.rawQuery("select rowid,time from ChatHistory limit 1",null);
                        if (data4!= null)
                        {



                                    if (data4.moveToFirst()){
                                                do{
                                                            rowid= data4.getString(data4.getColumnIndex("rowid"));
                                                            String firstrowtime=data4.getString(data4.getColumnIndex("time"));
                                                            Log.e(TAG,"rowid"+rowid);
                                                            Log.e(TAG,"firstrowtim"+firstrowtime);

                                                }while(data4.moveToNext());
                                    }
                        }
                        Log.e(TAG,"rowid"+rowid);
                        Cursor data5 = mDataBase.rawQuery("select rowid from ChatHistory",null);
                        if (data5!= null)
                        {



                                    if (data5.moveToFirst()){
                                                do{
                                                            String rowid1= data5.getString(data5.getColumnIndex("rowid"));
                                                            Log.e(TAG,"rowid1"+rowid1);
                                                }while(data5.moveToNext());
                                    }
                        }
                        mRowidEditor=mRowid.edit();
                        mRowidEditor.putString("firstrowid",rowid);
                        mRowidEditor.commit();
                        Log.e(TAG,"mRowid in chat"+mRowid.getString("firstrowid","1"));
                        Calendar c = Calendar.getInstance();
                        System.out.println("Current time => "+c.getTime());

                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        mFormattedDate = df.format(c.getTime());


                        Log.e(TAG,"System.currentTimeMillis()"+mFormattedDate);


                        Log.i(TAG, "Sending text [" + text + "] to [" + to + "]");

                        msg.setBody(text);
                        MessageEventManager.addNotificationsRequests(msg, true, true, true, true);
                        mConnection1.sendPacket(msg);
                        mChatMsgList.add(to + ":");
                        mChatMsgList.add(text);
                        mUserChatSession.setChattext("me: "+text);
                        mStrings.add("me: "+text);
                        mTime.add("sent at"+mFormattedDate);
                        mAdapter.notifyDataSetChanged();
                       
                        mChatMsg.setText(null);
            }

/** Method to bind to the service */
            void doBindService() {
                        // Establish a connection with the service.  We use an explicit
                        // class name because there is no reason to be able to let other
                        // applications replace our component.
                        mConnection = new ServiceConnection() {

                                    public void onServiceConnected(ComponentName className, IBinder service) {
                                                mService = new Messenger(service);
                                                Log.e(TAG,"binding to service in ServiceConnection for chat msg");

                                                try {
                                                            Log.e(TAG,"UIAct onServiceConnected");




                                                            android.os.Message msg = android.os.Message.obtain(null, NetworkService.MSG_REGISTER_CLIENT);
                                                            Bundle b=new Bundle();

                                                            msg.replyTo = mMessenger;

                                                            b.putString("filter","one");
                                                            b.putString("id",mChatingPersonName);
                                                            msg.setData(b);
                                                            mService.send(msg);


                                                            Log.d(TAG,"connecting to server res");
                                                }


                                                catch (RemoteException e) {
                                                            // In this case the service has crashed before we could even do anything with it
                                                }

                                    }

                                    /**
                                     * Callback method to get disconnect from server
                                     *
                                     */

                                    public void onServiceDisconnected(ComponentName className) {
                                                // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
                                                mService = null;
                                                Log.e(TAG,"UIAct onServiceDisconnected");
                                    }
                        };
                        bindService(new Intent(Chat.this,
                                                MessageAlertService.class), mConnection, Context.BIND_AUTO_CREATE);
                        mIsBound = true;

            }
            /** Method to un bind to the service */
            void doUnbindService() {
                        if (mIsBound) {
                                    // If we have received the service, and hence registered with
                                    // it, then now is the time to unregister.
                                    if (mService != null) {
                                                try {
                                                            android.os.Message msg = android.os.Message.obtain(null,
                                                                                    NetworkService.MSG_UNREGISTER_CLIENT);
                                                            msg.replyTo = mMessenger;
                                                            mService.send(msg);
                                                } catch (RemoteException e) {
                                                            // There is nothing special we need to do if the service
                                                            // has crashed.
                                                }
                                    }

                                    // Detach our existing connection.
                                    unbindService(mConnection);
                                    mIsBound = false;

                        }
            }
/** Activity life cycle method  */
                        @Override
            public void onDestroy() {
                        Log.i(TAG,"Chat onDestroy Called");
                        super.onDestroy();
                        try {
                                    unbindService(mConnection);
                                    mDataBase.close();
                        } catch (Throwable t) {

                        }
            }
           
            /**This class is used to customize the listview appearence */
           
            public class MyCustomAdapter extends ArrayAdapter<String> {
                        ArrayList<String> time1;
                        public MyCustomAdapter(Context context, int textViewResourceId,
                                                ArrayList<String> mStrings, ArrayList<String> time) {
                                    super(context, textViewResourceId, mStrings);
                                    time1=time;
                                    // TODO Auto-generated constructor stub
                        }

                        @Override
                        public View getView(int position, View convertView, ViewGroup parent) {
                                    // TODO Auto-generated method stub
                                    //return super.getView(position, convertView, parent);

                                    View row = convertView;

                                    if(row==null){
                                                LayoutInflater inflater=getLayoutInflater();
                                                row=inflater.inflate(R.layout.chattext, parent, false);
                                    }

                                    TextView msg=(TextView)row.findViewById(R.id.post);
                                    TextView timesent=(TextView)row.findViewById(R.id.time);

                                    ImageView icon=(ImageView)row.findViewById(R.id.iv);
                                    msg.setText(mStrings.get(position));
                                    timesent.setText(time1.get(position));
                                    if (mStrings.get(position).contains("me")){
                                                icon.setImageResource(R.drawable.icon);
                                    }
                                    else{
                                                icon.setImageResource(R.drawable.android_waving);
                                    }

                                    return row;
                        }
            }
}
Chat.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:paddingLeft="8dip"
    android:paddingRight="8dip"
   android:background="#FFFFFF">
    <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="8dip"
    android:paddingRight="8dip"
    android:background="#FFFFFF"
    >
    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="8dip"
    android:paddingRight="8dip"
    android:background="#FFFFFF"
    >
    <ImageView android:id="@+id/status" android:gravity="center_vertical"
                        android:layout_width="wrap_content" android:layout_height="wrap_content"
                        android:src="@drawable/icon"
                         />      
    <TextView android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
      
        android:textColor="#333399"
        android:textSize="20sp"/>
          </LinearLayout>
    <ListView android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="400dip"
        android:layout_weight="1"
        android:stackFromBottom="true"
        android:transcriptMode="normal"/>
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_margin="2dp" >
<EditText android:id="@+id/userText"
        android:layout_width="210dip"
        android:layout_height="60dip"
         android:maxLength="300" />
            <Button android:id="@+id/send" android:gravity="center_vertical"
                        android:layout_width="90dip" android:layout_height="60dip"
                       
                        android:text="Send"
                        android:textSize="@dimen/menu_buttons_text_size"
                                    android:textColor="@color/menu_buttons" android:textStyle="bold"
                        android:layout_toRightOf="@+id/userText" />  

</RelativeLayout>
   
        </LinearLayout>
</LinearLayout>

Chattext.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:orientation="horizontal"
            android:background="@color/list_bg" >
<ImageView android:id="@+id/iv" android:gravity="center_vertical"
                        android:layout_width="wrap_content" android:layout_height="50dp"
                        android:src="@drawable/icon"
                         />      
                         <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:orientation="vertical" >
            <TextView android:id="@+id/post" android:gravity="center_vertical"
                        android:layout_width="wrap_content" android:layout_height="wrap_content"
                        android:textSize="20sp"
                        android:textColor="#000000" 
                         />
                        <TextView android:id="@+id/time" android:gravity="center_vertical"
                        android:layout_width="wrap_content" android:layout_height="wrap_content"
                        android:textSize="15sp"
                        android:textColor="#000fff" 
                         />      
</LinearLayout>
</LinearLayout>

Chatlist.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
 android:background="@drawable/bk_gnd"
>
            <ListView android:id="@+id/chatlist1"
                      android:layout_width="fill_parent"
                      android:layout_height="wrap_content"
                      android:layout_weight="1">
            </ListView>
           
</LinearLayout>


How to send SMS
package com.inception.smui;

import com.ServiceMessenger.R;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMS extends Activity
{
            Button btnSendSMS;
            EditText txtPhoneNo;
            EditText txtMessage;
           
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sms);       
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);
       
        /*
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.putExtra("sms_body", "Content of the SMS goes here...");
        sendIntent.setType("vnd.android-dir/mms-sms");
        startActivity(sendIntent);
        */
               
        btnSendSMS.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {                      
                        String phoneNo = txtPhoneNo.getText().toString();
                        String message = txtMessage.getText().toString();                  
                if (phoneNo.length()>0 && message.length()>0)               
                 //   sendSMS(phoneNo, message);    
                        Toast.makeText(getBaseContext(),
                            " message sent.",
                            Toast.LENGTH_SHORT).show();
                else
                        Toast.makeText(getBaseContext(),
                        "Please enter both phone number and message.",
                        Toast.LENGTH_SHORT).show();
            }
        });       
    }
   
    //---sends a SMS message to another device---
  /*  private void sendSMS(String phoneNumber, String message)
    {     
            /*
        PendingIntent pi = PendingIntent.getActivity(this, 0,
                new Intent(this, test.class), 0);               
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, pi, null);       
        */
           
  /*       String SENT = "SMS_SENT";
            String DELIVERED = "SMS_DELIVERED";
           
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);
       
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);
           
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
                                    @Override
                                    public void onReceive(Context arg0, Intent arg1) {
                                                switch (getResultCode())
                                                {
                                                    case Activity.RESULT_OK:
                                                                Toast.makeText(getBaseContext(), "SMS sent",
                                                                                    Toast.LENGTH_SHORT).show();
                                                                break;
                                                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                                                                Toast.makeText(getBaseContext(), "Generic failure",
                                                                                    Toast.LENGTH_SHORT).show();
                                                                break;
                                                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                                                                Toast.makeText(getBaseContext(), "No service",
                                                                                    Toast.LENGTH_SHORT).show();
                                                                break;
                                                    case SmsManager.RESULT_ERROR_NULL_PDU:
                                                                Toast.makeText(getBaseContext(), "Null PDU",
                                                                                    Toast.LENGTH_SHORT).show();
                                                                break;
                                                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                                                                Toast.makeText(getBaseContext(), "Radio off",
                                                                                    Toast.LENGTH_SHORT).show();
                                                                break;
                                                }
                                    }
        }, new IntentFilter(SENT));
       
        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
                                    @Override
                                    public void onReceive(Context arg0, Intent arg1) {
                                                switch (getResultCode())
                                                {
                                                    case Activity.RESULT_OK:
                                                                Toast.makeText(getBaseContext(), "SMS delivered",
                                                                                    Toast.LENGTH_SHORT).show();
                                                                break;
                                                    case Activity.RESULT_CANCELED:
                                                                Toast.makeText(getBaseContext(), "SMS not delivered",
                                                                                    Toast.LENGTH_SHORT).show();
                                                                break;                                                           
                                                }
                                    }
        }, new IntentFilter(DELIVERED));       
           
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);               
    } */  
}
Sms.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Enter the phone number of recipient"
        />    
    <EditText
        android:id="@+id/txtPhoneNo" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"       
        />
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"        
        android:text="Message"
        />    
    <EditText
        android:id="@+id/txtMessage" 
        android:layout_width="fill_parent"
        android:layout_height="150px"
        android:gravity="top"        
        />         
    <Button
        android:id="@+id/btnSendSMS" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />   
</LinearLayout>