Wednesday 29 January 2014

Create GIF Wallpapaer

Write below code in main xml file

<?xml version="1.0" encoding="utf-8"?>
<wallpaper xmlns:android="http://schemas.android.com/apk/res/android" />

Create raw folder in below res folder and put your GIF file in that raw folder.


Create Service Class in scr folder name MyService and write below code in that service



import java.io.IOException;
import java.io.InputStream;

import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.Handler;
import android.os.SystemClock;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.SurfaceHolder;

public class MyService extends WallpaperService {
    static final String TAG = "MyService";
    static final Handler mNyanHandler = new Handler();

    /**
     * @see android.service.wallpaper.WallpaperService#onCreate()
     */
    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * @see android.service.wallpaper.WallpaperService#onCreateEngine()
     */
    @Override
    public Engine onCreateEngine() {
        try {
            return new NyanEngine();
        } catch (IOException e) {
            Log.w(TAG, "Error creating NyanEngine", e);
            stopSelf();
            return null;
        }
    }

    class NyanEngine extends Engine {
        private final Movie mNyan;
        private final int mNyanDuration;
        private final Runnable mNyanNyan;
        float mScaleX;
        float mScaleY;
        int mWhen;
        long mStart;

        NyanEngine() throws IOException {
            InputStream is = getResources().openRawResource(R.raw.christmas);
            if (is != null) {
                try {
                    mNyan = Movie.decodeStream(is);
                    mNyanDuration = mNyan.duration();
                } finally {
                    is.close();
                }
            } else {
                throw new IOException("Unable to open R.raw.nyan");
            }

            mWhen = -1;
            mNyanNyan = new Runnable() {
                public void run() {
                    nyan();
                }
            };
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            mNyanHandler.removeCallbacks(mNyanNyan);
        }

        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);
            if (visible) {
                nyan();
            } else {
                mNyanHandler.removeCallbacks(mNyanNyan);
            }
        }

        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            super.onSurfaceChanged(holder, format, width, height);
            mScaleX = width / (1f * mNyan.width());
            mScaleY = height / (1f * mNyan.height());
            nyan();
        }

        @Override
        public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep,
                float yOffsetStep, int xPixelOffset, int yPixelOffset) {
            super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
            nyan();
        }

        void nyan() {
            tick();
            SurfaceHolder surfaceHolder = getSurfaceHolder();
            Canvas canvas = null;
            try {
                canvas = surfaceHolder.lockCanvas();
                if (canvas != null) {
                    nyanNyan(canvas);
                }
            } finally {
                if (canvas != null) {
                    surfaceHolder.unlockCanvasAndPost(canvas);
                }
            }
            mNyanHandler.removeCallbacks(mNyanNyan);
            if (isVisible()) {
                mNyanHandler.postDelayed(mNyanNyan, 1000L/25L);
            }
        }

        void tick() {
            if (mWhen == -1L) {
                mWhen = 0;
                mStart = SystemClock.uptimeMillis();
            } else {
                long mDiff = SystemClock.uptimeMillis() - mStart;
                mWhen = (int) (mDiff % mNyanDuration);
            }
        }

        void nyanNyan(Canvas canvas) {
            canvas.save();
            canvas.scale(mScaleX, mScaleY);
            mNyan.setTime(mWhen);
            mNyan.draw(canvas, 0, 0);
            canvas.restore();
        }
    }
}

below is my manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gifwall"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <service
            android:label="@string/app_name"
            android:name=".MyService"
            android:permission="android.permission.BIND_WALLPAPER">
            <intent-filter>
                <action android:name="android.service.wallpaper.WallpaperService" />
            </intent-filter>
            <meta-data android:name="android.service.wallpaper" android:resource="@layout/main_xml" />
        </service>
    </application>

</manifest>

Tuesday 3 December 2013

Add pin point on Map V2

When you have latitude and longitude then use this code

                                if(!TextUtils.isEmpty(checklat) && !TextUtils.isEmpty(checklon)){
                                        new Mybitmap().execute();
                                }


public class Mybitmap extends AsyncTask<Void, Void, Bitmap>{
        @Override
        protected Bitmap doInBackground(Void... params) {
            // TODO Auto-generated method stub
            abc = imgloader.getBitmap(checkimg);
            return abc;
        }
       
        @Override
        protected void onPostExecute(
                Bitmap result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            try{
            if(result != null){
                final LatLng latlong = new LatLng((Double.parseDouble(checklat)), (Double.parseDouble(checklon)));
                  Log.i(tag, "Latitude and Longitude ...."+latlong);
           
                  map.addMarker(new MarkerOptions()
                    .position(latlong)
                    .title(checktitle + " " +checksdateformate).icon(BitmapDescriptorFactory.fromBitmap(result)));
                map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlong, 20));
                map.animateCamera(CameraUpdateFactory.zoomTo(20), 2000, null);                                               
            }}
            catch(Exception e){
                e.printStackTrace();
            }
        }
    };

Tuesday 15 October 2013

Set wallpaper from gallery

 final int RESULT_LOAD_IMAGE=100;

On button Click 

Intent i = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, 100);


@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
         if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
               String wallpaper = selectedWallpaperImage(getApplicationContext(),data);
               WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
             
               try {
    wallpaperManager.setBitmap(BitmapFactory.decodeFile(wallpaper));
                             //this line of code will set the selected image as your wallpaper...........
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }}
    }


public static String selectedWallpaperImage(Context context,Intent data){
             Uri selectedImage = data.getData();
     String[] filePathColumn = { MediaStore.Images.Media.DATA };

     Cursor cursor = context.getContentResolver().query(selectedImage,
             filePathColumn, null, null, null);
     cursor.moveToFirst();

     int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
     String picturePath = cursor.getString(columnIndex);
     cursor.close();
return picturePath;
}


and add permission  <uses-permission android:name="android.permission.SET_WALLPAPER" />

And if you want direct set image from application resource 

WallpaperManager myWallpaperManager = WallpaperManager
            .getInstance(getApplicationContext());
          try {
           //set wallpaper picture from resource here
           myWallpaperManager.setResource(R.drawable.andr_gp);
           Toast.makeText(getApplicationContext(),"Success set as wallpaper",22).show();
          } catch (IOException e) {
              Toast.makeText(getApplicationContext(),"Error set as wallpaper",22).show();
          } 

Image upload

When i want to upload image into web server 
 GetNameValue nv = new GetNameValue();
String signupop = chngpassop
                        .getOPName(Utility.OPERATION_NAME);


List<NameValuePair> nvp = nv.getMyInfoEditDetail(userfname,
                        userlname, usermobile, userhomephone, userworkphone,
                        userdob, strheight, strwight, streyecolor,
                        strhaircolor, strtimepref, selectedImagePath, user_id,useremail);
                if(!TextUtils.isEmpty(selectedImagePath)){
                    result = httpPost.uploadUserImage(
Utility.SIGNUP_PAGE
                            + signupop, nvp);
                }else{
                    result = httpPost.post(
Utility.SIGNUP_PAGE
                            + signupop, nvp);
                }


my http post class having function for upload image to server as define below

