sjizl.com.ChatActivity.java Source code

Java tutorial

Introduction

Here is the source code for sjizl.com.ChatActivity.java

Source

/*******************************************************************************
 * Copyright 2011-2013 Sergey Tarasevich
 *
 * 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.
 *******************************************************************************/
package sjizl.com;

import static sjizl.com.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static sjizl.com.CommonUtilities.EXTRA_MESSAGE;
import static sjizl.com.CommonUtilities.options;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;

import android.graphics.AvoidXfermode.Mode;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;

import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;

import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;

import android.widget.ImageView;
import android.widget.LinearLayout;

import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;

import android.widget.TextView;
import android.widget.Toast;

import sjizl.com.libary.UserFunctions;

import com.google.android.gcm.GCMRegistrar;
import com.ipaulpro.afilechooser.utils.FileUtils;

import com.navdrawer.SimpleSideDrawer;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketConnectionHandler;
import de.tavendo.autobahn.WebSocketException;

public class ChatActivity extends AbsListViewBaseActivity implements AsyncDelegate {
    private static final String LOG_TAG = null;
    private String[] tabs = { "Top Rated", "Games", "Movies" };
    ItemAdapter aaa;
    LinearLayout right_lin, left_lin, middle_lin, left_lin1, left_lin2, left_lin3, left_lin4, smile_lin, ber_lin,
            smiles_layout, photosend_lin;
    private ActionBar actionBar;
    TextView textView1_bgtext, textView2_under_title;
    EditText mNewMessage;
    SharedPreferences sp;
    private static final int SELECT_FILE1 = 1;
    ImageView smilbtn;
    String oldvalue = "";
    int orig_width_underlayout_list, orig_height_underlayout_list;
    ViewPager viewPager_smiles;
    int smiles_pressed = 1;
    int width_underlayout, height_underlayout;
    LinearLayout underlayout;
    UserFunctions userFunctions;
    ArrayList<getPhotos> ArrChatLines = new ArrayList<getPhotos>();
    String is_typing_name;
    HttpEntity resEntity;
    AlertDialogManager alert = new AlertDialogManager();
    ProgressBar progressBar_hole;
    ImageView imageView2_dashboard, imageView1_logo, imageView_bericht, photosend;
    String[] smiles_url, smiles_short, laatste_tijd;
    String[] laatste_bericht;
    String foto_num, foto, username, password, mybmp2, user, naam, bericht, user_foto_num, user_foto, pid, pid_user;
    Drawable d1, d2;
    int mScrollState, position_hole;
    ProgressDialog myPd_ring;
    InputMethodManager imm;
    String ber_todb;

    public void hideSoftKeyboard() {
        if (getCurrentFocus() != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    public void showSoftKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        // view.requestFocus();
        inputMethodManager.showSoftInput(view, 0);
    }

    @Override
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
        setIntent(intent);//needed so that getIntent() doesn't return null inside onResume()
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (CommonUtilities.isInternetAvailable(getApplicationContext())) //returns true if internet available
        {

            SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
            pid = sp.getString("pid", null);
            naam = sp.getString("naam", null);
            username = sp.getString("username", null);
            password = sp.getString("password", null);
            foto = sp.getString("foto", null);
            foto_num = sp.getString("foto_num", null);
            Bundle bundle = getIntent().getExtras();
            pid_user = bundle.getString("pid_user");
            user = bundle.getString("user");
            user_foto_num = bundle.getString("user_foto_num");
            user_foto = bundle.getString("user_foto");

            // Toast.makeText(getApplicationContext(), "pid_user"+pid_user, Toast.LENGTH_SHORT).show();

            if (user.equalsIgnoreCase(naam.toString())) {
                Toast.makeText(getApplicationContext(), "You can't message yourself!", Toast.LENGTH_SHORT).show();
                finish();
            }

            AbsListViewBaseActivity.imageLoader.init(ImageLoaderConfiguration.createDefault(getBaseContext()));

            //registerReceiver(mHandleMessageReceiver2, new IntentFilter(DISPLAY_MESSAGE_ACTION));
            setContentView(R.layout.activity_chat);

            imageLoader.loadImage("https://www.sjizl.com/fotos/" + user_foto_num + "/thumbs/" + user_foto + "",
                    new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                            d1 = new BitmapDrawable(getResources(), loadedImage);

                        }
                    });

