com.arctech.stikyhive.ChattingActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.arctech.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.arctech.stikyhive;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
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.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
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 int limitMsg;
    public static boolean firstConnect, noti;
    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;
    private ListView lv;
    private ProgressDialog dialog;
    private static ChatArrayAdapter adapter;

    SimpleDateFormat dateFormat, dateFormat2;
    private Date start;
    List<StikyChatTb> listHistory;
    List<ChatContact> listChatContact;
    private String timeSend, timeSendServer, recipientProfileGCM, recipientStkidGCM, messageGCM, recipientNameGCM,
            recipientTokenGCM, senderTokenGCM;
    private String chatRecipient, chatRecipientUrl, senderToken, recipientToken, message, messageServer;
    int rows;
    private boolean flagRefresh, flagAddContact, flagNotifi, flagPay;

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

    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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        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");

        pref = PreferenceManager.getDefaultSharedPreferences(this);
        ws = new JsonWebService();
        dbHelper = new DBHelper(this);
        dialog = new ProgressDialog(this);
        listChatContact = new ArrayList<>();
        listChatContact = dbHelper.getChatContact();
        Log.i(" Chat Contact ", " " + listChatContact.size());
        //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);

        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);
        // lv.smoothScrollToPosition(adapter.getCount() - 1);

        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(getApplicationContext(), R.layout.messaging_listview, faceSemi_bold,
                faceRegular);
        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 (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 = "";
        if (chatRecipientUrl.contains("http")) {
            url = chatRecipientUrl;
        } else {
            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 (StikyChatTb chatTb : listHistory) {
                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, ""));
                    } else {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate, ""));
                    }
                    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);
                messageGCM = sharedPreferences.getString("message", "");
                recipientProfileGCM = sharedPreferences.getString("chatRecipientUrl", "");
                recipientNameGCM = sharedPreferences.getString("chatRecipientName", "");
                recipientStkidGCM = sharedPreferences.getString("recipientStkid", "");
                recipientTokenGCM = sharedPreferences.getString("recipientToken", "");
                senderTokenGCM = sharedPreferences.getString("senderToken", "");

                Log.i(TAG, "..." + recipientStkidGCM.trim() + " STKID " + recipientStkid.trim() + ":");
                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);
                        StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend, "");
                        Log.i(TAG, " First " + message + " " + recipientProfileGCM + " " + timeSend);
                        Log.i(TAG, "User " + txtUserName.getText().toString());
                        //txtUserName.setText(message);
                        Log.i(TAG, "User 2 " + txtUserName.getText().toString());
                        adapter.add(stikyChat);
                        adapter.notifyDataSetChanged();
                        //new regTask2().execute("Obj ");
                        lv.smoothScrollToPosition(adapter.getCount() - 1);
                    } else {
                        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;
                }
            }
        };
    }

    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 clickSend(View v) {

        /*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();
        if (messageServer.equals("")) {
            Toast.makeText(getApplicationContext(), "Enter your message", Toast.LENGTH_SHORT).show();
        } else {
            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);
            // edTxtMsg.addTextChangedListener(txtEditorWatcher);
            Log.i("Time Server ", " * " + timeSendServer);
            new regTask().execute("Send message to ");
            adapter.add(new StikyChat("", edTxtMsg.getText().toString(), false, timeSend, ""));
            lv.smoothScrollToPosition(adapter.getCount() - 1);
            edTxtMsg.setText("");
        }

    }

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

    public void clickPay(View v) {
        flagPay = true;
        //        Intent intent = new Intent("com.arctech.MAKEOFFER");
        //        intent.putExtra("recipientName", chatRecipient);
        //        intent.putExtra("recipientUrl", chatRecipientUrl);
        //        startActivity(intent);
        new regTask3().execute("Pay");
    }

    @Override
    protected void onResume() {
        super.onResume();
        // txtUserName = (TextView) findViewById(R.id.txtChatName);
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(QuickstartPreferences.CHAT_REGISTRATION_COMPLETE));
        // txtUserName.invalidate();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, " REsume %%%%%%%%%%%%AAAAAAAAAAAAA");
        finish();
    }

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

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

            try {
                objTemp = sendcodeService();
                objTemp2 = sendcodeService2();
                // Prepare JSON containing the GCM message content. What to send and where to send.
                JSONObject jGcmData = new JSONObject();
                JSONObject jData = new JSONObject();
                jData.put("message", messageServer);
                jData.put("recipientStkid", pref.getString("stkid", ""));
                jData.put("chatRecipient", pref.getString("stikyBeeName", ""));
                jData.put("chatRecipientUrl", pref.getString("stikyBeeLocation", ""));
                Log.i(TAG, " Chat Chat %%%%% " + senderToken + " YOU YOU ....." + recipientToken);
                jData.put("senderToken", senderToken);
                jData.put("recipientToken", recipientToken);

                //jData.put("stkid", )
                //  String recipientToken = edTxtMsg.getString("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();
                        JSONArray array = objTemp2.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;
                            Log.i("Name ", name);
                            dbHelper.insertChatMore(id, fromStikyBee, toStikyBee, message, updateDate, status, name,
                                    profilePiture, chatStkid);
                        }
                    }
                } 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;

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

            try {
                if (flagAddContact) {
                    objContact = sendcodeService2();
                } else if (flagNotifi) {
                    objMessages = sendcodeService(recipientStkidGCM);
                } else {
                    objTemp = sendcodeService(recipientStkid);

                }
            } 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();
                    }
                }
            } 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");
                                Log.i("Chatting createDate : ", " *" + createDate);
                                dbHelper.insertStikyChat(id, fromStikyBee, toStikyBee, message, createDate);
                            }
                            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);
                    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
                            0 /* Request code */, intent, PendingIntent.FLAG_CANCEL_CURRENT);

                    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 (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");
                                Log.i("Chatting createDate : ", " *" + createDate);
                                dbHelper.insertStikyChat(id, fromStikyBee, toStikyBee, message, createDate);
                            }
                            flagRefresh = false;
                            onRefreshComplete(dbHelper.getStikyChat());
                        } else {
                            flagRefresh = false;
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

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

    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 = jObj.getDouble("price");
                                String rateName = jObj.getString("ratename");
                                Log.i("info ", skillId + " " + location + " " + vLocation + " " + thumbLocation
                                        + " " + profilePicture);

                                SellerMarket sellerMarket = new SellerMarket(skillId, expiredDate, location,
                                        vLocation, thumbLocation, caption, catId, name, skillDesc, stkid, type,
                                        profilePicture, fname, lname, beeInfo, price, rateName);
                                sellListBySellerMarket.add(sellerMarket);
                            }
                            Intent intent = new Intent("com.arctech.MAKEOFFER");
                            intent.putExtra("recipientStkid", recipientStkid);
                            intent.putExtra("recipientName", chatRecipient);
                            intent.putExtra("recipientUrl", chatRecipientUrl);
                            startActivity(intent);
                        } 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(getApplicationContext(), R.layout.messaging_listview, faceSemi_bold,
                faceRegular);
        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, ""));
                    } else {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate, ""));
                    }
                    //lv.smoothScrollToPosition(adapter.getCount() - 1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        // Stop the refreshing indicator
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onBackPressed() {
        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();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, " On STart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //finish();
        Log.i(TAG, " ON Destrory");
    }
}