public String uploadUserImage(String op,List<NameValuePair> nvp)
    {
        try
        {
            HttpConnectionParams.setConnectionTimeout(params,TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(params,TIMEOUT_MILLISEC);
          
                HttpContext localContext = new BasicHttpContext();
               // System.out.println("Server Link: "+serverurl+op);
                post = new HttpPost(serverurl+op);

                try {
                    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

                    //System.out.println("Upload Image: "+nvp);
                    if(nvp != null)
                    {
                         for(int index=0; index < nvp.size(); index++)
                         {
                             if(nvp.get(index).getName().equalsIgnoreCase("user_photo"))
                            {
                                if(nvp.get(index).getName().equalsIgnoreCase("user_photo"))
                                {
                                  // If the key equals to "U_PHOTO", we use FileBody to transfer the data
                                    multipartEntity.addPart(nvp.get(index).getName(), new FileBody(new File (nvp.get(index).getValue())));
                                }
                                else
                                {
                                    // Normal string data
                                    multipartEntity.addPart(nvp.get(index).getName(), new StringBody(nvp.get(index).getValue()));
                                    }
                                 }
                             else
                             {
                                if(nvp.get(index).getName().equalsIgnoreCase("user_photo"+index))
                                {
                                    //System.out.println("---In if UMI_NAME---");
                                    multipartEntity.addPart(nvp.get(index).getName(), new FileBody(new File (nvp.get(index).getValue())));
                                }
                                else
                                {
                                    // Normal string data
                                    //System.out.println("---In else UMI_NAME---");
                                     multipartEntity.addPart(nvp.get(index).getName(), new StringBody(nvp.get(index).getValue()));
                                }
                             }
                         }
                    }
                    post.setEntity(multipartEntity);
                    response = client.execute(post, localContext);
                    entity = response.getEntity();
                    if(entity != null)
                    {
                        result = EntityUtils.toString(entity);
                    }
                    else
                    {
                        Log.d("Response Failed","Response from server is failed");
                    }
                  
                } catch (IOException e) {
                    e.printStackTrace();
                }

        }catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return result;
      
    }

Friday 20 September 2013

Filtering with basea adapter

this is my main activity edittext 

edtsearch.addTextChangedListener(searchTextWatcher);

make funcetion

private TextWatcher searchTextWatcher = new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if(phonebookadp != null){
                String myst = s.toString();
              
                if(myst.equalsIgnoreCase(s.toString())){
                    phonebookadp.getFilter().filter(s.toString());
                }
            }
        }
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
        public void afterTextChanged(Editable s) {}
    };


This is my adapter 

   
    public class ImportPhonebook_Adapter extends BaseAdapter implements Filterable{
      
        private LayoutInflater l_Inflater;
        Filter myFilter;

        public ImportPhonebook_Adapter(Context context) {
            l_Inflater = LayoutInflater.from(context);
        }
        public int getCount() {
            // TODO Auto-generated method stub
                return contactname.size();
        }

        public Object getItem(int position) {
            return contactname.get(position);
        }

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

        public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder holder;
            if (convertView == null) {
                convertView = l_Inflater.inflate(R.layout.contactlist, null);
                holder = new ViewHolder();
                holder.fname = (TextView) convertView.findViewById(R.id.contactlist);
                holder.lname = (TextView) convertView.findViewById(R.id.contactlistlname);
                holder.textnum = (TextView)convertView.findViewById(R.id.textnumber);
                holder.imguser = (ImageView)convertView.findViewById(R.id.imageViewuser);
                holder.chkbx = (CheckBox)convertView.findViewById(R.id.checkBox1);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.chkbx.setVisibility(View.GONE);
          
            try{
                if(contactname != null){
                    ContactSetGet contasetget = new ContactSetGet();
                    contasetget = contactname.get(position);
                  
                    cont_id = contasetget.getmyId();
                    Log.i(tag, "my cont id...."+cont_id);
                  
              
                            strmob_no = contasetget.getMainnumber();
                            if(!TextUtils.isEmpty(strmob_no)){
                                holder.textnum.setText(strmob_no);
                            }else{
                                holder.textnum.setVisibility(View.INVISIBLE);
                            }
                            strfname = contasetget.getFname();
                            strgivenname = contasetget.getLname();
                      
                              
                                if(!TextUtils.isEmpty(strfname)){
                                    holder.fname.setText(contasetget.getFname());  
                                }else{
                                    holder.fname.setVisibility(View.GONE);
                                }
                                if(!TextUtils.isEmpty(strgivenname)){
                                    holder.lname.setText(contasetget.getLname());  
                                }else{
                                    holder.lname.setVisibility(View.GONE);
                                }
                              
                            String photoId = contasetget.getPhoto();
                          
                            Log.i("Phonebook_Adapter", "image ....."+photoId);
                            if(photoId != null){
                                if(photoId.equalsIgnoreCase("00")){
                                    holder.imguser.setImageResource(R.drawable.ic_launcher);
                                }else if(photoId.contains("mnt")){
                                    Bitmap bitmap = BitmapFactory.decodeFile(photoId);
                                    holder.imguser.setImageBitmap(bitmap);
                                  
                                }
                                else{
                                    photoUri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, Long.parseLong(photoId));
                                    holder.imguser.setImageURI(photoUri);
                                }
                            }else{
                                holder.imguser.setImageResource(R.drawable.ic_contact_picture_holo_light);
                            }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return convertView;
        }
      
        @Override
        public android.widget.Filter getFilter() {
            // TODO Auto-generated method stub
            return new android.widget.Filter() {
              
                @SuppressWarnings("unchecked")
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    // TODO Auto-generated method stub
                    contactname = (ArrayList<ContactSetGet>) results.values;
                    ImportPhonebook_Adapter.this.notifyDataSetChanged();  
                }
              
                @TargetApi(Build.VERSION_CODES.GINGERBREAD)
                @SuppressLint({ "DefaultLocale", "NewApi" })
                @Override
                protected FilterResults performFiltering(CharSequence prefix) {
                    // TODO Auto-generated method stub
                    FilterResults results = new FilterResults();
                    List<ContactSetGet> i = new ArrayList<ContactSetGet>();
                  
                    String myna = prefix.toString();
                  
                    if (prefix!= null && prefix.toString().length() > 0) {

                        for (int index = 0; index < contactname.size(); index++) {
                            ContactSetGet si = contactname.get(index);
                            Log.i("----------------si.getFirstName()---------","."+si.getFname());
                            Log.i("----------------prefix---------","."+prefix.toString());
                            //String number
                          
                            myna = si.getFname().toLowerCase();
                            if(myna.startsWith(prefix.toString())){
                                Log.i(tag, "insert name..."+si.getFname());
                              i.add(si);
                            }
                        }
                        results.values = i;
                        results.count = i.size();                 
                    }
                    else{
                        synchronized (contactname){
                            results.values = mycontnamesetget;
                            results.count = mycontnamesetget.size();
                        }
                    }
                    return results;
                }
            };
        }
}


contactname is my main listview

List<ContactSetGet> mycontnamesetget;
mycontnamesetget = new ArrayList<ContactSetGet>();

fill this list same where main list fiil up
mycontnamesetget = contactname;  

Monday 16 September 2013

Chat Screens

create class name ChatInvitationDialogActivity

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.jivesoftware.smack.packet.Message;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.easychat.constant.Global;
import com.easychat.data.UserInfoChat;
import com.easychat.parsedata.SendChatInvitation;
import com.easychat.rinterface.ResponseListener;
import com.easychat.task.HttpDeleteAsync;
import com.easychat.task.HttpPostAsync;
import com.easychat.utility.AroundLogger;
import com.easychat.utility.Utility;
import com.easychat.xmpp.XmppClient;
import com.google.gson.Gson;

public class ChatInvitationDialogActivity extends DialogActivity implements OnClickListener {

private static final String TAG = "ChatInvitationDialogActivity";

Context mContext;

//Widget
Button btnAccept, btnDecline;
TextView tvTitle, tvMessage;

// String sender;
String ownId;
// String status;
// String senderId;

UserInfoChat infoChat;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatinvitationdialog);

mContext = this;

// sender = getIntent().getStringExtra("sender");
// userId = getIntent().getStringExtra("userid");
// status = getIntent().getStringExtra("status");
// senderId = getIntent().getStringExtra("senderid");