            imageLoader.loadImage("https://www.sjizl.com/fotos/" + foto_num + "/thumbs/" + foto + "",
                    new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                            d2 = new BitmapDrawable(getResources(), loadedImage);

                        }
                    });

            smilbtn = (ImageView) findViewById(R.id.smilbtn);
            listView = (ListView) findViewById(android.R.id.list);
            underlayout = (LinearLayout) findViewById(R.id.underlayout);
            smiles_layout = (LinearLayout) findViewById(R.id.smiles);
            textView1_bgtext = (TextView) findViewById(R.id.textView1_bgtext);
            textView1_bgtext.setText(user);
            imageView2_dashboard = (ImageView) findViewById(R.id.imageView2_dashboard);
            imageView1_logo = (ImageView) findViewById(R.id.imageView1_logo);
            imageView_bericht = (ImageView) findViewById(R.id.imageView_bericht);
            textView2_under_title = (TextView) findViewById(R.id.textView2_under_title);
            right_lin = (LinearLayout) findViewById(R.id.right_lin);
            left_lin1 = (LinearLayout) findViewById(R.id.left_lin1);
            left_lin3 = (LinearLayout) findViewById(R.id.left_lin3);
            left_lin4 = (LinearLayout) findViewById(R.id.left_lin4);
            middle_lin = (LinearLayout) findViewById(R.id.middle_lin);
            smile_lin = (LinearLayout) findViewById(R.id.smile_lin);
            ber_lin = (LinearLayout) findViewById(R.id.ber_lin);
            progressBar_hole = (ProgressBar) findViewById(R.id.progressBar_hole);
            progressBar_hole.setVisibility(View.INVISIBLE);
            imageLoader.displayImage("http://sjizl.com/fotos/" + user_foto_num + "/thumbs/" + user_foto,
                    imageView2_dashboard, options);
            new UpdateChat().execute();
            mNewMessage = (EditText) findViewById(R.id.newmsg);

            ber_lin = (LinearLayout) findViewById(R.id.ber_lin);
            photosend = (ImageView) findViewById(R.id.photosend);

            /*
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    
                    
                    
                imageLoader.loadImage("http://sjizl.com/fotos/"+user_foto_num+"/thumbs/"+user_foto, new SimpleImageLoadingListener() {
                   @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            super.onLoadingComplete(imageUri, view, loadedImage);
                
            Bitmap LoadedImage2 = loadedImage;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
               if(loadedImage!=null){
            LoadedImage2 = CommonUtilities.fastblur16(loadedImage, 4,getApplicationContext());
               }
            }
                
            if (Build.VERSION.SDK_INT >= 16) {
                
               listView.setBackground(new BitmapDrawable(getApplicationContext().getResources(), LoadedImage2));
                
              } else {
                
                 listView.setBackgroundDrawable(new BitmapDrawable(LoadedImage2));
              }
                
            }
            }
                );
            }
            */
            final ImageView left_button;
            left_button = (ImageView) findViewById(R.id.imageView1_back);
            CommonUtilities u = new CommonUtilities();
            u.setHeaderConrols(getApplicationContext(), this, right_lin, left_lin3, left_lin4, left_lin1,
                    left_button);

            listView.setOnScrollListener(new OnScrollListener() {

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    mScrollState = scrollState;
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                        int totalItemCount) {
                }

            });
            listView.setLongClickable(true);
            registerForContextMenu(listView);

            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            viewPager_smiles = new ViewPager(this);
            viewPager_smiles.setId(0x1000);
            LayoutParams layoutParams555 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            layoutParams555.width = LayoutParams.MATCH_PARENT;
            layoutParams555.height = (metrics.heightPixels / 2);
            viewPager_smiles.setLayoutParams(layoutParams555);
            TabsPagerAdapter mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), mNewMessage);
            viewPager_smiles.setAdapter(mAdapter);
            LayoutInflater inflater = null;
            viewPager_smiles.setVisibility(View.VISIBLE);
            smiles_layout.addView(viewPager_smiles);
            smiles_layout.setVisibility(View.GONE);

            left_lin4.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        Intent profile = new Intent(getApplicationContext(), ProfileActivityMain.class);
                        profile.putExtra("user", user);
                        profile.putExtra("user_foto", user_foto);
                        profile.putExtra("user_foto_num", user_foto_num);
                        profile.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(profile);
                    }
                    return false;
                }
            });
            middle_lin.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        Intent profile = new Intent(getApplicationContext(), ProfileActivityMain.class);
                        profile.putExtra("user", user);
                        profile.putExtra("user_foto", user_foto);
                        profile.putExtra("user_foto_num", user_foto_num);
                        profile.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(profile);
                    }
                    return false;
                }
            });

            smile_lin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    opensmiles();
                }
            });

            listView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent dashboard = new Intent(getApplicationContext(), ProfileActivityMain.class);
                    dashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    dashboard.putExtra("user", ArrChatLines.get(position).getNaam());
                    dashboard.putExtra("user_foto", foto);
                    dashboard.putExtra("user_foto_num", foto_num);
                    startActivity(dashboard);
                }
            });

            mNewMessage.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {

                        v.setFocusable(true);
                        v.setFocusableInTouchMode(true);

                        smiles_layout.setVisibility(View.GONE);
                        smilbtn.setImageResource(R.drawable.emoji_btn_normal);
                        return false;
                    }
                    return false;
                }
            });

            TextWatcher textWatcher = new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    //after text changed
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    if (ArrChatLines.get(0).getblocked_profile().equals("1")) {

                    } else if (ArrChatLines.get(0).getblocked_profile2().equals("1")) {

                    } else {
                        CommonUtilities.startandsendwebsock(
                                "" + pid_user + " " + naam + " " + pid + " is typing to you ...");
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                    /*
                     AsyncHttpClient.getDefaultInstance().websocket("ws://sjizl.com:9300", "my-protocol", new WebSocketConnectCallback() {
                      @Override
                         public void onCompleted(Exception ex, WebSocket webSocket) {
                             if (ex != null) {
                       ex.printStackTrace();
                       return;
                             }
                             webSocket.send(""+pid_user+" "+naam+" "+pid+" is typing to you ...");
                                 
                             webSocket.close();
                         }
                     });
                     */
                }
            };

            photosend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (ArrChatLines.get(0).getblocked_profile().equals("1")) {

                    } else if (ArrChatLines.get(0).getblocked_profile2().equals("1")) {

                    } else {
                        openGallery(SELECT_FILE1);
                    }
                }
            });

            mNewMessage.addTextChangedListener(textWatcher);

            ber_lin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SpannableStringBuilder spanStr = (SpannableStringBuilder) mNewMessage.getText();
                    Spanned cs = (Spanned) mNewMessage.getText();
                    String a = Html.toHtml(spanStr);
                    String text = mNewMessage.getText().toString();
                    mNewMessage.setText("");
                    mNewMessage.requestFocus();
                    mybmp2 = "http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto;
                    if (text.length() < 1) {
                    } else {
                        addItem(foto, foto_num, "0", naam, text.toString(),
                                "http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto, "", a);
                    }
                }
            });

            hideSoftKeyboard();

        } else {

            Intent dashboard = new Intent(getApplicationContext(), NoInternetActivity.class);
            dashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(dashboard);

            finish();
        }
        mNewMessage.clearFocus();
        listView.requestFocus();

        final String wsuri = "ws://sjizl.com:9300";

        WebSocketConnection mConnection8 = new WebSocketConnection();

        if (mConnection8.isConnected()) {
            mConnection8.reconnect();

        } else {
            try {
                mConnection8.connect(wsuri, new WebSocketConnectionHandler() {

                    @Override
                    public void onOpen() {
                        Log.d("TAG", "Status: Connected to " + wsuri);

                    }

                    @Override
                    public void onTextMessage(String payload) {

                        if (payload.contains("message send")) {
                            String[] parts = payload.split(" ");
                            String zender = parts[0];
                            String send_from = parts[1];
                            String send_name = parts[2];
                            String send_foto = parts[3];
                            String send_foto_num = parts[4];
                            String send_xxx = parts[5];

                            //      Toast.makeText(getApplication(), "" +   "\n zender: "+zender+"" +   "\n pid_user: "+pid_user+"" +"\n pid: "+pid+"" +
                            //         "\n send_from: "+send_from, 
                            //                  Toast.LENGTH_LONG).show();
                            if (zender.equalsIgnoreCase(pid) || zender.equalsIgnoreCase(pid_user)) {

                                if (send_from.equalsIgnoreCase(pid_user) || send_from.equalsIgnoreCase(pid)) {

                                    //Toast.makeText(getApplication(), "uu",    Toast.LENGTH_LONG).show();

                                    new UpdateChat().execute();

                                }
                            }

                        } else if (payload.contains("is typing to you")) {

                            String[] parts = payload.split(" ");
                            String part1 = parts[0]; // 004
                            is_typing_name = parts[1]; // 034556
                            if (is_typing_name.equalsIgnoreCase(user)) {

                                if (ArrChatLines.size() > 0) {
                                    oldvalue = ArrChatLines.get(0).getLaatstOnline();

                                } else {
                                    oldvalue = textView2_under_title.getText().toString();
                                }

                                Timer t = new Timer(false);
                                t.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        runOnUiThread(new Runnable() {
                                            public void run() {
                                                textView2_under_title.setText("typing ...");
                                            }
                                        });
                                    }
                                }, 2);

                                Timer t2 = new Timer(false);
                                t2.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        runOnUiThread(new Runnable() {
                                            public void run() {
                                                textView2_under_title.setText(oldvalue);
                                            }
                                        });
                                    }
                                }, 2000);
                            }

                        }
                        Log.d("TAG", "Got echo: " + payload);
                    }

                    @Override
                    public void onClose(int code, String reason) {
                        Log.d("TAG", "Connection lost.");
                    }
                });
            } catch (WebSocketException e) {
                Log.d("TAG", e.toString());
            }
        }

    }

    public void opensmiles() {
        if (smiles_layout.isShown()) {
            smiles_layout.setVisibility(View.GONE);
            smiles_pressed = 1;
            smilbtn.setImageResource(R.drawable.emoji_btn_normal);

        } else {
            smiles_pressed = 0;
            smilbtn.setImageResource(R.drawable.emoji_btn_normal);
            smiles_layout.setVisibility(View.VISIBLE);
            hideSoftKeyboard();

        }
    }

    public void addItem(String foto, String foto_num, String gelezen, String username, String bericht,
            String url_foto, String ber_t, String a) {

        getPhotos photos = new getPhotos();
        photos.setPhotoSource("http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto);
        photos.setNaam(username);
        photos.setFoto(foto);
        photos.setFotoNum(foto_num);

        photos.setLaatstBericht(bericht.toString());
        photos.setLaatstOnline("l online");
        photos.setNew("0");
        photos.setBerTijd(ber_t);

        ArrChatLines.add(photos);

        sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
        naam = sp.getString("naam", null);
        username = sp.getString("username", null);
        password = sp.getString("password", null);
        foto = sp.getString("foto", null);
        foto_num = sp.getString("foto_num", null);

        aaa.notifyDataSetChanged();

        ber_todb = bericht;

        if (ArrChatLines.get(0).getblocked_profile().equals("1")) {

            Toast.makeText(getApplicationContext(), "You blocked " + user, Toast.LENGTH_SHORT).show();
            new UpdateChat().execute();
        } else if (ArrChatLines.get(0).getblocked_profile2().equals("1")) {
            Toast.makeText(getApplicationContext(), "You are blocked by " + user, Toast.LENGTH_SHORT).show();
            new UpdateChat().execute();
        } else {
            new AddChat().execute();
        }

    }

    public void addItemGCM(String foto, String foto_num, String gelezen, String username, String bericht,
            String url_foto, String ber_t) {

        getPhotos photos = new getPhotos();
        photos.setPhotoSource("http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto);
        photos.setNaam(username);
        photos.setFoto(foto);
        photos.setFotoNum(foto_num);

        photos.setLaatstBericht(bericht.toString());
        photos.setLaatstOnline("l online");
        photos.setNew("1");
        photos.setBerTijd(ber_t);

        ArrChatLines.add(photos);

        SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
        naam = sp.getString("naam", null);
        username = sp.getString("username", null);
        password = sp.getString("password", null);
        foto = sp.getString("foto", null);
        foto_num = sp.getString("foto_num", null);
        aaa.notifyDataSetChanged();
        new UpdateChat().execute();

    }

    @Override
    public void onResume(Bundle savedInstanceState) { // After a pause OR at startup
        super.onResume(savedInstanceState);
        new UpdateChat().execute();
    }

    @Override
    public void onBackPressed() {
        if (smiles_layout.isShown()) {
            smiles_layout.setVisibility(View.GONE);
            smilbtn.setImageResource(R.drawable.smileee);
        } else {
            super.onBackPressed();
        }
    }

    class ItemAdapter extends BaseAdapter {

        private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();

        @Override
        public int getCount() {
            return ArrChatLines.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        class ViewHolder {
            TextView chat_left, chat_right, chat_right_text, chat_left_text, chat_left_name, chat_left_time,
                    chat_right_time, chat_right_name;

            ImageView chat_right_text_image, chat_left_text_image, chat_right_image, chat_left_image,
                    chat_right_new1, chat_right_new2, chat_left_new1, chat_left_new2;
            ProgressBar progress;
            int position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            String str_x2 = "";
            String num_foto = "";
            int type = getItemViewType(position);
            System.out.println("getView " + position + " " + convertView + " type = " + type);
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.item_list_image_chat, null);
                holder.chat_left_text = (TextView) convertView.findViewById(R.id.chat_left_text);
                holder.chat_left_text_image = (ImageView) convertView.findViewById(R.id.chat_left_text_image);

                holder.chat_left_image = (ImageView) convertView.findViewById(R.id.chat_left_image);
                holder.chat_left_name = (TextView) convertView.findViewById(R.id.chat_left_name);
                holder.chat_left_time = (TextView) convertView.findViewById(R.id.chat_left_time);
                holder.chat_left_new1 = (ImageView) convertView.findViewById(R.id.chat_left_new1);
                holder.chat_left_new2 = (ImageView) convertView.findViewById(R.id.chat_left_new2);

                holder.chat_right_text = (TextView) convertView.findViewById(R.id.chat_right_text);
                holder.chat_right_text_image = (ImageView) convertView.findViewById(R.id.chat_right_text_image);
                holder.chat_right_image = (ImageView) convertView.findViewById(R.id.chat_right_image);
                holder.chat_right_name = (TextView) convertView.findViewById(R.id.chat_right_name);
                holder.chat_right_time = (TextView) convertView.findViewById(R.id.chat_right_time);
                holder.chat_right_new1 = (ImageView) convertView.findViewById(R.id.chat_right_new1);
                holder.chat_right_new2 = (ImageView) convertView.findViewById(R.id.chat_right_new2);

                holder.chat_left_image.setVisibility(View.INVISIBLE);
                holder.chat_right_image.setVisibility(View.INVISIBLE);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            String str2 = ArrChatLines.get(position).getLaatstBericht();
            String str = str2.replace("src=/i/smiles2/", "src=http://www.sjizl.com/i/smiles2/");
            String stringWithHtml = str;

            if (user.equalsIgnoreCase(ArrChatLines.get(position).getNaam())) {
                holder.chat_left_image.setVisibility(View.INVISIBLE);
                holder.chat_right_image.setVisibility(View.INVISIBLE);
                if (Build.VERSION.SDK_INT >= 16) {
                    holder.chat_left_image.setImageDrawable(d1);
                } else {
                    holder.chat_left_image.setImageDrawable(d1);
                }

                SmilesViewUtils.setText(holder.chat_left_text, stringWithHtml);

                holder.chat_left_time.setText(ArrChatLines.get(position).getBerTijd());
                holder.chat_left_name.setText(ArrChatLines.get(position).getNaam());
                holder.chat_left_name.setVisibility(View.GONE);
                if (ArrChatLines.get(position).getNew().equals("1")) {
                    holder.chat_left_new1.setImageResource(R.drawable.friend_added_gray);
                    holder.chat_left_new2.setImageResource(R.drawable.friend_added_gray);
                } else {
                    holder.chat_left_new1.setImageResource(R.drawable.friend_added_gray);
                    holder.chat_left_new2.setImageResource(0);
                }

                holder.chat_right_new1.setImageResource(0);
                holder.chat_right_new2.setImageResource(0);
                if (CommonUtilities.strStr(stringWithHtml, "<photo>") == true) {
                    String str_x = stringWithHtml.replace("<photo>", "");
                    str_x2 = str_x.replace("</photo>", "");
                    num_foto = CommonUtilities.getFotoNummer(str_x2);
                    //Toast.makeText(getApplicationContext(),"numfoto"+num_foto+"matches!"+stringWithHtml, Toast.LENGTH_SHORT).show();
                    imageLoader.displayImage("http://sjizl.com/fotos/" + num_foto + "/thumbs/" + str_x2,
                            holder.chat_left_text_image, options);
                    holder.chat_left_text_image.setScaleType(ScaleType.CENTER_CROP);
                    holder.chat_left_text_image.setVisibility(View.VISIBLE);
                } else {
                    holder.chat_left_text_image.setVisibility(View.GONE);
                    num_foto = "";
                    str_x2 = "";
                    holder.chat_left_text_image.setImageResource(0);
                    holder.chat_left_text_image.setBackgroundResource(0);

                    if (Build.VERSION.SDK_INT >= 16) {
                        holder.chat_left_text_image.setBackground(null);
                    } else {
                        holder.chat_left_text_image.setBackgroundDrawable(null);
                    }
                }

                holder.chat_left_text.setBackgroundResource(R.drawable.border);
                holder.chat_right_text.setBackgroundResource(0);
                holder.chat_right_text.setText("");
                holder.chat_right_name.setText("");
                holder.chat_right_time.setText("");

                holder.chat_right_text_image.setVisibility(View.GONE);
                holder.chat_left_image.setVisibility(View.VISIBLE);
            } else {
                holder.chat_left_image.setVisibility(View.INVISIBLE);
                holder.chat_right_image.setVisibility(View.INVISIBLE);
                if (Build.VERSION.SDK_INT >= 16) {
                    holder.chat_right_image.setBackground(d2);
                } else {
                    holder.chat_right_image.setBackgroundDrawable(d2);
                }
                SmilesViewUtils.setText(holder.chat_right_text, stringWithHtml);

                holder.chat_right_time.setText(ArrChatLines.get(position).getBerTijd());
                holder.chat_right_name.setText(ArrChatLines.get(position).getNaam());
                holder.chat_right_name.setVisibility(View.GONE);
                if (ArrChatLines.get(position).getNew().equals("1")) {
                    holder.chat_right_new1.setImageResource(R.drawable.friend_added_gray);
                    holder.chat_right_new2.setImageResource(R.drawable.friend_added_gray);
                } else {
                    holder.chat_right_new2.setImageResource(R.drawable.friend_added_gray);
                    holder.chat_right_new1.setImageResource(0);
                }
                holder.chat_left_new1.setImageResource(0);
                holder.chat_left_new2.setImageResource(0);
                if (CommonUtilities.strStr(stringWithHtml, "<photo>") == true) {
                    String str_x = stringWithHtml.replace("<photo>", "");
                    str_x2 = str_x.replace("</photo>", "");
                    num_foto = CommonUtilities.getFotoNummer(str_x2);
                    //Toast.makeText(getApplicationContext(),"numfoto"+num_foto+"matches!"+stringWithHtml, Toast.LENGTH_SHORT).show();
                    imageLoader.displayImage("http://sjizl.com/fotos/" + num_foto + "/thumbs/" + str_x2,
                            holder.chat_right_text_image, options);
                    holder.chat_right_text_image.setScaleType(ScaleType.CENTER_CROP);
                    holder.chat_right_text_image.setVisibility(View.VISIBLE);
                } else {
                    holder.chat_right_text_image.setVisibility(View.GONE);
                    num_foto = "";
                    str_x2 = "";
                    holder.chat_right_text_image.setImageResource(0);
                    holder.chat_right_text_image.setBackgroundResource(0);

                    if (Build.VERSION.SDK_INT >= 16) {
                        holder.chat_right_text_image.setBackground(null);
                    } else {
                        holder.chat_right_text_image.setBackgroundDrawable(null);
                    }
                }
                holder.chat_left_text.setBackgroundResource(0);
                holder.chat_right_text.setBackgroundResource(R.drawable.border);
                holder.chat_left_text.setText("");
                holder.chat_left_name.setText("");
                holder.chat_left_time.setText("");

                holder.chat_left_text_image.setVisibility(View.GONE);
                holder.chat_right_image.setVisibility(View.VISIBLE);
            }

            return convertView;
        }
    }

    private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }

    public void asyncComplete(boolean success) {
        aaa.notifyDataSetChanged();
        Log.i("list_updated", "list_updated");
        Log.e("list_updated", "list_updated");
    }

    public class TabsPagerAdapter extends FragmentPagerAdapter {
        EditText mNewMessage2;

        public TabsPagerAdapter(FragmentManager fm, EditText mNewMessage) {
            super(fm);
            mNewMessage2 = mNewMessage;
        }

        @Override
        public Fragment getItem(int index) {
            switch (index) {
            case 0:
                // Top Rated fragment activity
                return new Smiles1Fragment(mNewMessage2);
            case 1:
                // Games fragment activity
                return new Smiles2Fragment();
            case 2:
                // Movies fragment activity
                return new Smiles3Fragment();
            }

            return null;
        }

        @Override
        public int getCount() {
            // get item count - equal to number of tabs
            return 3;
        }

    }

    public class AddChat extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved",
                        Context.MODE_PRIVATE);
                String naam = sp.getString("naam", null);
                String username = sp.getString("username", null);
                String password = sp.getString("password", null);

                UserFunctions userFunctions = new UserFunctions();
                JSONArray a = userFunctions.instertBerichten(username, password, user, ber_todb.toString());

            } catch (Throwable t) {
                t.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onPostExecute(Void result) {

            CommonUtilities.startandsendwebsock(
                    "" + pid_user + " " + pid + " " + naam + " " + foto + " " + foto_num + " message send");
            /*
              AsyncHttpClient.getDefaultInstance().websocket("ws://sjizl.com:9300", "my-protocol", new WebSocketConnectCallback() {
               @Override
                  public void onCompleted(Exception ex, WebSocket webSocket) {
             if (ex != null) {
                 ex.printStackTrace();
                 return;
             }
             webSocket.send(""+pid_user+" "+ pid +" "+ naam +" "+ foto +" "+ foto_num +" message send");
             Log.d(""+pid_user+" "+ pid +" "+ naam +" "+ foto +" "+ foto_num +" message send",""+pid_user+" "+ pid +" "+ naam +" "+ foto +" "+ foto_num +" message send");
             webSocket.close();
                  }
              });
              */
            new UpdateChat().execute();
        }
    }

    private class UpdateChat extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            UserFunctions userFunctions = new UserFunctions();
            JSONArray json31 = userFunctions.getBerichten(username, password, user);

            ArrChatLines.clear();
            for (int i = 0; i < json31.length(); i++) { // **line 2**
                JSONObject childJSONObject = null;
                try {

                    childJSONObject = json31.getJSONObject(i);
                    String name = childJSONObject.getString("naam_vriend");
                    String foto2 = childJSONObject.getString("foto_vriend");
                    String foto_mum2 = childJSONObject.getString("num_vriend");
                    String laatste_berichten2 = childJSONObject.getString("laatste_bericht");
                    String laatste_online = childJSONObject.getString("laatst_online");
                    String aantal_news = childJSONObject.getString("new");
                    String ber_t = childJSONObject.getString("bericht_tijd");

                    String user_blocked_profile = childJSONObject.getString("user_blocked_profile");

                    String user_blocked_profile2 = childJSONObject.getString("user_blocked_profile2");

                    //imageUrls[] =url;

                    getPhotos photos = new getPhotos();
                    photos.setPhotoSource("http://sjizl.com/fotos/" + foto_mum2 + "/thumbs/" + foto2);
                    photos.setNaam(name);
                    photos.setFoto(foto2);
                    photos.setFotoNum(foto_mum2);
                    photos.set_user_blocked_profile(user_blocked_profile);
                    photos.set_user_blocked_profile2(user_blocked_profile2);
                    photos.setLaatstBericht(laatste_berichten2);
                    photos.setLaatstOnline(laatste_online);
                    photos.setNew(aantal_news);
                    photos.setBerTijd(ber_t);

                    ArrChatLines.add(photos);

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onPostExecute(Void result) {

            if (ArrChatLines.size() > 0) {
                textView2_under_title.setText(ArrChatLines.get(0).getLaatstOnline());
            }
            aaa = new ItemAdapter();
            ((ListView) listView).setAdapter(aaa);
            aaa.notifyDataSetChanged();

            CommonUtilities.startandsendwebsock(
                    "" + pid_user + " " + pid + " " + naam + " " + foto + " " + foto_num + " messages read");

        }
    }

    private final BroadcastReceiver mHandleMessageReceiver2 = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent i) {
            if (i != null) {
                String msg_receive = i.getStringExtra("type");
                Bundle bundle = i.getExtras();
                String type3 = bundle.getString("type");
                String type = "niks";
                type = i.getExtras().getString("type");
                if (i.getExtras() != null) {
                    if (i.getExtras().containsKey("type")) {
                        type = i.getExtras().getString("type");
                        if (type.toString().equals("bericht")) {
                            String user2 = i.getExtras().getString("user");
                            if (user2.toString().equals(user.toString())) {
                                WakeLocker.acquire(getApplicationContext());
                                String foto_server = i.getExtras().getString("foto_chat");
                                String foto_num_server = i.getExtras().getString("foto_num_chat");
                                String bericht_chat = i.getExtras().getString("bericht_chat");
                                addItemGCM(foto_server, foto_num_server, "0", user2, bericht_chat.toString(),
                                        "http://sjizl.com/fotos/" + foto_num_server + "/thumbs/" + foto_server + "",
                                        "");
                                WakeLocker.release();
                            }
                        }
                    }
                }
            } else {
                Toast.makeText(getApplicationContext(), "intent is null!!!", Toast.LENGTH_SHORT).show();
            }
        }
    };

    public class getPhotos {
        String PhotoSource, Online, Naam, Foto, FotoNum, Ber_t, Aantal_news, Laatste_online, Laatste_berichten2,
                user_blocked_profile, user_blocked_profile2;

        public void setFotoNum(String FotoNum) {
            this.FotoNum = FotoNum;
        }

        public void set_user_blocked_profile(String xuser_blocked_profile) {
            this.user_blocked_profile = xuser_blocked_profile;
        }

        public void set_user_blocked_profile2(String xuser_blocked_profile2) {
            this.user_blocked_profile2 = xuser_blocked_profile2;
        }

        public void setBerTijd(String ber_t) {
            this.Ber_t = ber_t;
        }

        public void setNew(String aantal_news) {
            this.Aantal_news = aantal_news;
        }

        public void setLaatstOnline(String laatste_online) {
            this.Laatste_online = laatste_online;
        }

        public void setLaatstBericht(String laatste_berichten2) {
            this.Laatste_berichten2 = laatste_berichten2;
        }

        public void setFoto(String Foto) {
            this.Foto = Foto;
        }

        public void setNaam(String Naam) {
            this.Naam = Naam;
        }

        public void setOnline(String Online) {
            this.Online = Online;
        }

        public void setPhotoSource(String PhotoSource) {
            this.PhotoSource = PhotoSource;
        }

        public String getFotoNum() {
            return FotoNum;
        }

        public String getFoto() {
            return Foto;
        }

        public String getNaam() {
            return Naam;
        }

        public String getOnline() {
            return Online;
        }

        public String getPhotoSource() {
            return PhotoSource;
        }

        public String getNew() {
            return Aantal_news;
        }

        public String getLaatstOnline() {
            return Laatste_online;
        }

        public String getLaatstBericht() {
            return Laatste_berichten2;
        }

        public String getBerTijd() {
            return Ber_t;
        }

        public String getblocked_profile2() {
            return user_blocked_profile2;
        }

        public String getblocked_profile() {
            return user_blocked_profile;
        }

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        int index = info.position;
        String textTocopy = ArrChatLines.get(index).getLaatstBericht();

        switch (item.getItemId()) {
        case R.id.delete:
            //   quoteResult.remove(info.position);
            //   ((StockQuoteAdapter)getListAdapter()).notifyDataSetChanged();

            Toast.makeText(getApplicationContext(), "delete almost implementated", Toast.LENGTH_SHORT).show();
            return false;

        case R.id.copy:
            //   quoteResult.remove(info.position);
            //   ((StockQuoteAdapter)getListAdapter()).notifyDataSetChanged();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                        Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("simple text", textTocopy);
                clipboard.setPrimaryClip(clip);
            } else {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                        Context.CLIPBOARD_SERVICE);
                clipboard.setText(textTocopy);

            }

            //place your TextView's text in clipboard

            Toast.makeText(getApplicationContext(), "Item copied", Toast.LENGTH_SHORT).show();
            return false;
        }
        return false;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.chat_menu_list, menu);

    }

    public void openGallery(int req_code) {

        //   Intent intent2 = new Intent();
        //   intent2.setType("image/*");
        //   intent2.setAction(Intent.ACTION_GET_CONTENT);
        //   startActivityForResult(Intent.createChooser(intent2,"Select file to upload "), req_code);

        // Use the GET_CONTENT intent from the utility class
        Intent target = FileUtils.createGetContentIntent();

        Intent intent = Intent.createChooser(target, getResources().getText(R.string.app_name));
        try {
            startActivityForResult(intent, req_code);
        } catch (ActivityNotFoundException e) {
            // The reason for the existence of aFileChooser
        }

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            if (data != null) {
                // Get the URI of the selected file
                final Uri uri = data.getData();
                Log.i("ffff:", "Uri = " + uri.toString());
                try {
                    // Get the file path from the URI
                    final String path = FileUtils.getPath(this, uri);
                    //      Toast.makeText(ChatActivity.this,
                    //    "File Selected: " + path, Toast.LENGTH_LONG).show();

                    //     CommonUtilities.custom_toast(getApplicationContext(), ChatActivity.this,"File Selected: " + path,  null,R.drawable.iconbd);                   

                    Thread thread = new Thread(new Runnable() {
                        public void run() {
                            doFileUpload(path);
                            runOnUiThread(new Runnable() {
                                public void run() {

                                }
                            });
                        }
                    });
                    thread.start();

                } catch (Exception e) {
                    Log.e("FileSelectorTestActivity", "File select error", e);
                }
            }
        }

    }

    private void doFileUpload(String path) {

        String username = "";
        String password = "";
        String foto = "";
        String foto_num = "";
        SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
        username = sp.getString("username", null);
        password = sp.getString("password", null);
        foto = sp.getString("foto", null);
        foto_num = sp.getString("foto_num", null);

        File file1 = new File(path);

        String urlString = "http://sjizl.com/postBD/UploadToServer.php?intochat=1&pid_user=" + pid_user
                + "&username=" + username + "&password=" + password;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(urlString);
            FileBody bin1 = new FileBody(file1);

            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("uploadedfile1", bin1);

            reqEntity.addPart("user", new StringBody("User"));
            post.setEntity(reqEntity);
            HttpResponse response = client.execute(post);
            resEntity = response.getEntity();
            final String response_str = EntityUtils.toString(resEntity);
            if (resEntity != null) {
                Log.i("RESPONSE", response_str);
                runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            // res.setTextColor(Color.GREEN);
                            // res.setText("n Response from server : n " + response_str);

                            CommonUtilities.custom_toast(getApplicationContext(), ChatActivity.this,
                                    "Upload Complete! ", null, R.drawable.iconbd);

                            new UpdateChat().execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        } catch (Exception ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        }

        //RegisterActivity.login(username,password,getApplicationContext());
        CommonUtilities.startandsendwebsock(
                "" + pid_user + " " + pid + " " + naam + " " + foto + " " + foto_num + " message send");
    }

    private class ImageGetter implements Html.ImageGetter {

        public Drawable getDrawable(String source) {
            int id;

            id = getResources().getIdentifier(source, "drawable", getPackageName());

            if (id == 0) {
                // the drawable resource wasn't found in our package, maybe it is a stock android drawable?
                id = getResources().getIdentifier(source, "drawable", "android");
            }

            if (id == 0) {
                // prevent a crash if the resource still can't be found
                return null;
            } else {
                Drawable d = getResources().getDrawable(id);
                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                return d;
            }
        }

    }
}