com.stikyhive.stikyhive.ChattingActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.stikyhive.stikyhive.ChattingActivity.java

Source

/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 * <p/>
 * 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
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * 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 com.stikyhive.stikyhive;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.stikyhive.customcontrol.ChatArrayAdapter;
import com.stikyhive.gcm.MyGcmListenerService;
import com.stikyhive.gcm.QuickstartPreferences;
import com.stikyhive.model.ChatContact;
import com.stikyhive.model.SellerMarket;
import com.stikyhive.model.StikyChat;
import com.stikyhive.model.StikyChatMore;
import com.stikyhive.model.StikyChatTb;

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 java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class ChattingActivity extends Activity {
    public static String messageServer, timeSendOffer, price, rate, name;
    public static int limitMsg, offerId, offerStatus;
    public static boolean firstConnect, noti, flagChatting, flagFullPhoto, flagStikyPayChk;
    public static List sellListBySellerMarket;
    public static final String API_KEY = "AIzaSyCQPHllJgsZzVapK7rWdzdZ_dbIaqnrkks";
    private final String TAG = "ChattingActivity";

    private TextView txtUserName, txtLabel1, txtLabel2, txtLabel3;
    private static String recipientStkid;
    private EditText edTxtMsg;
    private ImageView imgViewProfile, imgViewAddCon;
    private LinearLayout layoutLabel, layoutTalk;

    private ProgressDialog dialog;
    public static ListView lv;
    public static ChatArrayAdapter adapter;

    SimpleDateFormat dateFormat, dateFormat2;
    private Date start;
    public static List<StikyChatTb> listHistory;
    List<ChatContact> listChatContact;
    private String timeSend, timeSendServer, recipientProfileGCM, recipientStkidGCM, messageGCM, recipientNameGCM,
            recipientTokenGCM, senderTokenGCM;
    private String chatRecipient, chatRecipientUrl, senderToken, recipientToken, message;
    int rows;
    private boolean flagRefresh, flagAddContact, flagNotifi, flagPay, flagMakeOffer, flagTransfer, flagRecord;
    private int offerIdGCM, offerStatusGCM;
    private String priceGCM, rateGCM, nameGCM, msg, fileNameGCM;

    ImageLoader imageLoader;
    TextWatcher txtEditorWatcher;
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    SharedPreferences pref;
    JsonWebService ws;
    DBHelper dbHelper;
    SwipeRefreshLayout swipeRefreshLayout;
    private File documentFile, audiofile;

    private String fontOSSemi_bold = "fonts/Open_Sans/OpenSans-Semibold.ttf";
    private String fontOSLight = "fonts/Open_Sans/OpenSans-Light.ttf";
    private String fontOSRegular = "fonts/Open_Sans/OpenSans-Regular.ttf";
    private Typeface faceSemi_bold, faceRegular;
    private static final int FILE_SELECT_CODE = 0;
    private DisplayMetrics metrics;
    private Uri imageUri;
    private final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;

    private final int GALLERY_ACTIVITY_CODE = 200;
    private String imagePath, upLoadServerUri, fileNameRes;
    private Cursor cursor;
    File SDFile1;
    String oriFName = "";

    //for recording
    private MediaRecorder mRecorder;
    private String mFileName = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setBackgroundDrawableResource(R.drawable.chat_bg);
        // this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        recipientStkid = getIntent().getExtras().getString("recipientStkid");
        chatRecipient = getIntent().getExtras().getString("chatRecipient");
        chatRecipientUrl = getIntent().getExtras().getString("chatRecipientUrl");
        senderToken = getIntent().getExtras().getString("senderToken");
        recipientToken = getIntent().getExtras().getString("recipientToken");
        noti = getIntent().getExtras().getBoolean("noti");
        message = getIntent().getExtras().getString("message");
        rows = getIntent().getExtras().getInt("rows");
        flagChatting = true;
        pref = PreferenceManager.getDefaultSharedPreferences(this);
        offerId = 0;
        offerStatus = 0;
        ws = new JsonWebService();
        dbHelper = new DBHelper(this);
        dialog = new ProgressDialog(this);
        listChatContact = new ArrayList<>();
        listChatContact = dbHelper.getChatContact();
        Log.i(" Chat Contact ", " " + listChatContact.size());
        metrics = this.getResources().getDisplayMetrics();
        //to change font
        faceSemi_bold = Typeface.createFromAsset(getAssets(), fontOSSemi_bold);
        Typeface faceLight = Typeface.createFromAsset(getAssets(), fontOSLight);
        faceRegular = Typeface.createFromAsset(getAssets(), fontOSRegular);

        imageLoader = ImageLoader.getInstance();
        if (!imageLoader.isInited()) {
            imageLoader.init(ImageLoaderConfiguration.createDefault(this));
        }

        start = new Date();
        SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
        timeSend = oFormat.format(start);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat);

        layoutTalk = (LinearLayout) findViewById(R.id.layoutTalk);
        txtUserName = (TextView) findViewById(R.id.txtChatName);
        edTxtMsg = (EditText) findViewById(R.id.edTxtMsg);
        imgViewProfile = (ImageView) findViewById(R.id.imgViewChat);
        imgViewAddCon = (ImageView) findViewById(R.id.imgAddContact);
        lv = (ListView) findViewById(R.id.listView1);
        layoutLabel = (LinearLayout) findViewById(R.id.layoutLabel);
        txtLabel1 = (TextView) findViewById(R.id.txtLabel1);
        txtLabel2 = (TextView) findViewById(R.id.txtLabel2);
        txtLabel3 = (TextView) findViewById(R.id.txtLabel3);
        txtLabel2.setText(" " + chatRecipient + " ");
        txtLabel1.setTypeface(faceLight);
        txtLabel2.setTypeface(faceRegular);
        txtLabel3.setTypeface(faceLight);

        for (ChatContact contact : listChatContact) {
            if (contact.getContactId().equals(recipientStkid)) {
                imgViewAddCon.setVisibility(View.INVISIBLE);
                layoutLabel.setVisibility(View.GONE);
                break;
            }
        }
        Log.i(TAG, " come back again");
        adapter = new ChatArrayAdapter(this, R.layout.chatting_listview, faceSemi_bold, faceRegular, recipientStkid,
                senderToken, recipientToken);
        lv.setAdapter(adapter);
        // adapter.add(new StikyChat(chatRecipientUrl, "Hello", false, "12.10.2015", "12.1.2014"));

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        // BEGIN_INCLUDE (change_colors)
        // Set the color scheme of the SwipeRefreshLayout by providing 4 color resource ids
        swipeRefreshLayout.setColorScheme(R.color.swipe_color_1, R.color.swipe_color_2, R.color.swipe_color_3,
                R.color.swipe_color_4);
        limitMsg = 7;
        // END_INCLUDE (change_colors)
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.i(" Refresh Layout ", "onRefresh called from SwipeRefreshLayout");
                if (limitMsg < rows) {
                    Log.i("Limit Message ", " " + limitMsg);
                    limitMsg *= 2;
                    fetchRecords();
                } else if ((!(rows <= 7)) && limitMsg > rows && (limitMsg - rows < 7)) {
                    fetchRecords();
                } else {
                    Log.i("No data ", "to refresh");
                    swipeRefreshLayout.setRefreshing(false);
                    Toast.makeText(getApplicationContext(), "No data to refresh!", Toast.LENGTH_SHORT).show();
                }
                // initiateRefresh();
            }
        });

        LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout headerLayout = (LinearLayout) findViewById(R.id.header);
        View header = inflator.inflate(R.layout.header, null);

        TextView textView = (TextView) header.findViewById(R.id.textView1);
        textView.setText("StikyChat");
        textView.setTypeface(faceSemi_bold);
        textView.setVisibility(View.VISIBLE);
        headerLayout.addView(header);
        LinearLayout layoutRight = (LinearLayout) header.findViewById(R.id.layoutRight);
        layoutRight.setVisibility(View.GONE);

        txtUserName.setText(chatRecipient);
        Log.i(TAG, "Activity Name " + txtUserName.getText().toString());
        txtUserName.setTypeface(faceSemi_bold);

        String url = "";

        Log.i(TAG, " ^^^ " + chatRecipientUrl + " ");
        if (chatRecipientUrl != null) {
            if (chatRecipientUrl.contains("http")) {
                url = chatRecipientUrl;
            } else if (chatRecipientUrl != "null") {
                url = this.getResources().getString(R.string.url) + "/" + chatRecipientUrl;
            }
        }
        addAndroidUniversalImageLoader(imgViewProfile, url);
        //        if (noti && (!message.equals(""))) {
        //            adapter.add(new StikyChat(chatRecipientUrl, message, true, timeSend, ""));
        //            lv.smoothScrollToPosition(adapter.getCount() - 1);
        //        }

        //to show history chats between two users(sender & recipient)
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat2 = new SimpleDateFormat("dd MMM HH:mm");
        listHistory = dbHelper.getStikyChat();
        if (listHistory.size() > 0) {
            Collections.reverse(listHistory);
            for (final StikyChatTb chatTb : listHistory) {
                String getDate = chatTb.getSendDate();
                String durationStr = null;
                String fromStikyBee = chatTb.getSender();
                try {
                    final String createDate = dateFormat2.format(dateFormat.parse(getDate));
                    if (chatTb.getFileName().contains("voice")) {
                        MediaPlayer mPlayer = new MediaPlayer();
                        String voiceFileName = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                        try {
                            mPlayer.setDataSource(voiceFileName);
                            mPlayer.prepare();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        //mPlayer.start();
                        int duration = mPlayer.getDuration();
                        mPlayer.release();
                        duration = (int) Math.ceil(duration / 1024);

                        if (duration < 10) {
                            durationStr = "00:0" + duration;
                        } else {
                            durationStr = "00:" + duration;
                        }
                        // Log.i(TAG, "Duration Srt " + durationStr);
                    }
                    if (fromStikyBee.equals(pref.getString("stkid", ""))) {
                        //String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                        // Log.i(TAG, " Offer Id " + chatTb.getOfferId() + " Price " + chatTb.getPrice() + " Name " + chatTb.getName());
                        //first false = right, second false = Offer
                        //  Log.i(TAG, " Duration " + chatTb.getRate() + " File Name " + chatTb.getFileName());
                        if (!chatTb.getFileName().contains("voice")) {
                            Log.i(TAG, " Voice is not ");
                            adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                    chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                    chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                    chatTb.getOriFName()));
                        } else {
                            Log.i(TAG, " Voice is ");
                            adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                    chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                    chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                        }
                    } else {
                        /* Bitmap bmImg = BitmapFactory.decodeFile(getResources().getString(R.string.url) + "/" + chatTb.getFileName());
                         Bitmap resBm = getResizedBitmap(bmImg, 500);*/
                        // String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                        if (!chatTb.getFileName().contains("voice")) {
                            adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                    chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                    chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                    chatTb.getOriFName()));
                        } else {
                            adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                    chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                    chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                        }
                    }
                    lv.smoothScrollToPosition(adapter.getCount() - 1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
                fileNameGCM = sharedPreferences.getString("fileName", "");
                messageGCM = sharedPreferences.getString("message", "");
                offerIdGCM = sharedPreferences.getInt("offerId", 0);
                offerStatusGCM = sharedPreferences.getInt("offerStatus", 0);
                priceGCM = sharedPreferences.getString("price", "");
                rateGCM = sharedPreferences.getString("rate", "");
                nameGCM = sharedPreferences.getString("name", "");
                recipientProfileGCM = sharedPreferences.getString("chatRecipientUrl", "");
                recipientNameGCM = sharedPreferences.getString("chatRecipientName", "");
                recipientStkidGCM = sharedPreferences.getString("recipientStkid", "");
                recipientTokenGCM = sharedPreferences.getString("recipientToken", "");
                senderTokenGCM = sharedPreferences.getString("senderToken", "");

                Log.i(TAG, " FileName GCM " + fileNameGCM + " " + " Name Rate Price &&&&& *** " + messageGCM + " "
                        + priceGCM + " " + rateGCM);
                if (firstConnect) {
                    if (recipientStkidGCM.trim() == recipientStkid.trim()
                            || recipientStkidGCM.equals(recipientStkid)) {
                        MyGcmListenerService.flagSendNoti = false;
                        Log.i(TAG, " " + message);
                        // (1) get today's date
                        start = new Date();
                        SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
                        timeSend = oFormat.format(start);

                        Log.i(TAG, "First connect " + firstConnect);
                        Log.i(TAG, " File Name GCMMMMMM " + fileNameGCM);
                        /*if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                        oriFName = saveFileAndImage(fileNameGCM);
                        }*/
                        /*if (fileNameGCM.contains("voice")) {
                        String durationStr;
                        MediaPlayer mPlayer = new MediaPlayer();
                        String voiceFileName = getResources().getString(R.string.url) + "/" + fileNameGCM;
                        try {
                            mPlayer.setDataSource(voiceFileName);
                            mPlayer.prepare();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                            
                        //mPlayer.start();
                        int duration = mPlayer.getDuration();
                        mPlayer.release();
                        duration = (int) Math.ceil(duration / 1024);
                            
                        if (duration < 10) {
                            durationStr = "00:0" + duration;
                        } else {
                            durationStr = "00:" + duration;
                        }
                        StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend, fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, durationStr, null, oriFName);
                        adapter.add(stikyChat);
                        } else {*/
                        StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend,
                                fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, nameGCM, null,
                                oriFName);
                        adapter.add(stikyChat);
                        //  }
                        Log.i(TAG, " First " + message + " " + recipientProfileGCM + " " + timeSend);
                        Log.i(TAG, "User " + txtUserName.getText().toString());

                        adapter.notifyDataSetChanged();
                        lv.setSelection(adapter.getCount() - 1);
                        new regTask2().execute("Obj ");
                    } else {
                        /* if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                        saveFileAndImage(fileNameGCM);
                         }*/
                        Log.i(TAG, "..." + recipientStkidGCM.trim());
                        Log.i(TAG, "&&&" + recipientStkid.trim());
                        Log.i(TAG, "else casee");
                        //notificaton send
                        flagNotifi = true;
                        new regTask2().execute("Notification");
                    }
                    firstConnect = false;
                }
                lv.setSelection(adapter.getCount() - 1);
            }
        };

        /*edTxtMsg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            layoutTalk.setLayoutParams(params);
            layoutTalk.setGravity(Gravity.CENTER);
          Toast.makeText(getBaseContext(),
                    ((EditText) v).getId() + " has focus - " + hasFocus,
                    Toast.LENGTH_LONG).show();
        }
        });*/
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        edTxtMsg.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, 0);
                params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                layoutTalk.setLayoutParams(params);
                layoutTalk.setGravity(Gravity.CENTER);
                flagRecord = false;
                /*getWindow().setSoftInputMode(
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
                );*/
                Toast.makeText(getBaseContext(), "Touch ...", Toast.LENGTH_LONG).show();
                return false;
            }
        });
    }

    private String saveFileAndImage(String url) {
        int index = url.lastIndexOf("/");
        String token = url.substring(index);
        String fileName = token.replace("/", "");
        Log.i("File Name ", " ^^ " + fileName.trim());
        String extStorageDirectory = Environment.getExternalStorageDirectory() + "/Download/";
        File file = new File(extStorageDirectory, fileName.trim());
        Log.i("File Directory...", " %%% " + file.getPath());
        DownloadFileFromURL fileFromURL = new DownloadFileFromURL(file);
        fileFromURL.execute(getResources().getString(R.string.url) + "/" + url.trim());
        return fileName;
    }

    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         */
        File fa;

        DownloadFileFromURL(File fil) {
            fa = fil;
        }

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

            //  showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file
                OutputStream output = new FileOutputStream(fa);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            //    pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task
         * Dismiss the progress dialog
         */
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            //    dismissDialog(progress_bar_type);

            // Displaying downloaded image into image view
            // Reading image path from sdcard
            String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf";

            // setting downloaded into image view
            //  my_image.setImageDrawable(Drawable.createFromPath(imagePath));

        }

    }

    public void addAndroidUniversalImageLoader(final ImageView imageView, final String url) {
        int drawable = 0;
        drawable = R.drawable.default_profile;

        {
            DisplayImageOptions options;
            options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_stub)
                    .showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(drawable).cacheInMemory(true)
                    .cacheOnDisk(true).considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565).build();
            imageLoader.getInstance().displayImage(url, imageView, options);
        }
    }

    public void clickAddContacts(View v) {
        Log.i("Add ", " Contacts ");
        flagAddContact = true;
        new regTask2().execute("Add Contact");
    }

    public void clickFileTransfer(View v) {
        flagMakeOffer = true;
        showFileChooser();
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
        flagRecord = false;
        //loadFileList();
        // onCreateDialog(DIALOG_LOAD_FILE);
    }

    public void clickImageTransfer(View v) {
        flagMakeOffer = true;
        showPhoto();
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
        flagRecord = false;
    }

    public void showPhoto() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        String[] strArray = { "Take photo", "Choose from Gallery" };

        builder.setTitle("Select Photo").setItems(strArray, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // The 'which' argument contains the index position
                // of the selected item
                switch (which) {
                case 0:

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    /*****
                     * Define the file-name to save photo taken by
                     * Camera activity
                     *******/
                    String fileName = "Camera_Example.jpg";

                    // Create parameters for Intent with filename
                    ContentValues values = new ContentValues();

                    values.put(MediaStore.Images.Media.TITLE, fileName);

                    values.put(MediaStore.Images.Media.DESCRIPTION, "Image capture by camera");
                    /******
                     * imageUri is the current activity attribute,
                     * define and save it for later usage
                     *****/
                    imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                    // start the image capture Intent
                    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                    Log.i("Camera ", " Testing...");
                    break;
                case 1:
                    // start GalleryUtil Activity to choose photo from
                    // Gallery
                    Intent gallery_Intent = new Intent("com.arctech.GALLERYUTIL");
                    gallery_Intent.putExtra("type", "image");
                    startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
                    break;
                default:
                    break;
                }
            }
        });
        builder.create();
        builder.show();
    }

    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("File/*");

        /*try {
        startActivityForResult(intent, FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
        }*/
        // special intent for Samsung file manager
        Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
        // if you want any file type, you can skip next line
        // sIntent.putExtra("CONTENT_TYPE", "*/*");
        sIntent.addCategory(Intent.CATEGORY_DEFAULT);

        Intent chooserIntent;
        if (getPackageManager().resolveActivity(sIntent, 0) != null) {
            // it is device with samsung file manager
            chooserIntent = Intent.createChooser(sIntent, "Open file");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent });
        } else {
            chooserIntent = Intent.createChooser(intent, "Open file");
        }

        try {
            startActivityForResult(chooserIntent, FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(getApplicationContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG, " ON ACTivyiy result");
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("Result code ", " ^^ " + requestCode);
        if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK) {
            Log.i(TAG, " ON ACTivyiy result ^^ 2");
            // Get the Uri of the selected file
            Uri uri = data.getData();
            Log.d("TAG", "File Uri: " + uri.toString());
            // Get the path
            String path;
            try {
                calcualteTodayDate();
                path = getPath(this, uri);
                documentFile = new File(path);

                String extension = "";
                int index = documentFile.getName().lastIndexOf(".");
                if (index != -1) {
                    extension = documentFile.getName().substring(index + 1);
                }
                Bitmap bmImg = BitmapFactory.decodeFile(path);
                //   Bitmap resBm = getResizedBitmap(bmImg, 500);
                adapter.add(new StikyChat("", "<img", false, timeSend, "file" + path, 0, 0, "", "", "", null,
                        documentFile.getPath()));
                adapter.notifyDataSetChanged();
                lv.setSelection(adapter.getCount() - 1);
                Log.i("Document File ", " %%%% " + documentFile.getAbsolutePath());
                upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                        + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                        + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension
                        + "&type=file" + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                        + URLEncoder.encode(getResources().getString(R.string.url));
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        int serverResponseCode = uploadFile(documentFile);
                        if (serverResponseCode == 200) {
                            Log.i("Success", " is done! ");
                            flagChatting = false;
                            flagTransfer = true;
                            messageServer = "<img";
                            msg = "File transfer.";
                            recipientStkidGCM = recipientStkid;
                            new regTask().execute("GCM");
                            new regTask2().execute("Last Message!");
                        }
                    }
                }).start();
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if (resultCode == Activity.RESULT_OK && requestCode == GALLERY_ACTIVITY_CODE) {
            Log.i(TAG, " Gallery is clicked..");
            calcualteTodayDate();
            imagePath = data.getStringExtra("picturePath");
            SDFile1 = new File(imagePath);

            String extension = "";
            int index = SDFile1.getName().lastIndexOf(".");
            if (index != -1) {
                extension = SDFile1.getName().substring(index + 1);
            }
            Bitmap bmImg = BitmapFactory.decodeFile(imagePath);
            Bitmap resBm = getResizedBitmap(bmImg, 500);
            adapter.add(new StikyChat("", "<img", false, timeSend, "bitmap" + imagePath, 0, 0, "", "", "", resBm,
                    SDFile1.getPath()));
            adapter.notifyDataSetChanged();
            lv.setSelection(adapter.getCount() - 1);
            Log.i("SDFile ", " $$$ " + SDFile1.getAbsolutePath());
            upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                    + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                    + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension + "&type=image"
                    + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                    + URLEncoder.encode(getResources().getString(R.string.url));
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    int serverResponseCode = uploadFile(SDFile1);
                    if (serverResponseCode == 200) {
                        Log.i("Success", " is done! ");
                        flagChatting = false;
                        flagTransfer = true;
                        messageServer = "<img";
                        msg = "Image Transfer";
                        recipientStkidGCM = recipientStkid;
                        new regTask().execute("GCM");
                        new regTask2().execute("Last Message!");
                    }
                }
            }).start();
            //performCrop(picturePath);
        } else if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            convertImageUriToFile(imageUri, this);
            SDFile1 = new File(imagePath);

            String extension = "";
            int index = SDFile1.getName().lastIndexOf(".");
            if (index != -1) {
                extension = SDFile1.getName().substring(index + 1);
            }
            Bitmap bmImg = BitmapFactory.decodeFile(imagePath);
            Bitmap resBm = getResizedBitmap(bmImg, 500);
            adapter.add(new StikyChat("", "<img", false, timeSend, "bitmap" + imagePath, 0, 0, "", "", "", resBm,
                    SDFile1.getPath()));
            adapter.notifyDataSetChanged();
            lv.setSelection(adapter.getCount() - 1);
            Log.i("SDFile ", " $$$ " + SDFile1.getAbsolutePath());
            upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                    + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                    + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension + "&type=image"
                    + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                    + URLEncoder.encode(getResources().getString(R.string.url));
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    int serverResponseCode = uploadFile(SDFile1);
                    if (serverResponseCode == 200) {
                        Log.i("Success", " is done! ");
                        flagChatting = false;
                        flagTransfer = true;
                        messageServer = "<img";
                        msg = "Image Transfer";
                        recipientStkidGCM = recipientStkid;
                        new regTask().execute("GCM");
                        new regTask2().execute("Last Message!");
                    }
                }
            }).start();
        }
    }

    public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();
        Log.i(TAG, " Widht .. " + width);
        Log.i(TAG, " Height .. " + height);
        float bitmapRatio = (float) width / (float) height;
        Log.i(TAG, " Bitmap Ratio" + bitmapRatio);
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        Log.i(TAG, " Width .. <Image> .." + width);
        Log.i(TAG, " Height .. <Image> .." + height);
        return Bitmap.createScaledBitmap(image, width, height, true);
    }

    public int uploadFile(final File SDFile) {
        String status = "";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(upLoadServerUri);
        FileBody bin = new FileBody(SDFile);
        MultipartEntity reqEntity = new MultipartEntity();
        try {
            reqEntity.addPart("Content-Disposition", new StringBody("multipart/form-data"));
            // reqEntity.addPart("filename", new StringBody(filename));
            reqEntity.addPart("uploaded_file", bin);
            reqEntity.addPart("Content-Type", new StringBody("image/png"));
            httppost.setEntity(reqEntity);
            //Log.d("Executing Request ", httppost.getRequestLine().toString());
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //dialog.show();
                }
            });
            if (resEntity != null) {
                Log.i("content length: ", resEntity.getContentLength() + "");
                if (resEntity.getContentLength() > 0) {
                    fileNameRes = EntityUtils.toString(resEntity);
                    Log.i(TAG, " Status ... ^^ " + status);
                    return 200;
                } else {
                    status = "No Response from Server";
                    Log.i("Status----->", status);
                    return 500;
                }
            } else {
                status = "No Response from Server";
                Log.i("Status----->", status);
                return 500;
            }
        } catch (Exception e) {
            e.printStackTrace();
            status = "Unable to connect with server";
            return 500;
        }
    }

    public String getPath(Context context, Uri uri) throws URISyntaxException {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = { "_data" };
            Cursor cursor = null;

            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * @param imageUri
     * @param activity
     * @return String
     */
    public String convertImageUriToFile(Uri imageUri, Activity activity) {
        cursor = null;
        int imageID = 0;
        try {
            /*********** Which columns values want to get *******/
            String[] proj = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID,
                    MediaStore.Images.Thumbnails._ID, MediaStore.Images.ImageColumns.ORIENTATION };
            cursor = getContentResolver().query(imageUri, proj, null, null, null);

            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
            int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

            if (cursor.moveToFirst()) {

                /**************** Captured image details ************/

                /***** Used to show image on view in LoadImagesFromSDCard class ******/
                imageID = cursor.getInt(columnIndex);

                imagePath = cursor.getString(file_ColumnIndex);

                // String orientation =
                // cursor.getString(orientation_ColumnIndex);

                /*
                 * String CapturedImageDetails = " CapturedImageDetails : \n\n"
                 * +" ImageID :"+imageID+"\n" +" ThumbID :"+thumbID+"\n"
                 * +" Path :"+Path+"\n";
                 */
            }

        } finally {
            if (cursor != null) {
                Log.i("Camera ", " cursor is closed..");
            }
        }
        return "" + imageID;
    }

    public void clickSend(View v) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
        flagRecord = false;
        /*txtEditorWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
            
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //This sets a textview to the current length
            Log.i("Text ", " is changed" + s + "**");
            if (s.toString().substring(0, s.length()).equalsIgnoreCase(" ")) {
                Log.i("Can't ", " space");
            }
            // txtTitleCha.setText(String.valueOf(50 - s.length()) + " characters left");
        }
            
        public void afterTextChanged(Editable s) {
        }
        };*/

        messageServer = edTxtMsg.getText().toString();
        lv.smoothScrollToPosition(adapter.getCount() - 1);
        if (messageServer.equals("")) {
            setShakeAnimation(edTxtMsg);
            Toast.makeText(getApplicationContext(), "Enter your message", Toast.LENGTH_SHORT).show();
        } else {
            // edTxtMsg.addTextChangedListener(txtEditorWatcher);
            calcualteTodayDate();
            Log.i("Time Server ", " * " + timeSendServer);
            flagChatting = true;
            msg = edTxtMsg.getText().toString();
            new regTask().execute("Send message to ");
            adapter.add(new StikyChat("", edTxtMsg.getText().toString(), false, timeSend, "", 0, 0, "", "", "",
                    null, ""));
            lv.smoothScrollToPosition(adapter.getCount() - 1);
            edTxtMsg.setText("");
        }

    }

    private void fetchRecords() {
        flagRefresh = true;
        new regTask2().execute("Refreshing");
    }

    public void clickPay(View v) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        flagPay = true;
        //        Intent intent = new Intent("com.arctech.MAKEOFFER");
        //        intent.putExtra("recipientName", chatRecipient);
        //        intent.putExtra("recipientUrl", chatRecipientUrl);
        //        startActivity(intent);
        flagChatting = false;
        new regTask3().execute("Pay");
    }

    public void clickRecord(View v) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                calculatePixels(150f));
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
        hideKeyboard(edTxtMsg);
        flagRecord = true;
        /* LayoutInflater inflator = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         View header = inflator.inflate(R.layout.chat_talk, null);
         layoutTalk.addView(header);*/
        /*Intent intent = new Intent("com.arctech.AUDIOACTIVITY");
        startActivity(intent);*/
    }

    public void clickHoldAndTalk(View v) {
        v.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                v.setBackgroundResource(R.drawable.spin_animation);
                // Get the background, which has been compiled to an AnimationDrawable object.
                AnimationDrawable frameAnimation = (AnimationDrawable) v.getBackground();

                if (event.getAction() == event.ACTION_DOWN) {
                    onRecord(true);

                    // Start the animation (looped playback by default).
                    frameAnimation.start();
                    Toast.makeText(getBaseContext(), "Action Down", Toast.LENGTH_SHORT).show();
                } else if (event.getAction() == event.ACTION_UP) {
                    calcualteTodayDate();
                    adapter.add(new StikyChat("", "<img", false, timeSend, "voiceSend", 0, 0, "", "",
                            audiofile.getAbsolutePath(), null, ""));
                    adapter.notifyDataSetChanged();
                    lv.smoothScrollToPosition(adapter.getCount() - 1);
                    Toast.makeText(getBaseContext(), "Action Up", Toast.LENGTH_SHORT).show();
                    onRecord(false);
                    frameAnimation.stop();
                    v.setBackgroundResource(R.drawable.chat_micro);
                    upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                            + "/androidstikyhive/voicetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                            + "&toStikyBee=" + recipientStkid + "&message=voice" + "&dateTime="
                            + URLEncoder.encode(timeSendServer) + "&url="
                            + URLEncoder.encode(getResources().getString(R.string.url));
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            int serverResponseCode = uploadFile(audiofile);
                            if (serverResponseCode == 200) {
                                Log.i("Success", " is done! ");
                                flagChatting = false;
                                flagTransfer = true;
                                messageServer = "<img";
                                msg = "Voice Message";
                                recipientStkidGCM = recipientStkid;
                                new regTask().execute("GCM");
                                new regTask2().execute("Last Message!");
                            }
                        }
                    }).start();
                }
                return false;
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(
                Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    private void calcualteTodayDate() {
        start = new Date();
        SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
        SimpleDateFormat oFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        timeSend = oFormat.format(start);
        timeSendServer = oFormat2.format(start);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, " ON RESUME");
        int a;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
        flagRecord = false;
        // txtUserName = (TextView) findViewById(R.id.txtChatName);
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(QuickstartPreferences.CHAT_REGISTRATION_COMPLETE));
        if (!ChattingActivity.flagChatting) {
            // Log.i(TAG, " FLag Make Offer");
            StikyChat stikyChat = new StikyChat("", messageServer, false, timeSendOffer, "", offerId, offerStatus,
                    price, rate, name, null, "");
            //stikyChat.setFlagStikyPayChk(flagStikyPayChk);
            adapter.add(stikyChat);
            lv.smoothScrollToPosition(adapter.getCount() - 1);
            if (offerId != 0) {
                msg = "Make Offer";
            } else {
                msg = messageServer;
            }
            new regTask().execute("Send ... ");
        }
    }

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

        //for recording
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }

        // If the screen is off then the device has been locked
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        boolean isScreenOn = powerManager.isScreenOn();
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
        flagRecord = false;

        if (!isScreenOn || flagMakeOffer || flagFullPhoto) {
            // The screen has been locked
            // do stuff...
            Log.i(TAG, "Screen is on...");
            flagFullPhoto = false;
        } else {
            Log.i(TAG, "Screen is off....");
            finish();
        }

        Log.i(TAG, " REsume %%%%%%%%%%%%AAAAAAAAAAAAA");
        /* if (this.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        // DO WHATEVER YOU NEED TO DO HERE
        wasScreenOn = false;
         } else {
            
         }
        */
    }

    final class regTask extends AsyncTask<Object, Object, Object> {
        String resp;
        JSONObject objTemp, objTemp2;

        @Override
        protected Object doInBackground(Object... params) {

            try {
                if (flagChatting) {
                    objTemp = sendcodeService();
                    objTemp2 = sendcodeService2();
                }
                flagChatting = true;
                // Prepare JSON containing the GCM message content. What to send and where to send.
                JSONObject jGcmData = new JSONObject();
                JSONObject jData = new JSONObject();

                jData.put("fileName", fileNameRes);
                jData.put("msg", msg);
                jData.put("message", messageServer);
                jData.put("offerId", offerId);
                jData.put("offerStatus", offerStatus);
                jData.put("price", price);
                jData.put("rate", rate);
                jData.put("name", name);
                //mine
                jData.put("recipientStkid", pref.getString("stkid", ""));
                //other name
                jData.put("chatRecipient", pref.getString("stikyBeeName", ""));
                //other pic
                jData.put("chatRecipientUrl", pref.getString("stikyBeeLocation", ""));
                Log.i(TAG, " Chat Chat %%%%% " + senderToken + " YOU YOU ....." + recipientToken);
                //mine
                jData.put("senderToken", senderToken);

                //other
                jData.put("recipientToken", recipientToken);

                // Where to send GCM message.
                jGcmData.put("to", recipientToken);

                //jGcmData.put("to", "/topics/global");

                // What to send in GCM message.
                jGcmData.put("data", jData);

                // Create connection to send GCM Message request.
                URL url = new URL("https://android.googleapis.com/gcm/send");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty("Authorization", "key=" + API_KEY);
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);

                // Send GCM message content.
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(jGcmData.toString().getBytes());

                // Read GCM response.
                InputStream inputStream = conn.getInputStream();
                //resp = IOUtils.toString(inputStream);
                //System.out.println(resp);
                System.out.println("Check your device/emulator for notification or logcat for "
                        + "confirmation of the receipt of the GCM message.");
            } catch (IOException e) {
                System.out.println("Unable to send GCM message.");
                System.out.println("Please ensure that API_KEY has been replaced by the server "
                        + "API key, and that the device's registration token is correct (if specified).");
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (objTemp != null && objTemp2 != null) {
                try {
                    if (objTemp.getString("status").toString().equals("success")
                            && objTemp2.getString("status").toString().equals("success")) {
                        Log.i("Success ", " web service");

                        // dbHelper.deleteChatMore();
                        JSONObject obj = objTemp2.getJSONObject("updateMsg");
                        int id = obj.getInt("id");
                        String fromStikyBee = obj.getString("fromStikyBee");
                        String toStikyBee = obj.getString("toStikyBee");
                        String message = obj.getString("message");
                        String updateDate = obj.getString("updateDate");
                        // int status = obj.getInt("status");
                        String chatStkid = obj.getString("chatStkid");
                        String firstname = obj.getString("firstname");
                        String lastname = obj.getString("lastname");
                        if (lastname.equals("null")) {
                            lastname = "";
                        }
                        String name = firstname + " " + lastname;
                        String profilePiture = obj.getString("profilePicture");
                        Log.i("Chat More... ", " >>>");

                        dbHelper.deleteChatMoreById(id);
                        List<StikyChatMore> tempList = dbHelper.getChatMore();

                        dbHelper.deleteChatMore();
                        dbHelper.insertChatMore(id, fromStikyBee, toStikyBee, message, updateDate, 0, name,
                                profilePiture, chatStkid, 0);
                        for (StikyChatMore tempChatMore : tempList) {
                            dbHelper.insertChatMore(tempChatMore.getId(), tempChatMore.getFromStikyBee(),
                                    tempChatMore.getToStikyBee(), tempChatMore.getMessage(),
                                    tempChatMore.getUpdateDate(), tempChatMore.getStatus(), tempChatMore.getName(),
                                    tempChatMore.getProfileUrl(), tempChatMore.getChatStkid(),
                                    tempChatMore.getStatusMsgUpdate());
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * @return JSONObject
         * @throws JSONException
         */
        public JSONObject sendcodeService() throws JSONException {

            JSONObject objTemp = null;
            String url2 = "/androidstikyhive/index.php/api/users/insertChatMsg/format/json";

            try {

                JSONObject obj = new JSONObject();

                obj.put("fromStikyBee", pref.getString("stkid", ""));
                obj.put("toStikyBee", recipientStkid);
                obj.put("message", messageServer);
                obj.put("createDate", timeSendServer);
                //obj.put("createDate", "2015-09-01");
                objTemp = ws.insertORupdateObj(getResources().getString(R.string.url), url2, obj);

            } catch (Exception e) {
                // TODO: handle exception

            } finally {

            }
            return objTemp;
        }

        /**
         * @return JSONObject
         * @throws org.json.JSONException
         */
        public JSONObject sendcodeService2() throws JSONException {
            JSONObject objTemp = null;
            String url2 = "/androidstikyhive/index.php/api/users/checkLastMessage/format/json";

            try {
                JSONObject obj = new JSONObject();
                Log.i(TAG, "" + pref.getString("stkid", ""));
                Log.i(TAG, "" + recipientStkid + " " + messageServer + " " + timeSendServer);
                obj.put("fromStikyBee", pref.getString("stkid", ""));
                obj.put("toStikyBee", recipientStkid);
                obj.put("message", messageServer);
                obj.put("createDate", timeSendServer);

                objTemp = ws.insertORupdateObj(getResources().getString(R.string.url), url2, obj);

            } catch (Exception e) {
                // TODO: handle exception

            } finally {

            }
            return objTemp;
        }
    }

    final class regTask2 extends AsyncTask<Object, Object, Object> {
        JSONObject objTemp, objContact, objMessages, objLastMsg;

        @Override
        protected Object doInBackground(Object... params) {

            try {
                if (flagAddContact) {
                    objContact = sendcodeService2();
                } else if (flagNotifi) {
                    objMessages = sendcodeService(recipientStkidGCM);
                } else if (flagRefresh) {
                    objTemp = sendcodeService(recipientStkid);
                }
                objLastMsg = sendcodeService3();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (flagAddContact) {
                if (objContact != null) {
                    try {
                        if (objContact.getString("status").toString().equals("success")) {
                            Toast.makeText(getApplicationContext(), "Contact saved.", Toast.LENGTH_SHORT).show();
                            imgViewAddCon.setVisibility(View.INVISIBLE);
                            layoutLabel.setVisibility(View.GONE);
                            JSONArray jsonArr = objContact.getJSONArray("contacts");
                            dbHelper.deleteChatContact();
                            for (int i = 0; i < jsonArr.length(); i++) {
                                JSONObject json = jsonArr.getJSONObject(i);
                                int id = json.getInt("id");
                                String stkid = json.getString("stkid");
                                String name = json.getString("firstName") + " " + json.getString("lastName");
                                String contactId = json.getString("contactId");
                                String profilePicture = json.getString("profilePicture");
                                String createDate = json.getString("createDate");
                                dbHelper.insertChatContact(id, name, stkid, contactId, profilePicture, createDate);
                            }
                            flagAddContact = false;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                flagAddContact = false;
            } else if (flagNotifi) {
                if (objMessages != null) {
                    try {
                        if (objMessages.getString("status").toString().equals("success")) {
                            dbHelper.deleteStikyChat();
                            JSONArray jsonArr = objMessages.getJSONArray("messages");
                            for (int i = 0; i < jsonArr.length(); i++) {
                                JSONObject json = jsonArr.getJSONObject(i);
                                int id = json.getInt("id");
                                String fromStikyBee = json.getString("fromStikyBee");
                                String toStikyBee = json.getString("toStikyBee");
                                String message = json.getString("message");
                                String createDate = json.getString("createDate");
                                String fileName = json.getString("fileName");
                                int offerId = 0, offerStatus = 0, skillId = 0;
                                String price = null, rate = null, name = null;
                                if (json.getString("offerId") != "null") {
                                    offerId = json.getInt("offerId");
                                    offerStatus = json.getInt("offerStatus");
                                    skillId = json.getInt("skillId");
                                    price = json.getString("price");
                                    rate = json.getString("rate");
                                    name = json.getString("name");
                                }
                                Log.i("Chatting createDate : ", " *" + createDate);
                                dbHelper.insertStikyChat(id, fromStikyBee, toStikyBee, message, createDate, offerId,
                                        offerStatus, skillId, price, rate, name, fileName);
                            }
                            rows = objMessages.getInt("rows");

                        } else {

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Log.i(TAG,
                            " senderToken " + senderToken + " ..... " + " recipient Token &&&& " + senderTokenGCM);
                    Log.i(TAG, " GCM name " + recipientNameGCM);
                    Intent intent = new Intent("com.arctech.CHATTING");
                    intent.putExtra("recipientStkid", recipientStkidGCM);
                    intent.putExtra("chatRecipient", recipientNameGCM);
                    intent.putExtra("chatRecipientUrl", recipientProfileGCM);
                    intent.putExtra("senderToken", senderToken);
                    intent.putExtra("recipientToken", senderTokenGCM);
                    intent.putExtra("noti", false);
                    intent.putExtra("message", messageGCM);
                    intent.putExtra("rows", rows);

                    // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    int requestID = (int) System.currentTimeMillis();
                    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
                            requestID /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

                    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                            getApplicationContext()).setSmallIcon(R.drawable.ic_launcher)
                                    .setContentTitle("StikyHive Message").setContentText(messageGCM)
                                    .setAutoCancel(true).setSound(defaultSoundUri).setContentIntent(pendingIntent);

                    NotificationManager notificationManager = (NotificationManager) getSystemService(
                            Context.NOTIFICATION_SERVICE);

                    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
                }
            } else if (flagRefresh) {
                if (objTemp != null) {
                    try {
                        if (objTemp.getString("status").toString().equals("success")) {
                            Log.i("Success ", " web service");
                            JSONArray jsonArr = objTemp.getJSONArray("messages");
                            dbHelper.deleteStikyChat();
                            for (int i = 0; i < jsonArr.length(); i++) {
                                JSONObject json = jsonArr.getJSONObject(i);
                                int id = json.getInt("id");
                                String fromStikyBee = json.getString("fromStikyBee");
                                String toStikyBee = json.getString("toStikyBee");
                                String message = json.getString("message");
                                String createDate = json.getString("createDate");
                                String fileName = json.getString("fileName");
                                int offerId = 0, offerStatus = 0, skillId = 0;
                                String price = null, rate = null, name = null;
                                if (json.getString("offerId") != "null") {
                                    offerId = json.getInt("offerId");
                                    offerStatus = json.getInt("offerStatus");
                                    skillId = json.getInt("skillId");
                                    price = json.getString("price");
                                    rate = json.getString("rate");
                                    name = json.getString("name");
                                }
                                Log.i("Chatting createDate : ", " *" + createDate);
                                dbHelper.insertStikyChat(id, fromStikyBee, toStikyBee, message, createDate, offerId,
                                        offerStatus, skillId, price, rate, name, fileName);
                            }
                            flagRefresh = false;
                            onRefreshComplete(dbHelper.getStikyChat());
                        } else {
                            flagRefresh = false;
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "No data to refresh", Toast.LENGTH_SHORT).show();
                }
                flagRefresh = false;
            }
            if (objLastMsg != null) {
                try {
                    if (objLastMsg.getString("status").toString().equals("success")) {
                        Log.i("Success ", " web service");

                        JSONArray array = objLastMsg.getJSONArray("contacts");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject obj = array.getJSONObject(i);
                            int id = obj.getInt("id");
                            String fromStikyBee = obj.getString("fromStikyBee");
                            String toStikyBee = obj.getString("toStikyBee");
                            String message = obj.getString("message");
                            String updateDate = obj.getString("updateDate");
                            // int status = obj.getInt("status");
                            String chatStkid = obj.getString("chatStkid");
                            String firstname = obj.getString("firstname");
                            String lastname = obj.getString("lastname");
                            if (lastname.equals("null")) {
                                lastname = "";
                            }
                            String profilePiture = obj.getString("profilePicture");

                            StikyChatMore chatMore = new StikyChatMore();
                            chatMore.setId(id);
                            chatMore.setFromStikyBee(fromStikyBee);
                            chatMore.setToStikyBee(toStikyBee);
                            chatMore.setMessage(message);
                            chatMore.setUpdateDate(updateDate);
                            chatMore.setChatStkid(chatStkid);
                            //chatMore.setStatus(status);
                            chatMore.setName(firstname + " " + lastname);
                            chatMore.setProfileUrl(profilePiture);
                            String name = firstname + " " + lastname;
                            int noRoom = 0;

                            if (chatStkid.equals(recipientStkidGCM)) {
                                Log.i("ChatMoreActivity", "is equal ***** ");
                                boolean flagChat = false;
                                for (int j = 0; j < dbHelper.getChatMore().size(); j++) {
                                    StikyChatMore tempChatMore = dbHelper.getChatMore().get(j);
                                    if (tempChatMore.getId() == id) {
                                        Log.i(TAG, " Chat more == id");
                                        flagChat = true;
                                        noRoom = j;
                                        break;
                                    } else {
                                        Log.i(TAG, " Chat more != id");
                                        flagChat = false;
                                    }
                                }
                                if (flagChat) {
                                    Log.i(TAG, " Chat more .. status 1");
                                    if (!((toStikyBee.equals(recipientStkid))
                                            || fromStikyBee.equals(recipientStkid)))
                                        dbHelper.updateChatMoreByChatStkid(message, 1, updateDate, recipientStkid);
                                    else
                                        dbHelper.updateChatMoreByChatStkid(message, 0, updateDate, recipientStkid);
                                    List<StikyChatMore> tempList = dbHelper.getChatMore();
                                    Collections.swap(tempList, 0, noRoom);
                                    dbHelper.deleteChatMore();
                                    for (StikyChatMore tempChatMore : tempList) {
                                        dbHelper.insertChatMore(tempChatMore.getId(),
                                                tempChatMore.getFromStikyBee(), tempChatMore.getToStikyBee(),
                                                tempChatMore.getMessage(), tempChatMore.getUpdateDate(),
                                                tempChatMore.getStatus(), tempChatMore.getName(),
                                                tempChatMore.getProfileUrl(), tempChatMore.getChatStkid(),
                                                tempChatMore.getStatusMsgUpdate());
                                    }
                                } else {
                                    Log.i(TAG, " Chat more .. status 0");
                                    List<StikyChatMore> tempList = dbHelper.getChatMore();
                                    dbHelper.deleteChatMore();
                                    dbHelper.insertChatMore(id, fromStikyBee, toStikyBee, message, updateDate, 0,
                                            name, profilePiture, chatStkid, 1);
                                    for (StikyChatMore tempChatMore : tempList) {
                                        dbHelper.insertChatMore(tempChatMore.getId(),
                                                tempChatMore.getFromStikyBee(), tempChatMore.getToStikyBee(),
                                                tempChatMore.getMessage(), tempChatMore.getUpdateDate(),
                                                tempChatMore.getStatus(), tempChatMore.getName(),
                                                tempChatMore.getProfileUrl(), tempChatMore.getChatStkid(),
                                                tempChatMore.getStatusMsgUpdate());
                                    }
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            flagNotifi = false;
        }

        /**
         * @return JSONObject
         * @throws JSONException
         */
        /**
         * @return JSONObject
         * @throws JSONException
         */
        public JSONObject sendcodeService(String reStkid) throws JSONException {

            JSONObject objTemp = null;
            String url2 = "/androidstikyhive/index.php/api/users/selectChatMsgs/format/json";

            try {
                JSONObject obj = new JSONObject();
                Log.i(TAG, "From " + pref.getString("stkid", ""));
                Log.i(TAG, "to " + reStkid);
                obj.put("fromStikyBee", pref.getString("stkid", ""));
                obj.put("toStikyBee", reStkid);
                Log.i("Limit Message of limit ", " %%%%%%%%%% " + limitMsg);
                obj.put("limit", limitMsg);

                objTemp = ws.insertORupdateObj(getResources().getString(R.string.url), url2, obj);

            } catch (Exception e) {
                // TODO: handle exception

            } finally {

            }
            return objTemp;
        }

        /**
         * @return JSONObject
         * @throws JSONException
         */
        /**
         * @return JSONObject
         * @throws JSONException
         */
        public JSONObject sendcodeService2() throws JSONException {

            JSONObject objTemp = null;
            String url2 = "/androidstikyhive/index.php/api/users/insertContact/format/json";

            try {
                JSONObject obj = new JSONObject();

                obj.put("stkid", pref.getString("stkid", ""));
                obj.put("contactId", recipientStkid);

                objTemp = ws.insertORupdateObj(getResources().getString(R.string.url), url2, obj);

            } catch (Exception e) {
                // TODO: handle exception

            } finally {

            }
            return objTemp;
        }

        /**
         * @return JSONObject
         * @throws org.json.JSONException
         */
        public JSONObject sendcodeService3() throws JSONException {
            JSONObject objTemp = null;
            String url2 = "/androidstikyhive/index.php/api/users/checkLastMsgByUserId/format/json";

            try {
                JSONObject obj = new JSONObject();
                Log.i(TAG, "" + pref.getString("stkid", ""));
                //Log.i(TAG, "" + recipientStkid + " " + messageServer + " " + timeSendServer);
                obj.put("fromStikyBee", pref.getString("stkid", ""));

                objTemp = ws.insertORupdateObj(getResources().getString(R.string.url), url2, obj);

            } catch (Exception e) {
                // TODO: handle exception

            } finally {

            }
            return objTemp;
        }
    }

    final class regTask3 extends AsyncTask<Object, Object, Object>
            implements android.content.DialogInterface.OnDismissListener {
        JSONObject objTemp;

        @Override
        protected void onPreExecute() {
            dialog.setOnDismissListener(this);
            dialog.show();
        }

        @Override
        protected Object doInBackground(Object... params) {

            try {
                objTemp = sendcodeService();

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            if (flagPay) {
                if (objTemp != null) {
                    try {
                        if (objTemp.getString("status").toString().equals("success")) {
                            sellListBySellerMarket = new ArrayList<SellerMarket>();
                            JSONArray sellersJArray = objTemp.getJSONArray("result");

                            for (int i = 0; i < sellersJArray.length(); i++) {
                                JSONObject jObj = sellersJArray.getJSONObject(i);
                                int skillId = jObj.getInt("skillId");
                                String expiredDate = jObj.getString("expiredDate");
                                String location = jObj.getString("location");
                                String vLocation = jObj.getString("videoLocation");
                                String thumbLocation = jObj.getString("thumbnailLocation");
                                String caption = jObj.getString("caption");
                                int catId = jObj.getInt("catId");
                                String name = jObj.getString("name");
                                String skillDesc = jObj.getString("skillDesc");
                                String stkid = jObj.getString("stkid");
                                int type = jObj.getInt("type");
                                String profilePicture = jObj.getString("profilePicture");
                                String fname = jObj.getString("firstname");
                                String lname = jObj.getString("lastname");
                                String beeInfo = jObj.getString("beeInfo");
                                double price = 0;
                                if (jObj.getString("price") != "null") {
                                    price = jObj.getDouble("price");
                                }
                                String rateName = jObj.getString("ratename");
                                Log.i("info ", skillId + " " + location + " " + vLocation + " " + thumbLocation
                                        + " " + profilePicture);
                                String summary = jObj.getString("summary");
                                int likeCount = 0;
                                if (jObj.getString("likeCount") != "null")
                                    likeCount = jObj.getInt("likeCount");
                                String issuedDate = jObj.getString("issuedDate");
                                String email = jObj.getString("email");
                                SellerMarket sellerMarket = new SellerMarket(skillId, issuedDate, expiredDate,
                                        location, vLocation, thumbLocation, caption, catId, name, skillDesc, stkid,
                                        type, profilePicture, fname, lname, beeInfo, price, rateName, summary,
                                        likeCount, email);
                                sellListBySellerMarket.add(sellerMarket);
                            }
                            Intent intent = new Intent("com.arctech.MAKEOFFER");
                            intent.putExtra("recipientStkid", recipientStkid);
                            intent.putExtra("recipientName", chatRecipient);
                            intent.putExtra("recipientUrl", chatRecipientUrl);
                            startActivity(intent);
                            flagMakeOffer = true;
                        } else {
                            sellListBySellerMarket = new ArrayList<SellerMarket>();
                            Toast.makeText(getApplicationContext(), "No skills uploaded yet!", Toast.LENGTH_SHORT)
                                    .show();
                        }
                        flagPay = false;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        /**
         * @return JSONObject
         * @throws JSONException
         */
        /**
         * @return JSONObject
         * @throws JSONException
         */
        public JSONObject sendcodeService() throws JSONException {

            JSONObject objTemp = null;
            String url2 = "/androidstikyhive/index.php/api/users/getSellAll/format/json";

            try {
                JSONObject obj = new JSONObject();

                obj.put("limit", 0);
                obj.put("catId", 0);
                obj.put("stkid", recipientStkid);

                objTemp = ws.insertORupdateObj(getResources().getString(R.string.url), url2, obj);

            } catch (Exception e) {
                // TODO: handle exception

            } finally {

            }
            return objTemp;
        }

        @Override
        public void onDismiss(DialogInterface dialog) {

        }

    }

    /**
     * When the AsyncTask finishes, it calls onRefreshComplete(), which updates the data in the
     * ListAdapter and turns off the progress bar.
     */
    private void onRefreshComplete(List<StikyChatTb> chatRefreshList) {
        Log.i("Swipe Refresh ", "onRefreshComplete");

        adapter = new ChatArrayAdapter(this, R.layout.chatting_listview, faceSemi_bold, faceRegular, recipientStkid,
                senderToken, recipientToken);
        lv.setAdapter(adapter);

        Log.i("Adapter Count ", " " + adapter.getCount());
        Log.i("Chat History size ", " " + chatRefreshList.size());
        if (chatRefreshList.size() > 0) {
            Collections.reverse(chatRefreshList);
            for (StikyChatTb chatTb : chatRefreshList) {
                String getDate = chatTb.getSendDate();
                String fromStikyBee = chatTb.getSender();
                try {
                    String createDate = dateFormat2.format(dateFormat.parse(getDate));
                    if (fromStikyBee.equals(pref.getString("stkid", ""))) {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null, chatTb.getOriFName()));
                    } else {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null, chatTb.getOriFName()));
                    }
                    //lv.smoothScrollToPosition(adapter.getCount() - 1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        // Stop the refreshing indicator
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onBackPressed() {
        if (flagRecord) {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 0);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            layoutTalk.setLayoutParams(params);
            layoutTalk.setGravity(Gravity.CENTER);
            flagRecord = false;
        } else if (noti) {
            Intent intent = new Intent("com.arctech.BROWSEACTIVITY");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        } else {
            super.onBackPressed();
            StikyChatMoreActivity.flagStart = false;
            finish();
        }
    }

    private int calculatePixels(float a) {
        float fpixels = metrics.density * a;
        int b = (int) (fpixels + 0.5f);
        return b;
    }

    /**
     * Use shake animation of View for Validation
     *
     * @param v
     */
    public void setShakeAnimation(View v) {
        Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
        v.startAnimation(shake);
    }

    //for recording
    private void onRecord(boolean start) {
        if (start) {
            startRecording();
        } else {
            stopRecording();
        }
    }

    private void startRecording() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        //get current date time with Date()
        Date date = new Date();
        String customDate = dateFormat.format(date);

        File myDataPath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/My Recordings");
        if (!myDataPath.exists())
            myDataPath.mkdir();

        audiofile = new File(myDataPath + "/" + customDate + ".3gp");
        /* mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
         mFileName +=  "/" + customDate + ".3gp";
            
        // String mfileName = mFileName + customDate + ".3gp";
        // File newFile = new File(dir, fileName);*/

        mRecorder = new MediaRecorder();
        mRecorder.setMaxDuration(30000);
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(audiofile.getAbsolutePath());
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(TAG, "prepare() failed");
        }

        mRecorder.start();
    }

    private void stopRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
    }
}