sjizl.com.ChatActivityFragment.java Source code

Java tutorial

Introduction

Here is the source code for sjizl.com.ChatActivityFragment.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.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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.ProgressDialog;
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.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.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.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 ChatActivityFragment extends AbsListViewBaseActivityChat 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;
    private ActionBar actionBar;
    TextView textView1_bgtext, textView2_under_title;
    EditText mNewMessage;
    SharedPreferences sp;
    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;
    AlertDialogManager alert = new AlertDialogManager();
    ProgressBar progressBar_hole;
    ImageView imageView2_dashboard, imageView1_logo, imageView_bericht;
    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 (getActivity().getCurrentFocus() != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
        }
    }

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

    private static final String ARG_POSITION = "position";

    private int position;

    public static ChatActivityFragment newInstance(int position) {
        ChatActivityFragment f = new ChatActivityFragment();
        Bundle b = new Bundle();
        b.putInt(ARG_POSITION, position);
        f.setArguments(b);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LayoutInflater factory = LayoutInflater.from(getActivity());
        View myView = factory.inflate(R.layout.activity_chat_fragment, null);

        if (CommonUtilities.isInternetAvailable(getActivity().getApplicationContext())) //returns true if internet available
        {

            SharedPreferences sp = getActivity().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 = getActivity().getIntent().getExtras();

            Bundle args = getArguments();

            Log.i("args", args.toString());
            if (args != null && args.containsKey("pid_user")) {

                pid_user = args.getString("pid_user");
                user = args.getString("user");
                user_foto_num = args.getString("user_foto_num");
                user_foto = args.getString("user_foto");
            } else {

                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(getActivity().getApplicationContext(), "You can't message yourself!",
                        Toast.LENGTH_SHORT).show();
                getActivity().finish();
            }

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

            getActivity().registerReceiver(mHandleMessageReceiver2, new IntentFilter(DISPLAY_MESSAGE_ACTION));

            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) myView.findViewById(R.id.smilbtn);
            listView = (ListView) myView.findViewById(android.R.id.list);
            underlayout = (LinearLayout) myView.findViewById(R.id.underlayout);
            smiles_layout = (LinearLayout) myView.findViewById(R.id.smiles);
            textView1_bgtext = (TextView) getActivity().findViewById(R.id.textView1_bgtext);
            textView1_bgtext.setText(user);
            imageView2_dashboard = (ImageView) getActivity().findViewById(R.id.imageView2_dashboard);
            imageView1_logo = (ImageView) getActivity().findViewById(R.id.imageView1_logo);
            imageView_bericht = (ImageView) getActivity().findViewById(R.id.imageView_bericht);
            textView2_under_title = (TextView) getActivity().findViewById(R.id.textView2_under_title);
            right_lin = (LinearLayout) getActivity().findViewById(R.id.right_lin);
            left_lin1 = (LinearLayout) getActivity().findViewById(R.id.left_lin1);
            left_lin3 = (LinearLayout) getActivity().findViewById(R.id.left_lin3);
            left_lin4 = (LinearLayout) getActivity().findViewById(R.id.left_lin4);
            middle_lin = (LinearLayout) getActivity().findViewById(R.id.middle_lin);
            smile_lin = (LinearLayout) myView.findViewById(R.id.smile_lin);
            ber_lin = (LinearLayout) myView.findViewById(R.id.ber_lin);
            progressBar_hole = (ProgressBar) getActivity().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) myView.findViewById(R.id.newmsg);
            ber_lin = (LinearLayout) myView.findViewById(R.id.ber_lin);

            /*
            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));
              }
                
            }
            }
                );
            }
            */

            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();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
            viewPager_smiles = new ViewPager(getActivity());
            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(getActivity().getSupportFragmentManager(),
                    mNewMessage);
            viewPager_smiles.setAdapter(mAdapter);
            LayoutInflater inflater2 = 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(getActivity().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(getActivity().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(getActivity().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) {

                    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();
                         }
                     });
                     */
                }
            };

            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(getActivity().getApplicationContext(), NoInternetActivity.class);
            dashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(dashboard);

            getActivity().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() {
                                        getActivity().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() {
                                        getActivity().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());
            }
        }
        return myView;

    }

    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 = getActivity().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;
        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 = getActivity().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();
    }

    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_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;
            int type = getItemViewType(position);
            System.out.println("getView " + position + " " + convertView + " type = " + type);
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = getActivity().getLayoutInflater().inflate(R.layout.item_list_image_chat, null);
                holder.chat_left_text = (TextView) convertView.findViewById(R.id.chat_left_text);
                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_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);

                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_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);

                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_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 = getActivity().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");

                    //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.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();

        }
    }

    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(getActivity().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(getActivity().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;

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

        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;
        }

    }

    @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(getActivity().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) getActivity()
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("simple text", textTocopy);
                clipboard.setPrimaryClip(clip);
            } else {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getActivity()
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setText(textTocopy);

            }

            //place your TextView's text in clipboard

            Toast.makeText(getActivity().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 = getActivity().getMenuInflater();
        inflater.inflate(R.menu.chat_menu_list, menu);

    }

}