Chat window Issues in android
<p>Actually i am working on livechat application i have four part for my application.after login screen there is open a window in which i am showing the list of visitor visiting the site.my data of the list is updating each after 3 seconds.this part is working fine.the list the list row i am showing the data like ipaddress,statustext,noofvisit,buttontext,durationtime extra.</p>

<p>When any new chat request come(list refresh if status text is chatrequest) and if i click on accept the chat accepted and call go to server status change and a new window will open chat window.this part is also working fine.the issue is for chat window for sending message a call go to server and for response message a call also go.</p>

<p>My issue is that the in chatting part 5 or 6 message are going and receiving after that i am getting null pointer exception.In chat window i am using code like following</p>

<pre><code>    import java.util.HashMap;
    import java.util.Timer;
    import java.util.TimerTask;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Gravity;
    import android.view.KeyEvent;
    import android.view.LayoutInflater;

    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;


    public class Chat extends Activity   {



        private static final String TAG = "Chat";
        private static final boolean D = true;
        private final int NOTIFICATION_ID = 1012;

        private NotificationManager mNotificationManager;

        private String response;
        private String chatMsg,previousChatMsg,sender,textchat,lastnum;
        private int position;
        public static String message,receivedmsg;
        // Layout Views
        private ListView    mConversationView;
        private EditText    mOutEditText;
        private Button      mSendButton,header,showall;
        private String delimiter,delimiter1,delimiter2,delimiter3;
        private boolean IsSoundEnable;

        // Array adapter for the conversation thread
        private ArrayAdapter&lt;String&gt; mConversationArrayAdapter;
        private TextView view;
        private String[] valueArray,valueArray1,messagelist,temp1;
        private String strchattext,strResponseFirst,strMsgNewNum,strMsgOldNum;

        // Member object for the chat services
        private static final String DEB_TAG = "Error Message";

        final static int PACKET_CAME = 1;
        final static int TOAST1  = 2;
        //user name
        private String mUserName = "admin";
        ServerThread    myThread;
        private Timer timer = new Timer();
        private ImageView view2;
        private LinearLayout view1;




        public void setUserName(String userName){
            mUserName = userName;
        }

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.chat);

            header = (Button) findViewById(R.id.btnheadertext);

            showall = (Button) findViewById(R.id.btnshowall);

            view1 = (LinearLayout) findViewById(R.id.LinearLayout01);

            view2 = (ImageView) findViewById(R.id.ImageView01);



            if(D) Log.e(TAG, "+++ ON CREATE +++");

            Bundle extras = getIntent().getExtras();
            if (extras != null) {

                extras.getString(Visitor.IPText.get(position));                     
                extras.getString("From");           
                position=extras.getInt("Position");
                extras.getString(VisitorDetail.name);                       
                setTitle("Messaging with " + Visitor.IPText.get(position));


            }

            //------------------Set IP Address on header------------------------

            header.setText(Visitor.IPText.get(position));



            //---------------------List adapter-------------------------
            mConversationArrayAdapter = new ArrayAdapter&lt;String&gt;(this, R.layout.message);
            mConversationView = (ListView) findViewById(R.id.in);
            mConversationView.setAdapter(mConversationArrayAdapter);


            // Initialize the compose field with a listener for the return key
            mOutEditText = (EditText) findViewById(R.id.edit_text_out);


            // Initialize the send button with a listener that for click events
            mSendButton = (Button) findViewById(R.id.button_send);



            //-----------------------Send button click event--------------------------

            mSendButton.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if(D) Log.e(TAG, "[sendButton clicked]");
                    // Send a message using content of the edit text widget
                    view = (TextView) findViewById(R.id.edit_text_out);
                    message = view.getText().toString();

                    try{
                        setupChat();
                        postMessage();
                    }
                    catch(Exception e){
                        e.printStackTrace();
                    }

                    TimerTask timerTask = new TimerTask()
                    {
                        @Override
                        public void run()
                        {
                            getResponseMessage(Visitor.SessionText.get(position));

                        }


                    };
                    timer.schedule(timerTask, 10000);
                    new StringBuffer("");
                }



            });


        }

        public void onStart() {
            super.onStart();
            if(D) Log.e(TAG, "++ ON START ++");



        }

        //--------------------Start Chatting from here when click on send button-----------------------------------

            private void setupChat() {
                // TODO Auto-generated method stub


                final String url = "http://sa.live2support.com/cpn//wz-amessub.php?";
                final HashMap&lt;String, String&gt; postParameters = new HashMap&lt;String, String&gt;();

                postParameters.put("say",message);              
                postParameters.put("csesid",Visitor.SessionText.get(position)); 
                postParameters.put("adminid", Main.loginId.getText().toString());
                postParameters.put("sid", Main.siteId.getText().toString());


                Runnable searchThread = new Runnable(){

                    public void run() {
                        // TODO Auto-generated method stub

                        try {
                            response = CustomHttpClient.executeHttpPost1(url,postParameters);

                            Log.i(DEB_TAG, "Requesting to server"+response);
                            //CustomHttpClient.getResponseInString(response );

                            System.out.println("Output of httpResponse:"+response);





                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        if(response!=null){

                            runOnUiThread(new Runnable() {

                                public void run() {

                                    if(CustomHttpClient.Response.getStatusLine().getStatusCode()==200){
                                        // TODO Auto-generated method stub

                                        System.out.println(response);
                                        playsound();


                                    }
                                    else{

                                        setupChat();
                                    }
                                }




                            });
                        }


                    }


                };

                Thread thread =  new Thread(null, searchThread, "MagentoBackground");
                thread.start();


            }

            private void postMessage() {
                // TODO Auto-generated method stub

                String theNewMessage = view.getText().toString();
                try{
                    mConversationArrayAdapter.add(mUserName+":"+theNewMessage);
                    view.setText("");
                }catch(Exception e){
                    e.printStackTrace();
                }


            }





        //---------------------Getting the response message of visitor-----------------------------

            private void getResponseMessage(String session){

                final String url = "http://sa.live2support.com/cpn/wz-achats.php?";
                final HashMap&lt;String, String&gt; postParameters = new HashMap&lt;String, String&gt;();

                try{
                    postParameters.put("uname", VisitorDetails.name);
                    postParameters.put("adminid", Main.loginId.getText().toString());
                    postParameters.put("sid", Main.siteId.getText().toString());
                    postParameters.put("csesid",session);   

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



                Runnable searchThread = new Runnable(){

                    public void run() {
                        // TODO Auto-generated method stub

                        try {
                            response = CustomHttpClient.executeHttpPost1(url,postParameters);

                            Log.i(DEB_TAG, "Requesting to server"+response);
                            //CustomHttpClient.getResponseInString(response );

                            delimiter = "&lt;l2s_type_split&gt;";
                            delimiter1= "&lt;l2s_blk&gt;";
                            delimiter2 = "&lt;l2s_ln&gt;";
                            delimiter3 = "&lt;nsp&gt;";

                            valueArray = response.split(delimiter);
                            lastnum = valueArray[1];
                            System.out.println("lastnum is"+lastnum);
                            if(valueArray.length==3){

                                strResponseFirst = valueArray[0];
                                System.out.println("first response================"+strResponseFirst);

                                if(!(strResponseFirst.equalsIgnoreCase(""))){

                                    valueArray1 = strResponseFirst.split(delimiter1);

                                    if(valueArray1.length!=0){

                                        strchattext = valueArray1[0];
                                        strMsgNewNum = valueArray1[1];
                                        strMsgOldNum = valueArray1[2];

                                        System.out.println("strchattext=================="+valueArray1[0]+"\n"+"strMsgNewNum======================"+strMsgNewNum+"\n"+"strOldNum============"+strMsgOldNum);

                                        temp1 = strchattext.split(delimiter2);

                                        System.out.println("value of temp variable"+temp1[1]);
                                        System.out.println("value of strchatmsg============="+valueArray1[0]+"\n"+"value of new num"+valueArray1[1]+"\n"+"value of old num=="+strMsgOldNum);

                                        for(int i=0;i&lt;temp1.length;i++){

                                            System.out.println("temp value are============="+temp1[i]);
                                        }

                                        for(int i=0;i&lt;temp1.length;i++){

                                            String strToAppend = temp1[i];

                                            messagelist = strToAppend.split(delimiter3);

                                            if(messagelist.length==3){

                                                chatMsg = messagelist[2];

                                                previousChatMsg = temp1[0];

                                                sender = messagelist[0];

                                                System.out.println("previouschatmsg=========="+previousChatMsg);
                                                System.out.println("chatmsg=========="+chatMsg);
                                                System.out.println("name of sender=========="+sender);
                                            }


                                            else if(sender.equals(Main.loginId.getText().toString())){

                                                textchat = messagelist[0];

                                                System.out.println("textchat message are the followings"+textchat);
                                            }

                                            else {
                                                if(sender.equals("notice")){
                                                    String textchat = messagelist[0];
                                                }
                                            }

                                            System.out.println("chattext============="+messagelist[0]);
                                        }






                                        if(chatMsg.equals("chat close by user")){
                                            getResponseMessage(Visitor.SessionText.get(position));

                                        }
                                    }

                                }
                            }



                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        if(response!=null){

                            runOnUiThread(new Runnable() {

                                public void run() {
                                    // TODO Auto-generated method stub
                                    if(CustomHttpClient.Response.getStatusLine().getStatusCode()==200){

                                        try{

                                            if(chatMsg!=null)
                                                handleMessage(chatMsg);
                                        }catch(Exception e){
                                            e.printStackTrace();
                                        }
                                        TimerTask timerTask = new TimerTask()
                                        {
                                            @Override
                                            public void run()
                                            {
                                                playsound();
                                                triggerNotification(chatMsg);

                                            }






                                        };
                                        timer.schedule(timerTask, 10000);
                                    }

                                    playsound();

                                }


                            });
                        }

                    }



                };

                Thread thread =  new Thread(null, searchThread, "MagentoBackground");
                thread.start();

            }

            //--------------------For seeing message if any exists--------------------

            private void handleMessage(String receivedmsg) {
                // TODO Auto-generated method stub
                String receivemsg = receivedmsg;
                try{
                    mConversationArrayAdapter.add(Visitor.IPText.get(position)+":"+receivemsg);
                    view.setText("");

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

            }

            //----------Show notification when any response message occurs--------------------

            private void triggerNotification(String chatMsg) {
                // TODO Auto-generated method stub
                CharSequence title = "A new Message arrived";

                NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
                Notification notification = new Notification(R.drawable.chat, chatMsg, System.currentTimeMillis());
                notification.flags |= Notification.FLAG_AUTO_CANCEL;

                Intent notificationIntent = new Intent(this, Chat.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

                notification.setLatestEventInfo(Chat.this, title, chatMsg, pendingIntent);
                notificationManager.notify(NOTIFICATION_ID, notification);
            }

            public void completed()    {
                //remove the notification from the status bar
                mNotificationManager.cancel(NOTIFICATION_ID);
            }



            private void playsound() {
                // TODO Auto-generated method stub
                MediaPlayer mp = MediaPlayer.create(this, R.raw.chatmessage);
                if(IsSoundEnable){
                    mp.start();
                }

            }



            //--------------Called this method when send any message--------------



        //-------------------For closing the chat------------------------

        private void closechat() {
            // TODO Auto-generated method stub

            final String url = "http://sa.live2support.com/cpn/wz-action.php?";
            final HashMap&lt;String, String&gt; postParameters = new HashMap&lt;String, String&gt;();

            postParameters.put("action", "endchatcl");
            postParameters.put("csesid",Visitor.SessionText.get(position));         
            postParameters.put("sid", Main.siteId.getText().toString());
            postParameters.put("adminid", Main.loginId.getText().toString());

            Runnable searchThread = new Runnable(){

                public void run() {
                    // TODO Auto-generated method stub

                    try {
                        response = CustomHttpClient.executeHttpPost1(url,postParameters);

                        Log.i(DEB_TAG, "Requesting to server"+response);
                        //CustomHttpClient.getResponseInString(response );

                        System.out.println("Output of httpResponse:"+response);





                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(response!=null){

                        runOnUiThread(new Runnable() {

                            public void run() {
                                // TODO Auto-generated method stub

                                System.out.println(response);
                                showCloseAlert();


                            }





                        });
                    }

                }


            };

            Thread thread =  new Thread(null, searchThread, "MagentoBackground");
            thread.start();

        }

        //------------------For showing the chat closing alert--------------------------------

        private void showCloseAlert() {
            // TODO Auto-generated method stub
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            final AlertDialog alert = builder.create();
            alert.setTitle("Are You sure want to close chat");

            alert.setButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    //startActivity(new Intent(CreateAccount.this,CreateAccount.class));
                    alert.dismiss();

                }
            });

            alert.show();
        }




        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK &amp;&amp; event.getRepeatCount() == 0) {          
                finish();
                return true;    
            }
            return super.onKeyDown(keyCode, event);
        }


    }