bindComponents();
init();
addListeners();
}


private void bindComponents(){
btnAccept = (Button) findViewById(R.id.btnAccept);
btnDecline = (Button) findViewById(R.id.btnDecline);
tvTitle = (TextView)findViewById(R.id.tvTitle);
tvMessage = (TextView)findViewById(R.id.tvMessage);
}

private void init(){
infoChat = (UserInfoChat) getIntent().getSerializableExtra("userinfo");
ownId = Utility.getSharedKey("userid", this);

tvMessage.setText(String.format(getString(R.string.chatdialog_message), infoChat.sender));
}

private void addListeners(){
btnAccept.setOnClickListener(this);
btnDecline.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnAccept:
approveFriendRequest(ownId, infoChat.userid);
// approveFriendRequest(senderId, userId);
return;

case R.id.btnDecline:
delineFriendRequest(ownId, infoChat.userid);
// delineFriendRequest(senderId, userId);
return;
}
}


private void approveInvitationUsingXmpp() {
UserInfoChat userInfoChat = new UserInfoChat();
// userInfoChat.status = status;


/**
* Set current login user's id as a userid
*/
userInfoChat.userid = ownId;
// userInfoChat.senderId = senderId;

Message message = new Message(Global.getReceiver(infoChat.sender), Message.Type.chat);
message.setFrom(Utility.getSharedKey("username", mContext));
message.setBody(Global.TYPE_INVITATION_ACCEPT);
// message.setProperty("userid", userId);
// message.setProperty("status", status);
message.setProperty("userinfo", userInfoChat);
XmppClient.sendMessage(this, message);
}

private void declineInvitationUsingXmpp() {
UserInfoChat userInfoChat1 = new UserInfoChat();
// userInfoChat1.status = status;
userInfoChat1.userid = ownId;
// userInfoChat1.senderId = senderId;

Message message1 = new Message( Global.getReceiver(infoChat.sender), Message.Type.chat);
message1.setFrom(Utility.getSharedKey("username", mContext));
message1.setBody(Global.TYPE_INVITATION_DECLINE);
// message1.setProperty("userid", userId);
// message1.setProperty("status", status);
message1.setProperty("userinfo", userInfoChat1);

XmppClient.sendMessage(this, message1);
}

private void approveFriendRequest(String userId, String requestId) {
AroundLogger.info(TAG + " ApproveFriendRequest   called---");
String token = Utility.getSharedKey("token", this);
List<Header> lstHeader = new ArrayList<Header>();
lstHeader.add(new BasicHeader("X-Apn-Authorization", token));

HttpPostAsync post = new HttpPostAsync(this);
post.setHeader(lstHeader);
post.isProgressBarEnabled(true);

post.setResponseListener(new ResponseListener() {
@Override
public void responseListener(String response) {
AroundLogger.info(TAG + "responseListener - response: " + response);
if(!TextUtils.isEmpty(response)) {

Gson mGson = new Gson();
SendChatInvitation mChatInvitation = mGson.fromJson(response, SendChatInvitation.class);
if(mChatInvitation == null || !TextUtils.isEmpty(mChatInvitation.error)) {
Utility.showToast(mChatInvitation.error, mContext);

}else {
approveInvitationUsingXmpp();
Intent chatintent = new Intent(mContext, ChatListAct.class);
chatintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
chatintent.putExtra("userid", infoChat.userid);
chatintent.putExtra("username", infoChat.sender);
startActivity(chatintent);
}

finish();
}
}
});
String StrUrl = Global.HOST + "users/" + userId + "/requests/" + requestId;
post.execute(StrUrl, null);

}

private void delineFriendRequest(String userId, String requestId) {
AroundLogger.info(TAG + " delineFriendRequest   called---");
String token = Utility.getSharedKey("token", this);
List<Header> lstHeader = new ArrayList<Header>();
lstHeader.add(new BasicHeader("X-Apn-Authorization", token));

HttpDeleteAsync delete = new HttpDeleteAsync(mContext);
delete.setHeader(lstHeader);
delete.isProgressBarEnabled(true);

delete.setResponseListener(new ResponseListener() {
@Override
public void responseListener(String response) {
AroundLogger.info(TAG + "responseListener - response: " + response);
if(!TextUtils.isEmpty(response)) {
Gson mGson = new Gson();
SendChatInvitation mChatInvitation = mGson.fromJson(response, SendChatInvitation.class);

if(mChatInvitation == null || !TextUtils.isEmpty(mChatInvitation.error)) {
Utility.showToast(mChatInvitation.error, mContext);

}else {
declineInvitationUsingXmpp();
}

finish();
}
}
});
String StrUrl = Global.HOST + "users/" + userId + "/requests/" + requestId;
delete.execute(StrUrl);

}

@Override
public void onBackPressed() {

}


}

cretae class name UserInfoChat


import java.io.Serializable;

public class UserInfoChat implements Serializable{

/**
*/
private static final long serialVersionUID = 1L;

public String userid;
// public String status;
// public String senderId;
public String sender;
}

create class name DialogActivity

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;

import com.easychat.constant.Global;

public class DialogActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Global.ACTION_LOGOUT);
registerReceiver(mBroadcastReceiver, intentFilter);
}
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
Log.d("onReceive","Logout in progress");
finish();
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBroadcastReceiver);
}
}


create class name ChatListAct


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.easychat.constant.Global;
import com.easychat.data.ChatInfo;
import com.easychat.data.UserInfoChat;
import com.easychat.mlisteners.ChatReceiver;
import com.easychat.parsedata.History;
import com.easychat.parsedata.HistoryallData;
import com.easychat.parsedata.HistoryallListData;
import com.easychat.parsedata.Userdata;
import com.easychat.quickactionbar.ActionItem;
import com.easychat.quickactionbar.QuickAction;
import com.easychat.rinterface.ResponseListener;
import com.easychat.task.HttpGetAsync;
import com.easychat.task.HttpPostAsync;
import com.easychat.utility.AroundLogger;
import com.easychat.utility.Utility;
import com.easychat.xmpp.XmppClient;
import com.google.gson.Gson;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

public class ChatListAct extends Default implements OnClickListener, ChatReceiver {

private static final String TAG = "UserlistAct-";

//Widgets
EditText cedtchat;
Button cbtnsend;
ListView lvwUserlist;
TextView tvUsername;
ImageView ivStatus;
ImageButton imgbtnSmiley;
static HorizontalScrollView hScrollFooter;

ChatListAdapter mAdapter;
String username;
String ownId;
String userId;
String token;
String ownUsername;

public static String userProfileImage;
public static String ownProfileImage;

QuickAction quickAction;

HistoryallListData historyparselist;
List<HistoryallData> historylist;
ArrayList<ChatInfo> chatList;

Context mContext;

// XmppService mXmppService;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.chatlist);

mContext = this;

bindComponents();
init();
addListeners();

}

private void bindComponents() {
AroundLogger.info(TAG + " bindComponents-");

lvwUserlist = (ListView) findViewById(R.id.clistchat);
hScrollFooter = (HorizontalScrollView) findViewById(R.id.hscrollview);
cedtchat = (EditText)findViewById(R.id.cedtchat);
cbtnsend = (Button)findViewById(R.id.cbtnsend);
tvUsername = (TextView) findViewById(R.id.tvUsername);
ivStatus = (ImageView) findViewById(R.id.ivStatus);
imgbtnSmiley = (ImageButton)findViewById(R.id.imgbtnSmiley);
}

private void init() {
AroundLogger.info(TAG + " init-");
chatList = new ArrayList<ChatInfo>();
mAdapter = new ChatListAdapter();
hScrollFooter.setVisibility(View.GONE);
lvwUserlist.setFocusable(false);
lvwUserlist.setFocusableInTouchMode(false);
lvwUserlist.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
lvwUserlist.setStackFromBottom(true);
lvwUserlist.setAdapter(mAdapter);
ownUsername = Utility.getSharedKey("username", this);
username = getIntent().getStringExtra("username");
userId = getIntent().getStringExtra("userid");
ownId = Utility.getSharedKey("userid", this);

if(BuildConfig.DEBUG) {
AroundLogger.info(TAG + " init - userId=" + userId + " ownId=" + ownId);
}

GetUserInfo(userId, false);
GetUserInfo(ownId, true);
if(getIntent().getBooleanExtra("fromhistory", false)) {
AllchatHistory();
}

/*mAdapter = new ChatListAdapter(this, new ArrayList<ChatInfo>());
lvwUserlist.setAdapter(mAdapter);
lvwUserlist.setDivider(null);
lvwUserlist.setDividerHeight(0);*/

// userid = getIntent().getStringExtra("userid");
// status = getIntent().getStringExtra("status");
// sender_id = getIntent().getStringExtra("userid");
// Log.i(Global.TAG, "init - Status--->: "+status);
/*if(!TextUtils.isEmpty(status)) {

if (status.equalsIgnoreCase(getResources().getString(R.string.S_online))) {
ivStatus.setImageResource(R.drawable.green);

} else if (status.equalsIgnoreCase(getResources().getString(R.string.S_busy))) {
ivStatus.setImageResource(R.drawable.orange);

} else if (status.equalsIgnoreCase(getResources().getString(R.string.S_do_not_disturb))) {
ivStatus.setImageResource(R.drawable.grey);

} else if (status.equalsIgnoreCase(getResources().getString(R.string.S_Offline))) {
ivStatus.setImageResource(R.drawable.red);
}
}*/

String text = getIntent().getStringExtra("message");

if(!TextUtils.isEmpty(text)) {

ChatInfo mChatInfo = new ChatInfo();
mChatInfo.setComment(text);
mChatInfo.setReceiver(ownUsername);
mChatInfo.setSender(username);
mChatInfo.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
chatList.add(mChatInfo);
notifyAdapter();


// mAdapter.add(mChatInfo);

/*Message message = new Message(ownUsername, Message.Type.chat);
message.setFrom(username);
message.setBody(text);
mAdapter.add(message);*/

}

tvUsername.setText(username);

setUpSmiles();

cedtchat.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View v, boolean hasFocus) {
cedtchat.setText(Global.getSmiledText(ChatListAct.this, cedtchat.getText().toString()));
}
});

}

private void addListeners() {
AroundLogger.info(TAG + " addListeners-");
imgbtn_back.setOnClickListener(this);
cbtnsend.setOnClickListener(this);
imgbtnSmiley.setOnClickListener(this);
}

@Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
case R.id.imgbtn_back:
finish();
break;

case R.id.cbtnsend:
InputMethodManager imm = (InputMethodManager)getSystemService(
     Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(cedtchat.getWindowToken(), 0);
String comment = cedtchat.getText().toString();
if(comment.trim().length() == 0) {
return;
}

cedtchat.setText("");

UserInfoChat mInfoChat = new UserInfoChat();
// mInfoChat.senderId = sender_id;
mInfoChat.userid = ownId;

Message message = new Message( Global.getReceiver(username), Message.Type.chat);
message.setFrom(Utility.getSharedKey("username", v.getContext()));
// message.setProperty("userid", userId);
message.setProperty("userinfo", mInfoChat);
message.setBody(comment);

XmppClient.sendMessage(this, message);
mAdapter.add(message);
notifyAdapter();

PostChat(comment);
break;
case R.id.imgbtnSmiley:
quickAction.show(v);
break;
default:
break;
}
}


@Override
public void receive(Message message) {
if(mAdapter != null) {
mAdapter.add(message);
notifyAdapter();

}
}


private void notifyAdapter() {
runOnUiThread(new Runnable() {

@Override
public void run() {
mAdapter.notifyDataSetChanged();


}
});
}


@Override
protected void onStart() {
super.onStart();
XmppClient.setCurrentChatListener(username, this);
// XmppClient.addChatReceiver(this);
}

@Override
protected void onStop() {
super.onStop();
XmppClient.removeCurrentChatListener();
// XmppClient.removeChatReceiver(this);
}


public void PostChat(String content) {
AroundLogger.info(TAG + "Post Chat is called---");

String token = Utility.getSharedKey("token", this);

List<Header> lstHeader = new ArrayList<Header>();
lstHeader.add(new BasicHeader("X-Apn-Authorization", token));

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("receiver_id", userId));
nameValuePairs.add(new BasicNameValuePair("content", content));

HttpPostAsync post = new HttpPostAsync(this);
post.isProgressBarEnabled(false);
post.setHeader(lstHeader);

post.setResponseListener(new ResponseListener() {
@Override
public void responseListener(String response) {
AroundLogger.info(TAG + "responseListener - response: " + response);

}
});

String StrUrl = Global.HOST + "chatHistory";
post.execute(StrUrl, nameValuePairs);
}

private void setUpSmiles() {

quickAction = new QuickAction(this, QuickAction.VERTICAL);

addActionItem(R.drawable.wink_,  ";)");
addActionItem(R.drawable.smile,  ":-)");
addActionItem(R.drawable.grin_,  ":D");
addActionItem(R.drawable.grumpy,  ">:c");
addActionItem(R.drawable.sunglasses,  "8-)");
addActionItem(R.drawable.gasp,  ":-o");
addActionItem(R.drawable.upset,  ">.<");
addActionItem(R.drawable.cry,  ":'c");
addActionItem(R.drawable.sad,  ":(");
addActionItem(R.drawable.the_softy,  ":'c");
addActionItem(R.drawable.the_sketchbag,  "x-c");



//Set listener for action item clicked
quickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
@Override
public void onItemClick(QuickAction source, int pos, int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);

cedtchat.setText(Global.getSmiledText(ChatListAct.this, cedtchat.getText() + actionItem.getSmileyName()));
cedtchat.setSelection(cedtchat.getText().length());
}
});
}

private void addActionItem(int drawable, String text) {
ActionItem actionItem = new ActionItem(drawable, null, getResources().getDrawable(drawable), text);
quickAction.addActionItem(actionItem);
}

public void AllchatHistory()
{

AroundLogger.info(TAG + "AllChatHistory is called-----");
token = Utility.getSharedKey("token",ChatListAct.this);

List<Header> lstHeader = new ArrayList<Header>();
lstHeader.add(new BasicHeader("X-Apn-Authorization",token));

HttpGetAsync get = new HttpGetAsync(mContext);
get.setHeader(lstHeader);
get.setResponseListener(new ResponseListener() { 
@Override
public void responseListener(String response) {
AroundLogger.info(TAG + "responseListener - response: " + response);

if(!response.equalsIgnoreCase("")) {
Gson gson = new Gson();

historyparselist = gson.fromJson(response, HistoryallListData.class);
Map<Integer, History> mHashMap = historyparselist.historyList;
for (Integer key : mHashMap.keySet()) {
History mHistories = mHashMap.get(key);
ChatInfo  chat= new ChatInfo();

chat.setSender(mHistories.sender);
chat.setReceiver(mHistories.receiver);
chat.setComment(mHistories.content);
chat.setTime(mHistories.time);
chatList.add(chat);
notifyAdapter();
}
/* historylist =  historyparselist.historylist;

HistoryallData  historydata;

for(int i=0;i<historylist.size();i++)
{
ChatInfo  chat= new ChatInfo();
historydata=historylist.get(i);
chat.setSender(historydata.senderusername);
chat.setReceiver(ownUsername);
chat.setComment(historydata.content);
chat.setTime(historydata.createdate);
chatList.add(chat);
notifyAdapter();
}
*/
Collections.sort(chatList, mComparator);
notifyAdapter();
}

}
});
String StrUrl = Global.HOST+"chatHistory/" + userId;
get.execute(StrUrl);
}