</code></pre>

<p>and the logcat is like the following...</p>

<pre><code>03-03 14:33:06.507: W/System.err(636): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
03-03 14:33:06.527: W/System.err(636):  at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
03-03 14:33:06.527: W/System.err(636):  at java.util.ArrayList.get(ArrayList.java:311)
03-03 14:33:06.547: W/System.err(636):  at com.live2support.Chat.setupChat(Chat.java:189)
03-03 14:33:06.547: W/System.err(636):  at com.live2support.Chat.access$2(Chat.java:181)
03-03 14:33:06.557: W/System.err(636):  at com.live2support.Chat$1.onClick(Chat.java:142)
03-03 14:33:06.557: W/System.err(636):  at android.view.View.performClick(View.java:2408)
03-03 14:33:06.557: W/System.err(636):  at android.view.View$PerformClick.run(View.java:8816)
03-03 14:33:06.568: W/System.err(636):  at android.os.Handler.handleCallback(Handler.java:587)
03-03 14:33:06.568: W/System.err(636):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-03 14:33:06.568: W/System.err(636):  at android.os.Looper.loop(Looper.java:123)
03-03 14:33:06.568: W/System.err(636):  at android.app.ActivityThread.main(ActivityThread.java:4627)
03-03 14:33:06.578: W/System.err(636):  at java.lang.reflect.Method.invokeNative(Native Method)
03-03 14:33:06.578: W/System.err(636):  at java.lang.reflect.Method.invoke(Method.java:521)
03-03 14:33:06.578: W/System.err(636):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-03 14:33:06.578: W/System.err(636):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-03 14:33:06.578: W/System.err(636):  at dalvik.system.NativeStart.main(Native Method)
03-03 14:33:07.237: E/AndroidRuntime(636): FATAL EXCEPTION: Timer-2
03-03 14:33:07.237: E/AndroidRuntime(636): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
03-03 14:33:07.237: E/AndroidRuntime(636):  at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
03-03 14:33:07.237: E/AndroidRuntime(636):  at java.util.ArrayList.get(ArrayList.java:311)
03-03 14:33:07.237: E/AndroidRuntime(636):  at com.live2support.Chat$1$1.run(Chat.java:154)
03-03 14:33:07.237: E/AndroidRuntime(636):  at java.util.Timer$TimerImpl.run(Timer.java:289)
03-03 14:33:10.806: W/System.err(758): Caused by: java.lang.NullPointerException
</code></pre>

<p>my code and logcat link is also can be see at the link given below.</p>

<p><a href="http://www.coderanch.com/t/569227/Android/Mobile/Chat-window-Issues-android#2586996" rel="nofollow">http://www.coderanch.com/t/569227/Android/Mobile/Chat-window-Issues-android#2586996</a></p>