Comparator<ChatInfo> mComparator = new Comparator<ChatInfo>() {
@Override
public int compare(ChatInfo lhs, ChatInfo rhs) {
return lhs.getTime().compareTo(rhs.getTime());
}
};
public void GetUserInfo(String uId, final boolean isOwnProfile) {

AroundLogger.info(TAG + "GetUser info is called---");

token = Utility.getSharedKey("token", this);
List<Header> lstHeader = new ArrayList<Header>();
lstHeader.add(new BasicHeader("X-Apn-Authorization", token));
AroundLogger.info(TAG + "User Info  called---");

HttpGetAsync get = new HttpGetAsync(this);

get.setHeader(lstHeader);
get.setResponseListener(new ResponseListener() {
@Override
public void responseListener(String response) {
AroundLogger.info(TAG + "responseListener - response: " + response);

if(!TextUtils.isEmpty(response)) {
try {
Gson gson = new Gson();
Userdata userprofiledata = gson.fromJson(response,Userdata.class);

if(!isOwnProfile) {
String status = userprofiledata.status;

AroundLogger.info(TAG + "responseListener - Status--->: "+status);

if (status.equalsIgnoreCase(getResources().getString(R.string.S_online))) {

ivStatus.setImageResource(R.drawable.green);

} else if (status.equalsIgnoreCase(getResources().getString(R.string.S_busy))) {

ivStatus.setImageResource(R.drawable.orange);
} else if (status.equalsIgnoreCase(getResources().getString(R.string.dnd))) {
ivStatus.setImageResource(R.drawable.grey);
} else if (status.equalsIgnoreCase(getResources().getString(R.string.S_Offline))) {
ivStatus.setImageResource(R.drawable.red);
}

userProfileImage = userprofiledata.thumbnail_url;
tvUsername.setText(Global.getDisplayName(userprofiledata.nickname, userprofiledata.firstname, userprofiledata.lname, userprofiledata.username));
}else {
ownProfileImage = userprofiledata.thumbnail_url;
}

} catch (Exception e) {
// TODO: handle exception
AroundLogger.info(TAG + "catch clause....");
}

}
}
});
AroundLogger.info(TAG + "GetUserInfo - ");
String StrUrl = Global.HOST + "users/" + uId;
get.execute(StrUrl);
}

public class ChatListAdapter extends BaseAdapter{

String receiver;

SimpleDateFormat mDateFormat;
SimpleDateFormat mDateFormat2;

public ChatListAdapter() {
receiver = Utility.getSharedKey("username", ChatListAct.this);
chatList = new ArrayList<ChatInfo>();
mDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
mDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}

public void add(ChatInfo mChatInfo) {
chatList.add(mChatInfo);
// notifyDataSetChanged();
}

public void add(Message message) {
ChatInfo mChatInfo = new ChatInfo();
if(message.getFrom().contains("@")) {
mChatInfo.setSender(StringUtils.parseName(message.getFrom()));
}else {
mChatInfo.setSender(message.getFrom());
}

mChatInfo.setReceiver(receiver);
mChatInfo.setComment(message.getBody());
mChatInfo.setTime(mDateFormat2.format(new Date()));
chatList.add(mChatInfo);
// notifyDataSetChanged();
}

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

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

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

@Override
public int getViewTypeCount() {
return 2;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

ChatInfo mChatInfo = chatList.get(position);

if(mChatInfo.getSender() == null || mChatInfo.getSender().equalsIgnoreCase(receiver)) {
convertView = getLayoutInflater().inflate(R.layout.chatlist_row_own, null);

}else {
convertView = getLayoutInflater().inflate(R.layout.chatlist_row_user, null);
}

TextView tvUsername = (TextView) convertView.findViewById(R.id.tvUsername);
ImageView userimage = (ImageView) convertView.findViewById(R.id.ivwuser);

if(mChatInfo.getSender() == null || mChatInfo.getSender().equalsIgnoreCase(receiver)) {
UrlImageViewHelper.setUrlDrawable(userimage, ChatListAct.ownProfileImage, R.drawable.no_image);
tvUsername.setText("Me");

}else {
UrlImageViewHelper.setUrlDrawable(userimage, ChatListAct.userProfileImage, R.drawable.no_image);
tvUsername.setText(mChatInfo.getSender());
}

TextView mView = (TextView)convertView.findViewById(R.id.tvComment);
mView.setText(Global.getSmiledText(mContext, mChatInfo.getComment()));

TextView tvChatTime = (TextView) convertView.findViewById(R.id.tvChatTime);
try {
tvChatTime.setText((mDateFormat.format(mDateFormat2.parse(mChatInfo.getTime()))));
} catch (ParseException e) {
e.printStackTrace();

}


return convertView;
}
}

}

create class name ChatListAdapter

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.easychat.app.R;
import com.easychat.constant.Global;
import com.easychat.data.ChatInfo;
import com.easychat.utility.Utility;

public class ChatListAdapter extends BaseAdapter{

ArrayList <ChatInfo> list;
Context mContext;
String receiver;

SimpleDateFormat mDateFormat;

public ChatListAdapter(Context context, ArrayList<ChatInfo> mList) {
this.mContext = context;
receiver = Utility.getSharedKey("username", context);
list = new ArrayList<ChatInfo>();
list = mList;
mDateFormat = new SimpleDateFormat("HH:mm aa");
}

public void add(ChatInfo mChatInfo) {
list.add(mChatInfo);
// notifyDataSetChanged();
}

public void add(Message message) {
ChatInfo mChatInfo = new ChatInfo();
if(message.getFrom().contains("@")) {
mChatInfo.setSender(StringUtils.parseName(message.getFrom()));
}else {
mChatInfo.setSender(message.getFrom());
}
mChatInfo.setReceiver(receiver);
mChatInfo.setComment(message.getBody());
mChatInfo.setTime(mDateFormat.format(new Date()));
list.add(mChatInfo);
// notifyDataSetChanged();
}

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

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {

ChatInfo mChatInfo = list.get(position);

if(mChatInfo.getSender() == null || mChatInfo.getSender().equals(receiver)) {
convertView = ((Activity)mContext).getLayoutInflater().inflate(R.layout.chatlist_row_own, null);

}else {
convertView = ((Activity)mContext).getLayoutInflater().inflate(R.layout.chatlist_row_user, null);
}

if(mChatInfo.getSender() == null || mChatInfo.getSender().equals(receiver)) {
}else {
}
TextView mView = (TextView)convertView.findViewById(R.id.tvComment);
mView.setText(Global.getSmiledText(mContext, mChatInfo.getComment()));

TextView tvUsername = (TextView) convertView.findViewById(R.id.tvUsername);
tvUsername.setText(mChatInfo.getSender());

TextView tvChatTime = (TextView) convertView.findViewById(R.id.tvChatTime);
tvChatTime.setText((mChatInfo.getTime()));


return convertView;
}
}
create class name QuickAction

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.easychat.app.R;

/**
 * QuickAction dialog, shows action list as icon and text like the one in Gallery3D app. Currently supports vertical 
 * and horizontal layout.
 * 
 * @author Lorensius W. L. T <lorenz@londatiga.net>
 * 
 * Contributors:
 * - Kevin Peck <kevinwpeck@gmail.com>
 */
public class QuickAction extends PopupWindows implements OnDismissListener {
private View mRootView;
private ImageView mArrowUp;
private ImageView mArrowDown;
private LayoutInflater mInflater;
private ViewGroup mTrack;
private ScrollView mScroller;
private OnActionItemClickListener mItemClickListener;
private OnDismissListener mDismissListener;
private List<ActionItem> actionItems = new ArrayList<ActionItem>();
private boolean mDidAction;
private int mChildPos;
    private int mInsertPos;
    private int mAnimStyle;
    private int mOrientation;
    private int rootWidth=0;
    
    public static final int HORIZONTAL = 0;
    public static final int VERTICAL = 1;
    
    public static final int ANIM_GROW_FROM_LEFT = 1;
public static final int ANIM_GROW_FROM_RIGHT = 2;
public static final int ANIM_GROW_FROM_CENTER = 3;
public static final int ANIM_REFLECT = 4;
public static final int ANIM_AUTO = 5;
    /**
     * Constructor for default vertical layout
     * 
     * @param context  Context
     */
    public QuickAction(Context context) {
        this(context, VERTICAL);
    }

    /**
     * Constructor allowing orientation override
     * 
     * @param context    Context
     * @param orientation Layout orientation, can be vartical or horizontal
     */
    public QuickAction(Context context, int orientation) {
        super(context);
        
        mOrientation = orientation;
        
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (mOrientation == HORIZONTAL) {
            setRootViewId(R.layout.popup_horizontal);
        } else {
            setRootViewId(R.layout.popup_vertical);
        }

        mAnimStyle = ANIM_AUTO;
        mChildPos = 0;
    }

    /**
     * Get action item at an index
     * 
     * @param index  Index of item (position from callback)
     * 
     * @return  Action Item at the position
     */
    public ActionItem getActionItem(int index) {
        return actionItems.get(index);
    }
    
/**
* Set root view.
* @param id Layout resource id
*/
public void setRootViewId(int id) {
mRootView = (ViewGroup) mInflater.inflate(id, null);
mTrack = (ViewGroup) mRootView.findViewById(R.id.tracks);

mArrowDown = (ImageView) mRootView.findViewById(R.id.arrow_down);
mArrowUp = (ImageView) mRootView.findViewById(R.id.arrow_up);

mScroller = (ScrollView) mRootView.findViewById(R.id.scroller);
//This was previously defined on show() method, moved here to prevent force close that occured
//when tapping fastly on a view to show quickaction dialog.
//Thanx to zammbi (github.com/zammbi)
mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
setContentView(mRootView);
}
/**
* Set animation style
* @param mAnimStyle animation style, default is set to ANIM_AUTO
*/
public void setAnimStyle(int mAnimStyle) {
this.mAnimStyle = mAnimStyle;
}
/**
* Set listener for action item clicked.
* @param listener Listener
*/
public void setOnActionItemClickListener(OnActionItemClickListener listener) {
mItemClickListener = listener;
}
/**
* Add action item
* @param action  {@link ActionItem}
*/
public void addActionItem(ActionItem action) {
actionItems.add(action);
String title = action.getTitle();
Drawable icon = action.getIcon();
View container;
if (mOrientation == HORIZONTAL) {
            container = mInflater.inflate(R.layout.action_item_horizontal, null);
        } else {
            container = mInflater.inflate(R.layout.action_item_vertical, null);
        }
ImageView img = (ImageView) container.findViewById(R.id.iv_icon);
TextView text = (TextView) container.findViewById(R.id.tv_title);
if (icon != null) {
img.setImageDrawable(icon);
} else {
img.setVisibility(View.GONE);
}
if (title != null) {
text.setText(title);
} else {
text.setVisibility(View.GONE);
}
final int pos =  mChildPos;
final int actionId = action.getActionId();
container.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mItemClickListener != null) {
                    mItemClickListener.onItemClick(QuickAction.this, pos, actionId);
                }
                if (!getActionItem(pos).isSticky()) {  
                mDidAction = true;
               
                    dismiss();
                }
}
});
container.setFocusable(true);
container.setClickable(true);
 
if (mOrientation == HORIZONTAL && mChildPos != 0) {
            View separator = mInflater.inflate(R.layout.horiz_separator, null);
            
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            
            separator.setLayoutParams(params);
            separator.setPadding(5, 0, 5, 0);
            
            mTrack.addView(separator, mInsertPos);
            
            mInsertPos++;
        }
mTrack.addView(container, mInsertPos);
mChildPos++;
mInsertPos++;
}
/**
* Show quickaction popup. Popup is automatically positioned, on top or bottom of anchor view.
*/
public void show (View anchor) {
preShow();
int xPos, yPos, arrowPos;
mDidAction = false;
int[] location = new int[2];
anchor.getLocationOnScreen(location);

Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1] 
                + anchor.getHeight());

//mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mRootView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int rootHeight = mRootView.getMeasuredHeight();
if (rootWidth == 0) {
rootWidth = mRootView.getMeasuredWidth();
}
int screenWidth = mWindowManager.getDefaultDisplay().getWidth();
int screenHeight = mWindowManager.getDefaultDisplay().getHeight();
//automatically get X coord of popup (top left)
if ((anchorRect.left + rootWidth) > screenWidth) {
xPos = anchorRect.left - (rootWidth-anchor.getWidth());
xPos = (xPos < 0) ? 0 : xPos;
arrowPos = anchorRect.centerX()-xPos;
} else {
if (anchor.getWidth() > rootWidth) {
xPos = anchorRect.centerX() - (rootWidth/2);
} else {
xPos = anchorRect.left;
}
arrowPos = anchorRect.centerX()-xPos;
}
int dyTop = anchorRect.top;
int dyBottom = screenHeight - anchorRect.bottom;

boolean onTop = (dyTop > dyBottom) ? true : false;

if (onTop) {
if (rootHeight > dyTop) {
yPos = 15;
LayoutParams l = mScroller.getLayoutParams();
l.height = dyTop - anchor.getHeight();
} else {
yPos = anchorRect.top - rootHeight;
}
} else {
yPos = anchorRect.bottom;
if (rootHeight > dyBottom) { 
LayoutParams l = mScroller.getLayoutParams();
l.height = dyBottom;
}
}
showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up), arrowPos);
setAnimationStyle(screenWidth, anchorRect.centerX(), onTop);
mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos);
}
/**
* Set animation style
* @param screenWidth screen width
* @param requestedX distance from left edge
* @param onTop flag to indicate where the popup should be displayed. Set TRUE if displayed on top of anchor view
*  and vice versa
*/
private void setAnimationStyle(int screenWidth, int requestedX, boolean onTop) {
int arrowPos = requestedX - mArrowUp.getMeasuredWidth()/2;

switch (mAnimStyle) {
case ANIM_GROW_FROM_LEFT:
mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left);
break;
case ANIM_GROW_FROM_RIGHT:
mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right);
break;
case ANIM_GROW_FROM_CENTER:
mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center);
break;
case ANIM_REFLECT:
mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Reflect : R.style.Animations_PopDownMenu_Reflect);
break;
case ANIM_AUTO:
if (arrowPos <= screenWidth/4) {
mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left);
} else if (arrowPos > screenWidth/4 && arrowPos < 3 * (screenWidth/4)) {
mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center);
} else {
mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right);
}
break;
}
}
/**
* Show arrow
* @param whichArrow arrow type resource id
* @param requestedX distance from left screen
*/
private void showArrow(int whichArrow, int requestedX) {
        final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp : mArrowDown;
        final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown : mArrowUp;

        final int arrowWidth = mArrowUp.getMeasuredWidth();

        showArrow.setVisibility(View.VISIBLE);
        
        ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams)showArrow.getLayoutParams();
       
        param.leftMargin = requestedX - arrowWidth / 2;
        
        hideArrow.setVisibility(View.INVISIBLE);
    }
/**
* Set listener for window dismissed. This listener will only be fired if the quicakction dialog is dismissed
* by clicking outside the dialog or clicking on sticky item.
*/
public void setOnDismissListener(QuickAction.OnDismissListener listener) {
setOnDismissListener(this);
mDismissListener = listener;
}
@Override
public void onDismiss() {
if (!mDidAction && mDismissListener != null) {
mDismissListener.onDismiss();
}
}
/**
* Listener for item click
*
*/
public interface OnActionItemClickListener {
public abstract void onItemClick(QuickAction source, int pos, int actionId);
}
/**
* Listener for window dismiss
*/
public interface OnDismissListener {
public abstract void onDismiss();
}
}

create class name PopupWindows

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.PopupWindow;

/**
 * Custom popup window.
 * 
 * @author Lorensius W. L. T <lorenz@londatiga.net>
 *
 */
public class PopupWindows {
protected Context mContext;
protected PopupWindow mWindow;
protected View mRootView;
protected Drawable mBackground = null;
protected WindowManager mWindowManager;
/**
* Constructor.
* @param context Context
*/
public PopupWindows(Context context) {
mContext = context;
mWindow = new PopupWindow(context);

mWindow.setTouchInterceptor(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
mWindow.dismiss();
return true;
}
return false;
}
});

mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
}
/**
* On dismiss
*/
protected void onDismiss() {
}
/**
* On show
*/
protected void onShow() {
}

/**
* On pre show
*/
protected void preShow() {
if (mRootView == null) 
throw new IllegalStateException("setContentView was not called with a view to display.");
onShow();

if (mBackground == null) 
mWindow.setBackgroundDrawable(new BitmapDrawable());
else 
mWindow.setBackgroundDrawable(mBackground);

mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
mWindow.setTouchable(true);
mWindow.setFocusable(true);
mWindow.setOutsideTouchable(true);

mWindow.setContentView(mRootView);
}

/**
* Set background drawable.
* @param background Background drawable
*/
public void setBackgroundDrawable(Drawable background) {
mBackground = background;
}

/**
* Set content view.
* @param root Root view
*/
public void setContentView(View root) {
mRootView = root;
mWindow.setContentView(root);
}

/**
* Set content view.
* @param layoutResID Resource id
*/
public void setContentView(int layoutResID) {
LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
setContentView(inflator.inflate(layoutResID, null));
}

/**
* Set listener on window dismissed.
* @param listener
*/
public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
mWindow.setOnDismissListener(listener);  
}

/**
* Dismiss the popup window.
*/
public void dismiss() {
mWindow.dismiss();
}
}
create class name HistoryallListData

import java.io.Serializable;
import java.util.Map;

import com.google.gson.annotations.SerializedName;

public class HistoryallListData implements Serializable{

/**
*/
private static final long serialVersionUID = 5319370330373259907L;

@SerializedName("chat_user_data")
public HistoryallData historyData;
@SerializedName("history")
public Map<Integer, History> historyList;
}
cretae class name ChatInfo

public class ChatInfo {

String sender;
String receiver;
String comment;
String image;
String time;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}


create class name HttpPostAsync


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
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 android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.easychat.app.R;
import com.easychat.rinterface.ResponseListener;
import com.easychat.utility.AroundLogger;
import com.easychat.utility.Utility;

public class HttpPostAsync extends AsyncTask<Object, Object, Object> {

private static final String TAG = "HttpGetAsync - ";
Context mContext;
ProgressDialog progress;
ResponseListener mListener;
boolean mIsProgress = true;
int responseCode;
String message;
List<Header> mHeader = null;
String mFilePath = "";

public HttpPostAsync(Context context) {
AroundLogger.info(TAG + "HttpGetAsync - ");
mContext = context;
}

public void setResponseListener(ResponseListener listener) {
AroundLogger.info(TAG + "setResponseListener - ");
mListener = listener;
}

public void isProgressBarEnabled(boolean isProgress) {
mIsProgress = isProgress;
}

public void setHeader(List<Header> header) {
mHeader = header;
}
public void setFilePath(String filePath){
mFilePath = filePath;
}

@Override
protected void onPreExecute() {
AroundLogger.info(TAG + "onPreExecute - ");
if (mIsProgress) {
progress = new ProgressDialog(mContext);
progress.show();
progress.setContentView(R.layout.custom_progress);
}
}

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

String response = "";
String strUrl = (String) params[0];
if(Utility.isNetworkAvailable(mContext)){
}
AroundLogger.info(TAG + "doInBackground - strUrl:" + strUrl);
@SuppressWarnings("unchecked")
List<NameValuePair> nameValuePair = (ArrayList<NameValuePair>) params[1];
AroundLogger.info(TAG + "doInBackground - nameValuePair:" + nameValuePair);
String filepath = mFilePath;

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(strUrl);
if (mHeader != null) {
for (Header header : mHeader) {
httpPost.addHeader(header);
}
}
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (nameValuePair != null) {
ContentBody cb;
for(NameValuePair value: nameValuePair){
cb =  new StringBody(value.getValue(),"", null);
entity.addPart(value.getName(), cb);
}
}
if(filepath != null && filepath.length() > 0){
File f = new File(filepath);
entity.addPart("uploadedfile", new FileBody(f));
}
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
response = EntityUtils.toString(httpResponse.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
//Display();
} catch (IOException e) {
e.printStackTrace();
//Display();
}

if (mIsProgress)
progress.dismiss();
return response;
}

@Override
protected void onPostExecute(Object response) {
AroundLogger.info(TAG + "onPostExecute - response: " + response);
mListener.responseListener((String) response);
}

ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
public String handleResponse(final HttpResponse response)
throws HttpResponseException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}

HttpEntity entity = response.getEntity();

AroundLogger.info(TAG + "doInBackground - entity: " + entity);
byte[] b = EntityUtils.toByteArray(entity);
return new String(b, "windows-1252");
// return entity == null ? null : EntityUtils.toString(entity);
}
};

public void Display()
{
((Activity)mContext).runOnUiThread(new Runnable() {
@Override
public void run() {
Utility.showToast("Internet Not Available..!", mContext);
}
});
}
}
create class name HttpDeleteAsync

import java.io.IOException;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import com.easychat.app.R;
import com.easychat.constant.Global;
import com.easychat.rinterface.ResponseListener;
import com.easychat.utility.AroundLogger;
import com.easychat.utility.Utility;

public class HttpDeleteAsync extends AsyncTask<Object, Object, Object> {
private static final String TAG = "HttpDeleteAsync - ";

Context mContext;
ProgressDialog progress;
ResponseListener mListener;
boolean mIsProgress = true;
int responseCode;
String message;
List<Header> mHeader = null;

public HttpDeleteAsync(Context context) {
AroundLogger.info(TAG + "HttpGetAsync - ");
mContext = context;
}

public void setResponseListener(ResponseListener listener) {
AroundLogger.info(TAG + "setResponseListener - ");
mListener = listener;
}

public void isProgressBarEnabled(boolean isProgress) {
mIsProgress = isProgress;
}

public void setHeader(List<Header> header) {
mHeader = header;
}

@Override
protected void onPreExecute() {
AroundLogger.info(TAG + "onPreExecute - ");
if (mIsProgress) {
progress = new ProgressDialog(mContext);
progress.show();
progress.setContentView(R.layout.custom_progress);

}
}

@Override
protected Object doInBackground(Object... params) {
AroundLogger.info(TAG + "doInBackground - ");
String response = "";
String strUrl = (String) params[0];
if(Utility.isNetworkAvailable(mContext)){
AroundLogger.info(TAG + "doInBackground - url: " + strUrl);

HttpClient client = new DefaultHttpClient();
HttpDelete delete = new HttpDelete(strUrl);
if(mHeader != null){
for(Header header: mHeader){
delete.addHeader(header);
}
}
delete.addHeader("Content-Type", "application/json");
HttpResponse hresponse = null;
try {
hresponse = client.execute(delete);
} catch (ClientProtocolException e) {
AroundLogger.info(TAG + "doInBackground - ClientProtocolException - Error:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
AroundLogger.info(TAG + "doInBackground - IOException - Error:" + e.getMessage());
e.printStackTrace();
}
HttpEntity resentity = hresponse.getEntity();
try {
response = EntityUtils.toString(resentity);
} catch (ParseException e) {
AroundLogger.info(TAG + "doInBackground - ParseException - Error:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
AroundLogger.info(TAG + "doInBackground - IOException - Error:" + e.getMessage());
e.printStackTrace();
}
}else{
// response = "{\"error\":\"No Internet Connection\"}";
Intent intent = new Intent();
intent.setAction(Global.NO_CONNECTION);
mContext.sendBroadcast(intent);
}

if (mIsProgress)
progress.dismiss();
return response;
}

@Override
protected void onPostExecute(Object response) {
AroundLogger.info(TAG + "onPostExecute - response: " + response);
mListener.responseListener((String) response);
}

ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
public String handleResponse(final HttpResponse response)
throws HttpResponseException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}

HttpEntity entity = response.getEntity();

AroundLogger.info(TAG + "handleResponse - entity: " + entity);
byte[] b = EntityUtils.toByteArray(entity);
return new String(b, "windows-1252");
// return entity == null ? null : EntityUtils.toString(entity);
}
};

}
create class name ActionItem

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;

/**
 * Action item, displayed as menu with icon and text.
 *
 * @author Lorensius. W. L. T <lorenz@londatiga.net>
 *
 * Contributors:
 * - Kevin Peck <kevinwpeck@gmail.com>
 *
 */
public class ActionItem {
private Drawable icon;
private Bitmap thumb;
private String title;
private int actionId = -1;
    private boolean selected;
    private boolean sticky;
    private String smileyName;

    /**
     * Constructor
     *
     * @param actionId  Action id for case statements
     * @param title     Title
     * @param smiley      Icon to use
     */
    public ActionItem(int actionId, String title, Drawable smiley, String smileyName) {
        this.title = title;
        this.icon = smiley;
        this.actionId = actionId;
        this.smileyName = smileyName;
    }
   
    /**
     * Constructor
     */
    public ActionItem() {
        this(-1, null, null, null);
    }
   
   /* *//**
     * Constructor
     *
     * @param actionId  Action id of the item
     * @param title     Text to show for the item
     *//*
    public ActionItem(int actionId, String title) {
        this(actionId, title, null);
    }
   
    *//**
     * Constructor
     *
     * @param icon {@link Drawable} action icon
     *//*
    public ActionItem(Drawable icon) {
        this(-1, null, icon);
    }
   
    /**
     * Constructor
     *
     * @param actionId  Action ID of item
     * @param icon      {@link Drawable} action icon
   
    public ActionItem(int actionId, Drawable icon) {
        this(actionId, null, icon);
    }*/

   
   
/**
* Set action title
*
* @param title action title
*/
public void setTitle(String title) {
this.title = title;
}

public String getSmileyName() {
return smileyName;
}

public void setSmileyName(String smileyName) {
this.smileyName = smileyName;
}

/**
* Get action title
*
* @return action title
*/
public String getTitle() {
return this.title;
}

/**
* Set action icon
*
* @param icon {@link Drawable} action icon
*/
public void setIcon(Drawable icon) {
this.icon = icon;
}

/**
* Get action icon
* @return  {@link Drawable} action icon
*/
public Drawable getIcon() {
return this.icon;
}

/**
     * Set action id
     *
     * @param actionId  Action id for this action
     */
    public void setActionId(int actionId) {
        this.actionId = actionId;
    }
   
    /**
     * @return  Our action id
     */
    public int getActionId() {
        return actionId;
    }
   
    /**
     * Set sticky status of button
     *
     * @param sticky  true for sticky, pop up sends event but does not disappear
     */
    public void setSticky(boolean sticky) {
        this.sticky = sticky;
    }
   
    /**
     * @return  true if button is sticky, menu stays visible after press
     */
    public boolean isSticky() {
        return sticky;
    }
   
/**
* Set selected flag;
*
* @param selected Flag to indicate the item is selected
*/
public void setSelected(boolean selected) {
this.selected = selected;
}

/**
* Check if item is selected
*
* @return true or false
*/
public boolean isSelected() {
return this.selected;
}

/**
* Set thumb
*
* @param thumb Thumb image
*/
public void setThumb(Bitmap thumb) {
this.thumb = thumb;
}

/**
* Get thumb image
*
* @return Thumb image
*/
public Bitmap getThumb() {
return this.thumb;
}
}
create interface name ResponseListener

public interface ResponseListener {
public void responseListener(String response);

}

create class name XMPPConn

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import com.easychat.constant.Global;
import com.easychat.mlisteners.OnLoginListener;
import com.easychat.utility.AroundLogger;
import com.easychat.utility.Utility;
import com.easychat.xmpp.XmppClient;
import com.easychat.xmpp.XmppConnectionListener;

public class XMPPConn extends AsyncTask<Object, Object, XMPPConnection>{

private static final String TAG = "XMPPConn - ";
Context mContext;

OnLoginListener mLoginListener;
XMPPConnection connection = null;
public XMPPConn(Context mContext, OnLoginListener loginListener) {
this.mContext = mContext;
this.mLoginListener = loginListener;
}
@Override
protected XMPPConnection doInBackground(Object... params) {
String host = Global.XMPPHOST;
String port = Global.XMPP_PORT;

if(Utility.isNetworkAvailable(mContext)){
AroundLogger.info(TAG + " host " + host + " port:" + port);
// Create a connection
ConnectionConfiguration connConfig = new ConnectionConfiguration(host, Integer.parseInt(port));
connection = new XMPPConnection(connConfig);
try {
connection.connect();
AroundLogger.info(TAG +  " Connected to " + connection.getHost());
} catch (XMPPException ex) {
AroundLogger.info(TAG + " Failed to connect to " + connection.getHost());
AroundLogger.info(TAG + ex.toString());
connection = null;
return connection;
}
if(connection != null && connection.isConnected()) {

String username = Utility.getSharedKey("username", mContext).toLowerCase();
String password = Utility.getSharedKey("password", mContext);
AroundLogger.info(TAG +  "doInBackground - User Name: " + username + " password:" + password);
try {
connection.login(username, password);
AroundLogger.info(TAG + " Logged in as " + connection.getUser());

Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
connection.addConnectionListener(new XmppConnectionListener(mContext));
XmppClient mXmppClient = XmppClient.getInstance(mContext);
XmppClient.setConnection(connection, mXmppClient);
AroundLogger.info(TAG + " Registered for chat as " + connection.getUser());
} catch (Exception ex) {
AroundLogger.info(TAG + " Failed to log in as " + username);
AroundLogger.info(TAG +  ex.toString());
connection = null;
ex.printStackTrace();
}
}
}else{
// response = "{\"error\":\"No Internet Connection\"}";
Intent intent = new Intent();
intent.setAction(Global.NO_CONNECTION);
mContext.sendBroadcast(intent);
}
return connection;
}

@Override
protected void onPostExecute(XMPPConnection con) {
super.onPostExecute(con);
if(con != null && con.isConnected()) {
if(mLoginListener != null) {
mLoginListener.onLogin(true);
}
}else {
if(mLoginListener != null) {
mLoginListener.onLogin(false);
}
}

}
}

create interface name OnLoginListener

public interface OnLoginListener {

public void onLogin(boolean success);
}

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...