Saturday 1 June 2019

Add Contact

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.getcontact.data.Address;
import com.getcontact.data.Contact;
import com.getcontact.data.Email;
import com.getcontact.data.Events;
import com.getcontact.data.Group;
import com.getcontact.data.Im;
import com.getcontact.data.Note;
import com.getcontact.data.Organization;
import com.getcontact.data.Phone;
import com.getcontacts.adapter.GroupListAdapter;
import com.getcontacts.sqlite.SQDataChecked;
import com.getcontacts.sqlite.SQDataSourceContcts;

public class AddCont extends Activity{

    private static final String tag = AddCont.class.getSimpleName();
    static String[] sprphonetype = {"Custom","Home","Mobile", "Work", "Work Fax", "Home Fax",
            "Pager", "Other", "Callback", "Car", "Company Main",
            "ISDN", "Main", "Other Fax", "Radio", "Telex", "TTY/TDD",
            "Work Mobile", "Work Pager", "Assistant", "MMS" };
    String[] sprimtype = {"Custom","AIM", "Windows Live", "Yahoo", "Skype", "QQ",
            "Google Talk", "ICQ", "Jabber"};
    String[] spremailtype = { "Custom","Home","Work","Other","Other Mobile"};
    String[] sprorgtype = {"Custom","Work", "Other"};
    String[] sprwebsitetype = {"Custom","Anniversary","Other","Birthday"};
   
    ArrayList<String> sprtypephone = new ArrayList<String>();
    ArrayList<String> sprtypeemail = new ArrayList<String>();
    ArrayList<String> sprtypeorg = new ArrayList<String>();
    ArrayList<String> sprtypeim = new ArrayList<String>();
    ArrayList<String> sprtypeevents = new ArrayList<String>();
   
    List<String> mygrouplist = null;
    List<String> getmygrouplist = null;
    GroupListAdapter grplstadp;
    ListView lstgrp;
    List<String> lstgprcheck;
   
    static ArrayList<String> addcontinlst;

    CheckBox imgarowlesmore, chkboxmore;

    EditText edtnamepref, edtfamilyname, edtmiddlename, edtgivenname,
            edtnamesifix, edtphoneticfamilyname, edtphoneticmidlename,
            edtphonecustomstr, edtphonetixgivenname, edtphone, edtemail,
            edtstreet, edtpobox, edtcity, edtneigthbhood, edtstate, edtzipcode,edtnote,edtnickname,
            edtcountry, edtorgname, edtorgtitle, edtim;
    static EditText edtwebsite;
    EditText edtevents;

    static String strfamilyname;
    static String strgivenname;
    String strnameprefix, strnamesufix,street,city,state,zip,country,pobox,neigborhood,strmiddlename,strphoneticfamilyname,strphoneticmiddlename
     ,myphoneedt,strphoneticgivenname,stremail,dbdate,contid,mywebsite;
    static String photoid;
    static String dateevent;
    static String selectedImagePath = "";
    String currentDateandTime,picturePath;
    String stremailtype;
    String mysprphontype;
    String sprlistemailtype;
    String sprlistaddtype;
    String sprlistorgtype;
    String postaladdedtitm;
    String strnote;
    static String strwebsite;
    static String strnickname;
    static String strwebsitename;
    String orgedtaddedtitm;
    static String strcustomsprtype,strcustomemailsprtype;
    String sprlistIMtype;
    String imedtaddedtitm;
    String sprlistEventstype;
    static String eventsedtaddedtitm;
    String orgtitle;
    String orgname;

    LinearLayout linearaddphone, linearemailadd, linearpostaldd, linearorg,
            linearim, lineatwebsite, linearevents, linearnotes, linearnickname,
            linearimmain, linearwebsitemain, lineareventsmain, linearmyown;

    int mytmpphone, mytmpemail, mytmppostaladd, mytmporg, mytmpbirthday,
            mytmpim;

    Spinner sprphone, spremail, spradd, sprorg, sprim, sprevents;

    ImageView mImage, mImageemail, mImageadd, mImageorg, mImageim,
            mImagewebsite, mImageevents, imguser;

    CheckBox chkadd;

    RelativeLayout.LayoutParams labelLayoutParams, sprlayout, imglayout,
            edtlayout, sprlayoutemail, imglayoutemail, edtlayoutemail,
            sprlayoutpostaladd, imglayoutadd, imglayoutaddcheckbox,
            edtlayoutstreet, edtlayoutpobox, edtlayoutneighood,
            edtlayoutaddcity, edtlayoutaddstate, edtlayoutaddzipcode,imglayoutwebsite,edtlayoutwebsite,
            edtlayoutaddcountry, sprlayoutorg, imglayoutorg, edtlayoutorgname,
            edtlayoutorgtitle, edtlayoutcustom,sprlayoutim,imglayoutim,edtlayoutim,sprlayoutevents,edtlayoutevents,imglayoutevents;

    Button btnok, btnrevert;

    ArrayAdapter<String> mysprphntype;
    ArrayAdapter<String> myspremailtype;
    ArrayAdapter<String> mysprorgtype;
    ArrayAdapter<String> mysprimtype;
    ArrayAdapter<String> mysprwebsitetype;

    private List<String> editTextListPhone = new ArrayList<String>();
    private List<String> editTextListEmail = new ArrayList<String>();
    private List<String> editTextIM = new ArrayList<String>();
    private List<String> editTextevents = new ArrayList<String>();
    private static ArrayList<String> editTextwebsite = new ArrayList<String>();

    private List<String> sprListphone = new ArrayList<String>();
    private List<String> sprListemail = new ArrayList<String>();
    private List<String> sprListaddress = new ArrayList<String>();
    private List<String> sprListorg = new ArrayList<String>();
    private List<String> sprListim = new ArrayList<String>();
    private List<String> sprListevents = new ArrayList<String>();

    List<String> strphonerowidlst = new ArrayList<String>();
    List<String> stremailrowidlst = new ArrayList<String>();
    List<String> straddressrowidlst = new ArrayList<String>();
    List<String> strorgrowidlst = new ArrayList<String>();
    List<String> strimrowidlst = new ArrayList<String>();
    List<String> streventsrowidlst = new ArrayList<String>();
    List<String> strwebsiterowidlst = new ArrayList<String>();

    TextView txtgropname;
    EditText txtbloodgrp;
    String bloodgroup;
    private PopupWindow mpopup;
    private static int RESULT_LOAD_IMAGE = 100;
    private final int CAMERA_RESULT = 1;
    Bitmap photo;
    View viewatende = null;

    Integer minsidemail, minidadd, minusidorg,minusidim,minusidevents,minsidwebsite;
    static Integer myemailtype;
    static Integer mytype;

    String minsidphone;
    static Phone phonesetget;
    static ArrayList<Phone> phonarylst;
    Group grpsetget;
    ArrayList<Group> grparylst;
    static Email emailsetget;
    static ArrayList<Email> emailarylst;
    static Address postaddsetget;
    static ArrayList<Address> addarylst;
    static Organization orgsetget;
    static ArrayList<Organization> orgarylst;
    static Im imsetget;
    static ArrayList<Im> imarylst;
    static Events events;
    static ArrayList<Events> arylstevents;
    Note note;
   
    static Contact contatsetget;
    static final int DATE_DIALOG_ID = 1;
    Calendar calender;
    private int pYear;
    private int pMonth;
    private int pDay;
   
    Contact cont;
    static ContentProviderResult[] results;
    ContentResolver contentResolver;
   
    static ArrayList<ContentProviderOperation> operations;
    static Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addcontc);

        for (int m = 0; m < sprphonetype.length; m++) {
            sprtypephone.add(sprphonetype[m]);
        }
        for (int i = 0; i < spremailtype.length; i++) {
            sprtypeemail.add(spremailtype[i]);
        }
        for (int k = 0; k < sprorgtype.length; k++) {
            sprtypeorg.add(sprorgtype[k]);
        }
        for (int j = 0; j < sprimtype.length; j++) {
            sprtypeim.add(sprimtype[j]);
        }
        for (int e = 0; e < sprwebsitetype.length; e++) {
            sprtypeevents.add(sprwebsitetype[e]);
        }
       
        bindComponent();
        mContext = AddCont.this;
        contentResolver = mContext.getContentResolver();
       
        init();
        addListners();

    }

    private void bindComponent() {
        // TODO Auto-generated method stub
        imgarowlesmore = (CheckBox) findViewById(R.id.btnarowimg);
        chkboxmore = (CheckBox) findViewById(R.id.btnarowimgmore);
        imguser = (ImageButton) findViewById(R.id.btnaddimg);
       
        edtnamepref = (EditText) findViewById(R.id.editTextnameprefinx);
        edtfamilyname = (EditText) findViewById(R.id.editTextfamilyname);
        edtmiddlename = (EditText) findViewById(R.id.editTextmiddlename);
        edtgivenname = (EditText) findViewById(R.id.editTextgivenname);
        edtnamesifix = (EditText) findViewById(R.id.editTextnamesifix);
        edtphoneticfamilyname = (EditText) findViewById(R.id.editTextphoneticfamilyname);
        edtphoneticmidlename = (EditText) findViewById(R.id.editTextphoneticmiddlename);
        edtphonetixgivenname = (EditText) findViewById(R.id.editTextphoneticgivenname);
        edtnote = (EditText)findViewById(R.id.edtnotes);
        edtnickname = (EditText)findViewById(R.id.edtnickname);

        linearaddphone = (LinearLayout) findViewById(R.id.linearphoneaddbotom);
        linearemailadd = (LinearLayout) findViewById(R.id.linearemailaddbotom);
        linearpostaldd = (LinearLayout) findViewById(R.id.linearpostaladdbotom);
        linearorg = (LinearLayout) findViewById(R.id.linearorgbotom);
        linearim = (LinearLayout) findViewById(R.id.linearimbotom);
        lineatwebsite = (LinearLayout) findViewById(R.id.linearwebsitebotom);
        linearevents = (LinearLayout) findViewById(R.id.lineareventsbotom);
        linearnotes = (LinearLayout) findViewById(R.id.linearnotes);
        linearnickname = (LinearLayout) findViewById(R.id.linearnickname);
        linearimmain = (LinearLayout) findViewById(R.id.linearim);
        linearwebsitemain = (LinearLayout) findViewById(R.id.linearwebsite);
        lineareventsmain = (LinearLayout) findViewById(R.id.linearevents);

        txtgropname = (TextView) findViewById(R.id.textViewgrptitle);
        //txtbloodgrp = (EditText)findViewById(R.id.edtbloodgroup);

        btnok = (Button) findViewById(R.id.buttodone);
        btnrevert = (Button) findViewById(R.id.buttonrevert);
    }

    @SuppressLint({ "NewApi", "SimpleDateFormat" })
    private void init() {
        // TODO Auto-generated method stub
       
        Utility.tempedittextphone = 0;
        Utility.tempedittextemail = 0;
       
        calender = Calendar.getInstance();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        currentDateandTime = sdf.format(new Date());

        Intent i = getIntent();
        String netmp;
        if (null != i.getExtras()) {
            String mycheckgrplst = i.getExtras().getString("gropchecklst");
            contid = i.getExtras().getString("contid");
           
            Log.i(tag, "get contid...." + contid);
            Log.i(tag, "get checked grp list...." + mycheckgrplst);

            if (!TextUtils.isEmpty(mycheckgrplst)) {
                netmp = mycheckgrplst.replaceAll("\\[|\\]", "");
                System.out.println(netmp);
                txtgropname.setText(netmp);
            }
        } else {
            txtgropname.setText(getResources().getString(R.string.nonetxt));
        }
       
        imgarowlesmore.setBackgroundResource(R.drawable.edit_btn_more_selector);
        imgarowlesmore.setButtonDrawable(R.drawable.edit_btn_more_selector);
        edtnamepref.setVisibility(View.GONE);
        edtmiddlename.setVisibility(View.GONE);
        edtnamesifix.setVisibility(View.GONE);
        edtphoneticfamilyname.setVisibility(View.GONE);
        edtphoneticmidlename.setVisibility(View.GONE);
        edtphonetixgivenname.setVisibility(View.GONE);

        imgarowlesmore.setBackgroundResource(R.drawable.edit_btn_more_selector);
        imgarowlesmore.setButtonDrawable(R.drawable.edit_btn_more_selector);
        linearimmain.setVisibility(View.GONE);
        linearwebsitemain.setVisibility(View.GONE);
        lineareventsmain.setVisibility(View.GONE);
        linearnotes.setVisibility(View.GONE);
        linearnickname.setVisibility(View.GONE);

        imgarowlesmore
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isChecked) {
                        // TODO Auto-generated method stub
                        if (imgarowlesmore.isChecked() == true) {
                            imgarowlesmore
                                    .setBackgroundResource(R.drawable.edit_btn_less_selector);
                            imgarowlesmore
                                    .setButtonDrawable(R.drawable.edit_btn_less_selector);
                            edtnamepref.setVisibility(View.VISIBLE);
                            edtmiddlename.setVisibility(View.VISIBLE);
                            edtnamesifix.setVisibility(View.VISIBLE);
                            edtphoneticfamilyname.setVisibility(View.VISIBLE);
                            edtphoneticmidlename.setVisibility(View.VISIBLE);
                            edtphonetixgivenname.setVisibility(View.VISIBLE);
                        } else {
                            imgarowlesmore
                                    .setBackgroundResource(R.drawable.edit_btn_more_selector);
                            imgarowlesmore
                                    .setButtonDrawable(R.drawable.edit_btn_more_selector);
                            edtnamepref.setVisibility(View.GONE);
                            edtmiddlename.setVisibility(View.GONE);
                            edtnamesifix.setVisibility(View.GONE);
                            edtphoneticfamilyname.setVisibility(View.GONE);
                            edtphoneticmidlename.setVisibility(View.GONE);
                            edtphonetixgivenname.setVisibility(View.GONE);
                        }
                    }
                });

        chkboxmore.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                if (chkboxmore.isChecked() == true) {
                    chkboxmore
                            .setBackgroundResource(R.drawable.edit_btn_less_selector);
                    chkboxmore
                            .setButtonDrawable(R.drawable.edit_btn_less_selector);
                    linearimmain.setVisibility(View.VISIBLE);
                    linearwebsitemain.setVisibility(View.VISIBLE);
                    lineareventsmain.setVisibility(View.VISIBLE);
                    linearnotes.setVisibility(View.VISIBLE);
                    linearnickname.setVisibility(View.VISIBLE);
                } else {
                    chkboxmore
                            .setBackgroundResource(R.drawable.edit_btn_more_selector);
                    chkboxmore
                            .setButtonDrawable(R.drawable.edit_btn_more_selector);
                    linearimmain.setVisibility(View.GONE);
                    linearwebsitemain.setVisibility(View.GONE);
                    lineareventsmain.setVisibility(View.GONE);
                    linearnotes.setVisibility(View.GONE);
                    linearnickname.setVisibility(View.GONE);
                }
            }
        });
    }

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    public void phoneAddClick(View v) {

        final RelativeLayout layoutphone = new RelativeLayout(this);
        labelLayoutParams = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        layoutphone.setLayoutParams(labelLayoutParams);
        layoutphone.setPadding(5, 0, 5, 0);

        // If you want to add some controls in this Relative Layout
        sprlayout = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 70);
        sprlayout.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        sprlayout.addRule(RelativeLayout.CENTER_HORIZONTAL);
        sprphone = new Spinner(AddCont.this);
        sprphone.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        sprphone.setBackgroundResource(R.drawable.spinnerselector);
        sprphone.setId(1001);
        sprphone.setGravity(Gravity.CENTER);
        sprphone.setPrompt("Select lable");
        mysprphntype = new ArrayAdapter<String>(AddCont.this,
                R.layout.sprlistraw, sprtypephone);
        sprphone.setAdapter(mysprphntype);
        layoutphone.addView(sprphone, sprlayout);

        imglayout = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        imglayout.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        imglayout.addRule(RelativeLayout.CENTER_IN_PARENT);
        mImage = new ImageView(this);
        mImage.setBackgroundResource(R.drawable.ic_btn_round_minus);
        mImage.setId(1000);
        layoutphone.addView(mImage, imglayout);

        edtlayout = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT);
        edtlayout.addRule(RelativeLayout.CENTER_IN_PARENT);
        edtlayout.addRule(RelativeLayout.RIGHT_OF, 1001);
        edtlayout.addRule(RelativeLayout.LEFT_OF, 1000);

        edtphone = new EditText(AddCont.this);
        edtphone.setInputType(InputType.TYPE_CLASS_NUMBER);
        int maxlength = 13;
        edtphone.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) });
        edtphone.setHint(getResources().getString(R.string.contphone));
        edtphone.setBackgroundResource(R.drawable.repeat_edit);
        edtphone.setSingleLine(true);
        layoutphone.addView(edtphone, edtlayout);

        mytmpphone = Utility.tempphone += 1;
        if (mytmpphone == 1) {
            sprphone.setSelection(1);
        } else if (mytmpphone == 2) {
            sprphone.setSelection(2);
        } else if (mytmpphone == 3) {
            sprphone.setSelection(3);
        } else {
            sprphone.setSelection(7);
        }

        linearaddphone.addView(layoutphone);

        mImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                linearaddphone.removeView(layoutphone);
                mytmpphone = Utility.tempphone -= 1;
            }
        });

        sprphone.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int pos, long id) {
                // TODO Auto-generated method stub
                if (sprphone.getSelectedItem() == "Custom") {

                    // custom dialog
                    final Dialog dialog = new Dialog(AddCont.this);
                    dialog.setContentView(R.layout.customdialog);
                    dialog.setTitle("Custom lable name");

                    // set the custom dialog components - text, image and button
                    final EditText edtlable = (EditText) dialog
                            .findViewById(R.id.editTexttypename);
                    Button btncustomok = (Button) dialog
                            .findViewById(R.id.buttoncustomok);
                    Button btncustomcancel = (Button) dialog
                            .findViewById(R.id.buttoncustomcancel);

                    btncustomcancel.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });

                    btncustomok.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            strcustomsprtype = edtlable.getText().toString();
                            dialog.dismiss();

                            sprtypephone.add(strcustomsprtype);
                            sprphone.setSelection(sprtypephone.lastIndexOf(strcustomsprtype));
                        }
                    });

                    dialog.show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {}
        });
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public void emailAddClick(View v) {

        final RelativeLayout layoutemail = new RelativeLayout(this);
        labelLayoutParams = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        layoutemail.setLayoutParams(labelLayoutParams);
        layoutemail.setPadding(5, 0, 5, 0);

        // If you want to add some controls in this Relative Layout
        sprlayoutemail = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 70);
        sprlayoutemail.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        sprlayoutemail.addRule(RelativeLayout.CENTER_IN_PARENT);
        spremail = new Spinner(AddCont.this);
        spremail.setBackgroundResource(R.drawable.spinnerselector);
        spremail.setId(1000);
        spremail.setGravity(Gravity.CENTER);
        spremail.setPrompt("Select lable");

        myspremailtype = new ArrayAdapter<String>(AddCont.this,
                R.layout.sprlistraw, sprtypeemail);
        spremail.setAdapter(myspremailtype);
        layoutemail.addView(spremail, sprlayoutemail);

        imglayoutemail = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        imglayoutemail.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        imglayoutemail.addRule(RelativeLayout.CENTER_IN_PARENT);
        mImageemail = new ImageView(this);
        mImageemail.setBackgroundResource(R.drawable.ic_btn_round_minus);
        mImageemail.setId(1001);
        layoutemail.addView(mImageemail, imglayoutemail);

        edtlayoutemail = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutemail.addRule(RelativeLayout.CENTER_IN_PARENT);
        edtlayoutemail.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutemail.addRule(RelativeLayout.LEFT_OF, 1001);
        edtemail = new EditText(AddCont.this);
        edtemail.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        edtemail.setBackgroundResource(R.drawable.repeat_edit);
        edtemail.setHint(getResources().getString(R.string.contemail));
        edtemail.setSingleLine(true);

        layoutemail.addView(edtemail, edtlayoutemail);

        mytmpemail = Utility.tempemail += 1;
        if (mytmpemail == 1) {
            spremail.setSelection(1);
        } else if (mytmpemail == 2) {
            spremail.setSelection(2);
        } else if (mytmpemail == 3) {
            spremail.setSelection(3);
        } else {
            spremail.setSelection(3);
        }

        linearemailadd.addView(layoutemail);

        mImageemail.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                linearemailadd.removeView(layoutemail);
                mytmpemail = Utility.tempemail -= 1;
            }
        });

        spremail.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int pos, long id) {
                // TODO Auto-generated method stub
                if (spremail.getSelectedItem() == "Custom") {

                    // custom dialog
                    final Dialog dialog = new Dialog(AddCont.this);
                    dialog.setContentView(R.layout.customdialog);
                    dialog.setTitle("Custom lable name");

                    // set the custom dialog components - text, image and button
                    final EditText edtlable = (EditText) dialog
                            .findViewById(R.id.editTexttypename);
                    Button btncustomok = (Button) dialog
                            .findViewById(R.id.buttoncustomok);
                    Button btncustomcancel = (Button) dialog
                            .findViewById(R.id.buttoncustomcancel);

                    btncustomcancel.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });

                    btncustomok.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            strcustomemailsprtype = edtlable.getText().toString();
                            dialog.dismiss();
                            sprtypeemail.add(strcustomemailsprtype);
                            spremail.setSelection(sprtypeemail.lastIndexOf(strcustomemailsprtype));
                        }
                    });
                    dialog.show();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public void postalAddressClick(View v) {

        final RelativeLayout layoutpostalladd = new RelativeLayout(this);
        labelLayoutParams = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        layoutpostalladd.setLayoutParams(labelLayoutParams);
        layoutpostalladd.setPadding(5, 5, 5, 5);

        // If you want to add some controls in this Relative Layout
        sprlayoutpostaladd = new RelativeLayout.LayoutParams(120, 70);
        sprlayoutpostaladd.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        sprlayoutpostaladd.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        spradd = new Spinner(AddCont.this);
        spradd.setBackgroundResource(R.drawable.spinnerselector);
        spradd.setId(1000);
        spradd.setGravity(Gravity.CENTER);
        spradd.setPrompt("Select lable");

        myspremailtype = new ArrayAdapter<String>(AddCont.this,
                R.layout.sprlistraw, sprtypeemail);
        spradd.setAdapter(myspremailtype);
        layoutpostalladd.addView(spradd, sprlayoutpostaladd);

        imglayoutadd = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        imglayoutadd.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        imglayoutadd.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        mImageadd = new ImageView(this);
        mImageadd.setBackgroundResource(R.drawable.ic_btn_round_minus);
        mImageadd.setId(1001);
        layoutpostalladd.addView(mImageadd, imglayoutadd);

        imglayoutaddcheckbox = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        imglayoutaddcheckbox.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        imglayoutaddcheckbox.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        chkadd = new CheckBox(this);
        chkadd.setBackgroundResource(R.drawable.edit_btn_less_selector);
        chkadd.setButtonDrawable(R.drawable.edit_btn_less_selector);
        chkadd.setId(1002);
        layoutpostalladd.addView(chkadd, imglayoutaddcheckbox);

        edtlayoutstreet = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutstreet.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutstreet.addRule(RelativeLayout.LEFT_OF, 1001);
        edtstreet = new EditText(AddCont.this);
        edtstreet.setBackgroundResource(R.drawable.repeat_edit);
        edtstreet.setHint(getResources().getString(R.string.street));
        edtstreet.setId(100);
        edtstreet.setSingleLine(true);
        layoutpostalladd.addView(edtstreet, edtlayoutstreet);

        edtlayoutpobox = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutpobox.addRule(RelativeLayout.BELOW, 100);
        edtlayoutpobox.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutpobox.addRule(RelativeLayout.LEFT_OF, 1001);
        edtpobox = new EditText(AddCont.this);
        edtpobox.setBackgroundResource(R.drawable.repeat_edit);
        edtpobox.setHint(getResources().getString(R.string.pobox));
        edtpobox.setSingleLine(true);
        edtpobox.setId(101);
        layoutpostalladd.addView(edtpobox, edtlayoutpobox);

        edtlayoutneighood = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutneighood.addRule(RelativeLayout.BELOW, 101);
        edtlayoutneighood.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutneighood.addRule(RelativeLayout.LEFT_OF, 1001);
        edtneigthbhood = new EditText(AddCont.this);
        edtneigthbhood.setBackgroundResource(R.drawable.repeat_edit);
        edtneigthbhood.setHint(getResources().getString(R.string.neighborhood));
        edtneigthbhood.setSingleLine(true);
        edtneigthbhood.setId(102);
        layoutpostalladd.addView(edtneigthbhood, edtlayoutneighood);

        edtlayoutaddcity = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutaddcity.addRule(RelativeLayout.BELOW, 102);
        edtlayoutaddcity.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutaddcity.addRule(RelativeLayout.LEFT_OF, 1001);
        edtcity = new EditText(AddCont.this);
        edtcity.setBackgroundResource(R.drawable.repeat_edit);
        edtcity.setHint(getResources().getString(R.string.city));
        edtcity.setSingleLine(true);
        edtcity.setId(103);
        layoutpostalladd.addView(edtcity, edtlayoutaddcity);

        edtlayoutaddstate = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutaddstate.addRule(RelativeLayout.BELOW, 103);
        edtlayoutaddstate.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutaddstate.addRule(RelativeLayout.LEFT_OF, 1001);
        edtstate = new EditText(AddCont.this);
        edtstate.setBackgroundResource(R.drawable.repeat_edit);
        edtstate.setHint(getResources().getString(R.string.state));
        edtstate.setSingleLine(true);
        edtstate.setId(104);
        layoutpostalladd.addView(edtstate, edtlayoutaddstate);

        edtlayoutaddzipcode = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutaddzipcode.addRule(RelativeLayout.BELOW, 104);
        edtlayoutaddzipcode.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutaddzipcode.addRule(RelativeLayout.LEFT_OF, 1001);
        edtzipcode = new EditText(AddCont.this);
        edtzipcode.setBackgroundResource(R.drawable.repeat_edit);
        edtzipcode.setHint(getResources().getString(R.string.zipcode));
        edtzipcode.setSingleLine(true);
        edtzipcode.setId(105);
        int maxlength = 6;
        edtzipcode.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) });
        layoutpostalladd.addView(edtzipcode, edtlayoutaddzipcode);

        edtlayoutaddcountry = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutaddcountry.addRule(RelativeLayout.BELOW, 105);
        edtlayoutaddcountry.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutaddcountry.addRule(RelativeLayout.LEFT_OF, 1001);
        edtcountry = new EditText(AddCont.this);
        edtcountry.setBackgroundResource(R.drawable.repeat_edit);
        edtcountry.setHint(getResources().getString(R.string.country));
        edtcountry.setSingleLine(true);
        layoutpostalladd.addView(edtcountry, edtlayoutaddcountry);

        chkadd.setBackgroundResource(R.drawable.edit_btn_more_selector);
        chkadd.setButtonDrawable(R.drawable.edit_btn_more_selector);
        edtpobox.setVisibility(View.GONE);
        edtcountry.setVisibility(View.GONE);
        edtneigthbhood.setVisibility(View.GONE);

        mytmppostaladd = Utility.temppostaladd += 1;
        Log.i(tag, "mytamp poastal address add is......" + mytmppostaladd);
        if (mytmppostaladd == 1) {
            spradd.setSelection(1);
        } else if (mytmppostaladd == 2) {
            spradd.setSelection(2);
        } else if (mytmppostaladd == 3) {
            spradd.setSelection(3);
        } else {
            spradd.setSelection(3);
        }

        linearpostaldd.addView(layoutpostalladd);

        mImageadd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                linearpostaldd.removeView(layoutpostalladd);
                mytmppostaladd = Utility.temppostaladd -= 1;
                Log.i(tag, "mytamp poastal address remove is......"
                        + mytmppostaladd);

            }
        });

        chkadd.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub

                if (chkadd.isChecked() == true) {
                    chkadd.setBackgroundResource(R.drawable.edit_btn_less_selector);
                    chkadd.setButtonDrawable(R.drawable.edit_btn_less_selector);
                    edtcity.setVisibility(View.VISIBLE);
                    edtstate.setVisibility(View.VISIBLE);
                    edtstreet.setVisibility(View.VISIBLE);
                    edtpobox.setVisibility(View.VISIBLE);
                    edtcountry.setVisibility(View.VISIBLE);
                    edtzipcode.setVisibility(View.VISIBLE);
                    edtneigthbhood.setVisibility(View.VISIBLE);

                } else {
                    chkadd.setBackgroundResource(R.drawable.edit_btn_more_selector);
                    chkadd.setButtonDrawable(R.drawable.edit_btn_more_selector);
                    edtpobox.setVisibility(View.GONE);
                    edtcountry.setVisibility(View.GONE);
                    edtneigthbhood.setVisibility(View.GONE);
                }
            }
        });

        spradd.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int pos, long id) {
                // TODO Auto-generated method stub
                if (spradd.getSelectedItem() == "Custom") {

                    // custom dialog
                    final Dialog dialog = new Dialog(AddCont.this);
                    dialog.setContentView(R.layout.customdialog);
                    dialog.setTitle("Custom lable name");

                    // set the custom dialog components - text, image and button
                    final EditText edtlable = (EditText) dialog
                            .findViewById(R.id.editTexttypename);
                    Button btncustomok = (Button) dialog
                            .findViewById(R.id.buttoncustomok);
                    Button btncustomcancel = (Button) dialog
                            .findViewById(R.id.buttoncustomcancel);

                    btncustomcancel.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });

                    btncustomok.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            strcustomsprtype = edtlable.getText().toString();
                            dialog.dismiss();

                            sprtypeemail.add(strcustomsprtype);
                            spradd.setSelection(sprtypeemail.lastIndexOf(strcustomsprtype));
                        }
                    });
                    dialog.show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });
    }

    @SuppressLint("NewApi")
    public void organizationClick(View v) {

        final RelativeLayout layoutpostalorg = new RelativeLayout(this);
        labelLayoutParams = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        layoutpostalorg.setLayoutParams(labelLayoutParams);
        layoutpostalorg.setPadding(5, 5, 5, 5);

        sprlayoutorg = new RelativeLayout.LayoutParams(120, 70);
        sprlayoutorg.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        sprlayoutorg.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        sprorg = new Spinner(AddCont.this);
        sprorg.setBackgroundResource(R.drawable.spinnerselector);
        sprorg.setId(1000);
        sprorg.setGravity(Gravity.CENTER);
        sprorg.setPrompt("Select lable");

        mysprorgtype = new ArrayAdapter<String>(AddCont.this,
                R.layout.sprlistraw, sprorgtype);
        sprorg.setAdapter(mysprorgtype);
        layoutpostalorg.addView(sprorg, sprlayoutorg);

        imglayoutorg = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        imglayoutorg.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        imglayoutorg.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        mImageorg = new ImageView(this);
        mImageorg.setBackgroundResource(R.drawable.ic_btn_round_minus);
        mImageorg.setId(1001);
        layoutpostalorg.addView(mImageorg, imglayoutorg);

        edtlayoutorgname = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutorgname.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutorgname.addRule(RelativeLayout.LEFT_OF, 1001);
        edtorgname = new EditText(AddCont.this);
        edtorgname.setBackgroundResource(R.drawable.repeat_edit);
        edtorgname.setHint(getResources().getString(R.string.company));
        edtorgname.setId(100);
        edtorgname.setSingleLine(true);
        layoutpostalorg.addView(edtorgname, edtlayoutorgname);

        edtlayoutorgtitle = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutorgtitle.addRule(RelativeLayout.BELOW, 100);
        edtlayoutorgtitle.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutorgtitle.addRule(RelativeLayout.LEFT_OF, 1001);
        edtorgtitle = new EditText(AddCont.this);
        edtorgtitle.setBackgroundResource(R.drawable.repeat_edit);
        edtorgtitle.setHint(getResources().getString(R.string.title));
        edtorgtitle.setSingleLine(true);
        edtorgtitle.setId(101);
        layoutpostalorg.addView(edtorgtitle, edtlayoutorgtitle);

        mytmporg = Utility.temporg += 1;
        Log.i(tag, "mytamp org add is......" + mytmporg);
        if (mytmporg == 1) {
            sprorg.setSelection(1);
        } else if (mytmporg == 2) {
            sprorg.setSelection(2);
        } else {
            sprorg.setSelection(2);
        }

        linearorg.addView(layoutpostalorg);

        mImageorg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                linearorg.removeView(layoutpostalorg);
                mytmporg = Utility.temporg -= 1;
                Log.i(tag, "mytamp org remove is......" + mytmporg);
            }
        });

        sprorg.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int pos, long id) {
                // TODO Auto-generated method stub
                if (sprorg.getSelectedItem() == "Custom") {

                    // custom dialog
                    final Dialog dialog = new Dialog(AddCont.this);
                    dialog.setContentView(R.layout.customdialog);
                    dialog.setTitle("Custom lable name");

                    // set the custom dialog components - text, image and button
                    final EditText edtlable = (EditText) dialog
                            .findViewById(R.id.editTexttypename);
                    Button btncustomok = (Button) dialog
                            .findViewById(R.id.buttoncustomok);
                    Button btncustomcancel = (Button) dialog
                            .findViewById(R.id.buttoncustomcancel);

                    btncustomcancel.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });

                    btncustomok.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            strcustomsprtype = edtlable.getText().toString();
                            dialog.dismiss();

                            sprtypeemail.add(strcustomsprtype);
                            sprorg.setSelection(sprtypeemail.lastIndexOf(strcustomsprtype));
                        }
                    });
                    dialog.show();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });
    }

    public void groupListClick(View view) {

        getContactGrouplist();

        if (mygrouplist.isEmpty()) {
            Utility.showDialogwithTitle(AddCont.this, "Your device have no any group names");
        }else{
                // custom dialog
                final Dialog dialog = new Dialog(AddCont.this);
                dialog.setContentView(R.layout.grouplistraw);
                dialog.setTitle("Select group");

                // set the custom dialog components - text, image and button
                lstgrp = (ListView) dialog.findViewById(R.id.listViewgrplst);
                Button btngroupok = (Button) dialog.findViewById(R.id.btnok);
                Button btngroupcancel = (Button) dialog.findViewById(R.id.btncancel);
               
                grplstadp = new GroupListAdapter(AddCont.this, mygrouplist);
                lstgrp.setAdapter(grplstadp);
               
                btngroupcancel.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                btngroupok.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        lstgprcheck = new ArrayList<String>();
                        lstgprcheck = grplstadp.GroupListMethod();
                       
                        dialog.dismiss();
                       
                        Log.i(tag, "get group list...." + lstgprcheck);
                        String netmp;
                        if (lstgprcheck != null) {
                           
                            String mycheckgrplst = lstgprcheck.toString();
                            if (!TextUtils.isEmpty(lstgprcheck.toString())) {

                                netmp = mycheckgrplst.replaceAll("\\[|\\]", "");
                                System.out.println(netmp);
                                txtgropname.setText(netmp);
                            }
                        } else {
                            txtgropname.setText(getResources().getString(R.string.nonetxt));
                        }
                    }
                });
               
                dialog.show();
           
            }
    }

    @SuppressLint("NewApi")
    public void imClick(View v) {

        final RelativeLayout layoutim = new RelativeLayout(this);
        labelLayoutParams = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        layoutim.setLayoutParams(labelLayoutParams);
        layoutim.setPadding(5, 0, 5, 0);

        // If you want to add some controls in this Relative Layout
        sprlayoutim = new RelativeLayout.LayoutParams(
                120, 70);
        sprlayoutim.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        sprlayoutim.addRule(RelativeLayout.CENTER_IN_PARENT);
        sprim = new Spinner(AddCont.this);
        sprim.setBackgroundResource(R.drawable.spinnerselector);
        sprim.setId(1000);
        sprim.setGravity(Gravity.CENTER);
        sprim.setPrompt("Select lable");
       
        mysprimtype = new ArrayAdapter<String>(AddCont.this, R.layout.sprlistraw, sprimtype);
        sprim.setAdapter(mysprimtype);
        layoutim.addView(sprim, sprlayoutim);

        imglayoutim = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        imglayoutim.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        imglayoutim.addRule(RelativeLayout.CENTER_IN_PARENT);
        mImageim = new ImageView(this);
        mImageim.setBackgroundResource(R.drawable.ic_btn_round_minus);
        mImageim.setId(1001);
        layoutim.addView(mImageim, imglayoutim);

        edtlayoutim = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutim.addRule(RelativeLayout.CENTER_IN_PARENT);
        edtlayoutim.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutim.addRule(RelativeLayout.LEFT_OF, 1001);
        edtim = new EditText(AddCont.this);
        edtim.setId(100);
        edtim.setBackgroundResource(R.drawable.repeat_edit);
        edtim.setHint(getResources().getString(R.string.imdetal));
        edtim.setSingleLine(true);
        layoutim.addView(edtim, edtlayoutim);

        mytmpim = Utility.tempim += 1;
        Log.i(tag, "mytamp im is......" + mytmpim);
        if (mytmpim == 1) {
            sprim.setSelection(1);
        } else if (mytmpim == 2) {
            sprim.setSelection(2);
        } else if (mytmpim == 3) {
            sprim.setSelection(3);
        } else if (mytmpim == 4) {
            sprim.setSelection(4);
        } else if (mytmpim == 5) {
            sprim.setSelection(5);
        } else if (mytmpim == 6) {
            sprim.setSelection(6);
        } else if (mytmpim == 7) {
            sprim.setSelection(7);
        } else if (mytmpim == 8) {
            sprim.setSelection(8);
        }

        linearim.addView(layoutim);

        mImageim.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                linearim.removeView(layoutim);
                mytmpim = Utility.tempim -= 1;
                Log.i(tag, "mytamp im is......" + mytmpim);
            }
        });

        sprim.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int pos, long id) {
                // TODO Auto-generated method stub
                if (sprim.getSelectedItem() == "Custom") {

                    // custom dialog
                    final Dialog dialog = new Dialog(AddCont.this);
                    dialog.setContentView(R.layout.customdialog);
                    dialog.setTitle("Custom lable name");

                    // set the custom dialog components - text, image and button
                    final EditText edtlable = (EditText) dialog
                            .findViewById(R.id.editTexttypename);
                    Button btncustomok = (Button) dialog
                            .findViewById(R.id.buttoncustomok);
                    Button btncustomcancel = (Button) dialog
                            .findViewById(R.id.buttoncustomcancel);

                    btncustomcancel.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });

                    btncustomok.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            strcustomsprtype = edtlable.getText().toString();
                            dialog.dismiss();

                            sprtypeim.add(strcustomsprtype);
                            sprim.setSelection(sprtypeim.lastIndexOf(strcustomsprtype));
                        }
                    });
                    dialog.show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });
       
    }

    public void websiteClick(View v) {

        final RelativeLayout layoutwebsite = new RelativeLayout(this);
        labelLayoutParams = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        layoutwebsite.setLayoutParams(labelLayoutParams);
        layoutwebsite.setPadding(5, 0, 5, 0);

        imglayoutwebsite = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        imglayoutwebsite.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        imglayoutwebsite.addRule(RelativeLayout.CENTER_IN_PARENT);
        mImagewebsite = new ImageView(this);
        mImagewebsite.setBackgroundResource(R.drawable.ic_btn_round_minus);
        mImagewebsite.setId(1001);
        layoutwebsite.addView(mImagewebsite, imglayoutwebsite);

        edtlayoutwebsite = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutwebsite.addRule(RelativeLayout.CENTER_IN_PARENT);
        edtlayoutwebsite.addRule(RelativeLayout.LEFT_OF, 1001);
        edtwebsite = new EditText(AddCont.this);
        edtwebsite.setId(100);
        edtwebsite.setBackgroundResource(R.drawable.repeat_edit);
        edtwebsite.setHint(getResources().getString(R.string.website));
        edtwebsite.setSingleLine(true);
        layoutwebsite.addView(edtwebsite, edtlayoutwebsite);

        lineatwebsite.addView(layoutwebsite);

        mImagewebsite.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                lineatwebsite.removeView(layoutwebsite);
            }
        });
    }
   
   
    @SuppressLint("NewApi")
    public void eventsClick(View v) {

        final RelativeLayout layoutevents = new RelativeLayout(this);
        labelLayoutParams = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        layoutevents.setLayoutParams(labelLayoutParams);
        layoutevents.setPadding(5, 0, 5, 0);

        // If you want to add some controls in this Relative Layout
        sprlayoutevents = new RelativeLayout.LayoutParams(
                120, 70);
        sprlayoutevents.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        sprlayoutevents.addRule(RelativeLayout.CENTER_IN_PARENT);
        sprevents = new Spinner(AddCont.this);
        sprevents.setBackgroundResource(R.drawable.spinnerselector);
        sprevents.setId(1000);
        sprevents.setGravity(Gravity.CENTER);
        sprevents.setPrompt("Select lable");
       
        mysprwebsitetype = new ArrayAdapter<String>(
                AddCont.this, R.layout.sprlistraw, sprtypeevents);
        sprevents.setAdapter(mysprwebsitetype);
        layoutevents.addView(sprevents, sprlayoutevents);

        imglayoutevents = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        imglayoutevents.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        imglayoutevents.addRule(RelativeLayout.CENTER_IN_PARENT);
        mImageevents = new ImageView(this);
        mImageevents.setBackgroundResource(R.drawable.ic_btn_round_minus);
        mImageevents.setId(1001);
        layoutevents.addView(mImageevents, imglayoutevents);

        edtlayoutevents = new RelativeLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        edtlayoutevents.addRule(RelativeLayout.CENTER_IN_PARENT);
        edtlayoutevents.addRule(RelativeLayout.RIGHT_OF, 1000);
        edtlayoutevents.addRule(RelativeLayout.LEFT_OF, 1001);
        edtevents = new EditText(AddCont.this);
        edtevents.setId(100);
        edtevents.setBackgroundResource(R.drawable.repeat_edit);
        edtevents.setHint(getResources().getString(R.string.events));
        edtevents.setSingleLine(true);
        layoutevents.addView(edtevents, edtlayoutevents);

        mytmpbirthday = Utility.tempbirthday += 1;
        Log.i(tag, "mytamp birtdhay is......" + mytmpbirthday);
        if (mytmpbirthday == 1) {
            sprevents.setSelection(0);
        } else if (mytmpbirthday == 2) {
            sprevents.setSelection(1);
        } else if (mytmpbirthday == 3) {
            sprevents.setSelection(2);
        } else {
            sprevents.setSelection(2);
        }

        linearevents.addView(layoutevents);

        mImageevents.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                linearevents.removeView(layoutevents);
                mytmpbirthday = Utility.tempbirthday -= 1;
                Log.i(tag, "mytamp birtdhay is......" + mytmpbirthday);
            }
        });
       
        edtevents.setOnClickListener(new OnClickListener() {
           
            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 final Calendar c = Calendar.getInstance();
                 pYear = c.get(Calendar.YEAR);
                 pMonth = c.get(Calendar.MONTH);
                 pDay = c.get(Calendar.DAY_OF_MONTH);
                showDialog(DATE_DIALOG_ID);
            }
        });
       
        sprevents.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int pos, long id) {
                // TODO Auto-generated method stub
                if (sprevents.getSelectedItem() == "Custom") {

                    // custom dialog
                    final Dialog dialog = new Dialog(AddCont.this);
                    dialog.setContentView(R.layout.customdialog);
                    dialog.setTitle("Custom lable name");

                    // set the custom dialog components - text, image and button
                    final EditText edtlable = (EditText) dialog
                            .findViewById(R.id.editTexttypename);
                    Button btncustomok = (Button) dialog
                            .findViewById(R.id.buttoncustomok);
                    Button btncustomcancel = (Button) dialog
                            .findViewById(R.id.buttoncustomcancel);

                    btncustomcancel.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });

                    btncustomok.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            strcustomsprtype = edtlable.getText().toString();
                            dialog.dismiss();

                            sprtypeevents.add(strcustomsprtype);
                            sprevents.setSelection(sprtypeevents.lastIndexOf(strcustomsprtype));
                        }
                    });
                    dialog.show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });

    }
   
     /** Callback received when the user "picks" a date in the dialog */
    private DatePickerDialog.OnDateSetListener pDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {
                    pYear = year;
                    pMonth = monthOfYear;
                    pDay = dayOfMonth;
                    updateDisplay();
                }
            };
    
    /** Updates the date in the TextView */
    private void updateDisplay() {
       
        edtevents.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(pMonth + 1).append("/")
                    .append(pDay).append("/")
                    .append(pYear).append(" "));
    }


    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,
                        pDateSetListener,
                        pYear, pMonth, pDay);
        }
        return null;
    }

    private void addListners() {
        // TODO Auto-generated method stub
    }
   
    public void addContactClick(View v) {
       
        contatsetget = new Contact();
        // get name details from edittext
        strfamilyname = edtfamilyname.getText().toString();
        strgivenname = edtgivenname.getText().toString();
        strnameprefix = edtnamepref.getText().toString();
        strnamesufix = edtnamesifix.getText().toString();
        strmiddlename = edtmiddlename.getText().toString();
        strphoneticfamilyname = edtphoneticfamilyname.getText().toString();
        strphoneticmiddlename = edtphoneticmidlename.getText().toString();
        strphoneticgivenname = edtphonetixgivenname.getText().toString();

        contatsetget.setFirstName(strfamilyname);
        contatsetget.setLastName(strgivenname);
       
        // =================== Start Code for Getting Phone details =======================

        // get phone number type details
        phonesetget = new Phone();
        phonarylst = new ArrayList<Phone>();
       
        sprListphone = new ArrayList<String>();
        editTextListPhone = new ArrayList<String>();
        strphonerowidlst = new ArrayList<String>();

        for (int i = 0; i < linearaddphone.getChildCount(); i++) {
            //minsidphone = i;
            View veiwlayout = linearaddphone.getChildAt(i);

            if (veiwlayout instanceof RelativeLayout) {

                int mchildd = ((RelativeLayout) veiwlayout).getChildCount();
                for (int x = 0; x < mchildd; x++) {

                    View subview = ((RelativeLayout) veiwlayout).getChildAt(x);

                    if (subview instanceof Spinner) {
                        mysprphontype = ((Spinner) subview).getSelectedItem()
                                .toString();
                        System.out
                                .println("sprphone.getItemAtPosition(i).toString()........."+ mysprphontype);
                        sprListphone.add(mysprphontype);
                    }
                    if (subview instanceof EditText) {
                        myphoneedt = ((EditText) subview).getText().toString();
                        System.out.println("myphoneedt........." + myphoneedt);
                        editTextListPhone.add(myphoneedt);
                    }
                   
                }
            }
            //strphonerowidlst.add(minsidphone);
            /*phonesetget.setNo(myphoneedt);
            phonesetget.setRowId(minsidphone.toString());
            phonesetget.setType(mysprphontype);*/
           
            phonesetget = new Phone(mysprphontype,myphoneedt);
            phonarylst.add(phonesetget);
        }
        contatsetget.setPhones(phonarylst);
        System.out.println("Get Phone getset lst....."+phonarylst.toString());

        // =================== End Code for Getting Phone details =======================

        // =================== Start Code for Getting Email details  =======================

        // get email type list
        emailsetget = new Email();
        emailarylst = new ArrayList<Email>();
        sprListemail = new ArrayList<String>();
        editTextListEmail = new ArrayList<String>();
        stremailrowidlst = new ArrayList<String>();

        for (int i = 0; i < linearemailadd.getChildCount(); i++) {
            minsidemail = i;
            View veiwlayoutemail = linearemailadd.getChildAt(i);

            if (veiwlayoutemail instanceof RelativeLayout) {

                int mchildd = ((RelativeLayout) veiwlayoutemail)
                        .getChildCount();
                for (int x = 0; x < mchildd; x++) {
                    View subviewemail = ((RelativeLayout) veiwlayoutemail)
                            .getChildAt(x);

                    if (subviewemail instanceof Spinner) {
                        sprlistemailtype = ((Spinner) subviewemail)
                                .getSelectedItem().toString();
                        sprListemail.add(sprlistemailtype);
                    }

                    if (subviewemail instanceof EditText) {
                        myphoneedt = ((EditText) subviewemail).getText()
                                .toString();
                        if(Utility.validEmail(myphoneedt)){
                            System.out.println("myphoneedt.........." + myphoneedt);
                            editTextListEmail.add(myphoneedt);
                        }else{
                            Utility.showDialogwithTitle(mContext, "Enter Valid Email Address");
                        }
                       
                       
                    }
                }
            }
            stremailrowidlst.add(minsidemail.toString());
            emailsetget = new Email(sprlistemailtype,myphoneedt);
            emailarylst.add(emailsetget);
        }
        contatsetget.setEmails(emailarylst);
        System.out.println("Get Email getset lst....."+emailarylst.toString());

        // =================== End Code for Getting Email details =======================

        // =================== Start Code for Getting Postal Address details  =======================

        // get address type list details
        postaddsetget = new Address();
        addarylst = new ArrayList<Address>();
        sprListaddress = new ArrayList<String>();
        straddressrowidlst = new ArrayList<String>();

        for (int i = 0; i < linearpostaldd.getChildCount(); i++) {
            minidadd = i;
            View veiwlayoutaddress = linearpostaldd.getChildAt(i);

            if (veiwlayoutaddress instanceof RelativeLayout) {

                int mchildd = ((RelativeLayout) veiwlayoutaddress)
                        .getChildCount();
                for (int x = 0; x < mchildd; x++) {
                    View subviewaddress = ((RelativeLayout) veiwlayoutaddress)
                            .getChildAt(x);

                    if (subviewaddress instanceof Spinner) {
                        sprlistaddtype = ((Spinner) subviewaddress)
                                .getSelectedItem().toString();
                        // System.out.println("sprlistemailtype.........."+sprlistaddtype);
                        sprListaddress.add(sprlistaddtype);
                    }

                    if (subviewaddress instanceof EditText) {
                        postaladdedtitm = ((EditText) subviewaddress).getText()
                                .toString();
                        // System.out.println("postaladdedtitm.........."+postaladdedtitm);

                        System.out.println("subviewaddress.getId()......"
                                + subviewaddress.getId());
                        if (subviewaddress.getId() == 100) {
                            street = postaladdedtitm;
                            //editTextListaddStreet.add(postaladdedtitm);
                        }
                        if (subviewaddress.getId() == 101) {
                            pobox = postaladdedtitm;
                            //editTextListaddpobox.add(postaladdedtitm);
                        }
                        if (subviewaddress.getId() == 102) {
                            neigborhood = postaladdedtitm;
                            //editTextListaddneighbrhood.add(postaladdedtitm);
                        }
                        if (subviewaddress.getId() == 103) {
                            city = postaladdedtitm;
                            //editTextListaddcity.add(postaladdedtitm);
                        }
                        if (subviewaddress.getId() == 104) {
                            state = postaladdedtitm;
                            //editTextListaddState.add(postaladdedtitm);
                        }
                        if (subviewaddress.getId() == 105) {
                            zip = postaladdedtitm;
                            //editTextListaddzipcode.add(postaladdedtitm);
                        }
                        if (subviewaddress.getId() == -1) {
                            country = postaladdedtitm;
                            //editTextListaddCountry.add(postaladdedtitm);
                        }
                    }
                }
            }
            straddressrowidlst.add(minidadd.toString());
            postaddsetget = new Address(sprlistaddtype,street,city,state,zip,country,pobox,postaladdedtitm);
            addarylst.add(postaddsetget);
        }
        contatsetget.setAddresses(addarylst);

        // =================== End Code for Getting Postal Address details  =======================

        // =================== Start Code for Getting Organization details  =======================

        orgsetget = new Organization();
        orgarylst = new ArrayList<Organization>();
        sprListorg = new ArrayList<String>();
        strorgrowidlst = new ArrayList<String>();

        for (int i = 0; i < linearorg.getChildCount(); i++) {
            minusidorg = i;
            View veiwlayoutorg = linearorg.getChildAt(i);

            if (veiwlayoutorg instanceof RelativeLayout) {

                int mchildd = ((RelativeLayout) veiwlayoutorg).getChildCount();
                for (int x = 0; x < mchildd; x++) {
                    View subvieworg = ((RelativeLayout) veiwlayoutorg)
                            .getChildAt(x);

                    if (subvieworg instanceof Spinner) {
                        sprlistorgtype = ((Spinner) subvieworg)
                                .getSelectedItem().toString();
                        sprListorg.add(sprlistorgtype);
                    }

                    if (subvieworg instanceof EditText) {
                        orgedtaddedtitm = ((EditText) subvieworg).getText()
                                .toString();
                        System.out.println("subvieworg.getId()......"
                                + subvieworg.getId());

                        if (subvieworg.getId() == 100) {
                            orgname = orgedtaddedtitm;
                            //editTextOrgname.add(orgedtaddedtitm);
                        }
                        if (subvieworg.getId() == 101) {
                            orgtitle = orgedtaddedtitm;
                        //    editTextListOrgtitle.add(orgedtaddedtitm);
                        }
                    }
                }
            }
            strorgrowidlst.add(minusidorg.toString());
            orgsetget = new Organization(sprlistorgtype,orgname,orgtitle);
            orgarylst.add(orgsetget);
        }
        contatsetget.setOrganizations(orgarylst);

        // =================== End Code for Getting Organization details  =======================
       
        // =================== Start Code for Getting IM details  =======================
       
        imsetget = new Im();
        imarylst = new ArrayList<Im>();
        editTextIM = new ArrayList<String>();
        sprListim = new ArrayList<String>();
        strimrowidlst = new ArrayList<String>();
       
        for (int i = 0; i < linearim.getChildCount(); i++) {
            minusidim = i;
            View veiwlayoutim = linearim.getChildAt(i);

            if (veiwlayoutim instanceof RelativeLayout) {

                int mchildd = ((RelativeLayout) veiwlayoutim).getChildCount();
                for (int x = 0; x < mchildd; x++) {
                    View subviewim = ((RelativeLayout) veiwlayoutim)
                            .getChildAt(x);

                    if (subviewim instanceof Spinner) {
                        sprlistIMtype = ((Spinner) subviewim)
                                .getSelectedItem().toString();
                        sprListim.add(sprlistIMtype);
                    }

                    if (subviewim instanceof EditText) {
                        imedtaddedtitm = ((EditText) subviewim).getText()
                                .toString();
                        System.out.println("subvieworg.getId()......"+ subviewim.getId());

                        if (subviewim.getId() == 100) {
                            editTextIM.add(imedtaddedtitm);
                        }
                    }
                }
            }
            strimrowidlst.add(minusidim.toString());
            imsetget = new Im(sprlistIMtype, imedtaddedtitm);
            imarylst.add(imsetget);
        }
       
        contatsetget.setIms(imarylst);
       
        // =================== Start Code for Getting IM details  =======================
               
               
                // =================== Start Code for Getting Notes details  =======================
               
                note = new Note();
                strnote = edtnote.getText().toString();
                System.out.println("note...."+strnote);
                note.setText(strnote);
                note.setRowId("0");
                contatsetget.setNote(note);
               
                // =================== Start Code for Getting Notes details  =======================
               
               
                // =================== Start Code for Getting Nickname details  =======================
               
                strnickname = edtnickname.getText().toString();
                System.out.println("Nickname...."+strnickname);
               
                // =================== Start Code for Getting Nickname details  =======================
               
                // =================== Start Code for Getting Website details =======================

                // get Website type details
                editTextwebsite = new ArrayList<String>();
                strwebsiterowidlst = new ArrayList<String>();

                for (int i = 0; i < lineatwebsite.getChildCount(); i++) {
                    minsidwebsite = i;
                    View veiwlayoutwebsite = lineatwebsite.getChildAt(i);

                    if (veiwlayoutwebsite instanceof RelativeLayout) {

                        int mchildd = ((RelativeLayout) veiwlayoutwebsite).getChildCount();
                        for (int x = 0; x < mchildd; x++) {

                            View subviewwebsite = ((RelativeLayout) veiwlayoutwebsite).getChildAt(x);

                            if (subviewwebsite instanceof EditText) {
                                strwebsitename = ((EditText) subviewwebsite).getText().toString();
                                System.out.println("website........." + strwebsitename);
                                editTextwebsite.add(strwebsitename);
                            }
                        }
                    }
                    strwebsiterowidlst.add(minsidwebsite.toString());
                }
               
                // =================== End Code for Getting Website details =======================   
               
               
                // =================== Start Code for Getting Events details  =======================
               
                events = new Events();
                arylstevents = new ArrayList<Events>();
                editTextevents = new ArrayList<String>();
                sprListevents = new ArrayList<String>();
                streventsrowidlst = new ArrayList<String>();
               
                for (int i = 0; i < linearevents.getChildCount(); i++) {
                    minusidevents = i;
                    View veiwlayoutevents = linearevents.getChildAt(i);

                    if (veiwlayoutevents instanceof RelativeLayout) {

                        int mchildd = ((RelativeLayout) veiwlayoutevents).getChildCount();
                        for (int x = 0; x < mchildd; x++) {
                            View subviewevents = ((RelativeLayout) veiwlayoutevents)
                                    .getChildAt(x);

                            if (subviewevents instanceof Spinner) {
                                sprlistEventstype = ((Spinner) subviewevents)
                                        .getSelectedItem().toString();
                                sprListevents.add(sprlistEventstype);
                            }

                            if (subviewevents instanceof EditText) {
                                eventsedtaddedtitm = ((EditText) subviewevents).getText()
                                        .toString();
                                System.out.println("subviewevents.getId()......"+ subviewevents.getId());

                                if (subviewevents.getId() == 100) {
                                    editTextevents.add(eventsedtaddedtitm);
                                }
                            }
                        }
                    }
                    streventsrowidlst.add(minusidevents.toString());
                    events = new Events(sprlistEventstype,eventsedtaddedtitm);
                    arylstevents.add(events);
                }
               
                // =================== Start Code for Getting Events details  =======================
               
                if(phonarylst == null || phonarylst.isEmpty()){
                    Utility.showDialogwithTitle(mContext, "Please enter contact number");
                }else{
                        saveContact(contatsetget,contentResolver,"Om","General");   
                }
                       
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("UseValueOf")
    private static void saveContact(Contact contact,ContentResolver contentResolver, String accountName,String accountType) {
       
        try{
       
        operations = new ArrayList<ContentProviderOperation>();
         int rawContactInsertIndex = operations.size();
       
           operations.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName)
                    .build());
           operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, contact.getFirstName())
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, contact.getLastName())               
                    .build());
          
           if(!TextUtils.isEmpty(selectedImagePath)){
                Bitmap bitmapOrg = BitmapFactory.decodeFile(selectedImagePath);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmapOrg.compress(Bitmap.CompressFormat.JPEG , 100, stream);
               
                  operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, stream.toByteArray())
                            .build());
                  
         }
           if(contact.getNote() != null){
               Log.i(tag, "note ..."+contact.getNote().getText());
               operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                       .withValue(ContactsContract.Data.MIMETYPE,
                               ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
                       .withValue(ContactsContract.CommonDataKinds.Note.NOTE, contact.getNote().getText())                               
                       .build());
           }
          
           if(!TextUtils.isEmpty(strnickname)){
               Log.i(tag, "nicak nam...."+strnickname);
               operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                       .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
                       .withValue(ContactsContract.CommonDataKinds.Nickname.NAME,strnickname)                               
                       .build());
           }
          
           //strwebsite = edtwebsite.getText().toString();
           if(editTextwebsite != null){
           for(int w=0;w<editTextwebsite.size();w++){
               strwebsitename = editTextwebsite.get(w);
               Log.i(tag, "website name...."+editTextwebsite.get(w));
          // if(!TextUtils.isEmpty(strwebsite)){
               if(editTextwebsite.get(w).equalsIgnoreCase("0")){
                   myemailtype = 1;
               }else if(editTextwebsite.get(w).equalsIgnoreCase("1")){
                   myemailtype = 2;
               }else if(editTextwebsite.get(w).equalsIgnoreCase("2")){
                   myemailtype = 3;
               }else if(editTextwebsite.get(w).equalsIgnoreCase("3")){
                   myemailtype = 4;
               }else if(editTextwebsite.get(w).equalsIgnoreCase("4")){
                   myemailtype = 5;
               }else if(editTextwebsite.get(w).equalsIgnoreCase("5")){
                   myemailtype = 6;
               }else if(editTextwebsite.get(w).equalsIgnoreCase("6")){
                   myemailtype = 7;
               }else {
                   myemailtype = 7;
               }
              
               operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,   rawContactInsertIndex)
                       .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
                       .withValue(ContactsContract.CommonDataKinds.Website.URL, strwebsitename) 
                       .withValue(ContactsContract.CommonDataKinds.Website.TYPE, myemailtype)
                       .build());
           }
           }
          
           if(arylstevents != null){
               for(int e=0;e<arylstevents.size();e++){
                   events = arylstevents.get(e);
                   dateevent = Utility.convertDate(events.getDate(), "MM/dd/yyyy", "dd MMMM yyyy");
                   Log.i(tag, "start date of dateevent...."+dateevent);
                   if(events.getType() == "Anniversary"){
                       myemailtype = 1;
                   }if(events.getType() == "Other"){
                       myemailtype = 2;
                   }if(events.getType() == "Birthday"){
                       myemailtype = 3;
                   }
                   Log.i(tag, "start date type myemailtype...."+myemailtype);
                   operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                           .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,rawContactInsertIndex)
                           .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)
                           .withValue(ContactsContract.CommonDataKinds.Event.TYPE,myemailtype) 
                           .withValue(ContactsContract.CommonDataKinds.Event.START_DATE,"25 June 2013")
                           .build());
               }
           }
               //ArrayList<Address> addresses = contact.getAddresses();
            for(int a=0;a<addarylst.size();a++){
                postaddsetget = addarylst.get(a);
               
                if(postaddsetget.getType() == "Home"){
                    myemailtype = 1;
                }if(postaddsetget.getType() == "Work"){
                    myemailtype = 2;
                }if(postaddsetget.getType() == "Other"){
                    myemailtype = 3;
                }if(postaddsetget.getType() == "Other Mobile"){
                    myemailtype = 4;
                }
                //for(Address address:addresses){
                    operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE,myemailtype)
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,postaddsetget.getStreet())
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,postaddsetget.getCity())
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION,postaddsetget.getState())
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POBOX,postaddsetget.getPoBox())
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,postaddsetget.getZip())
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,postaddsetget.getCountry())
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD,postaddsetget.getNeighborhood())
                            .build());
            }
           
                for(int o=0;o<orgarylst.size();o++){
                    orgsetget = orgarylst.get(o);
                    if(orgsetget.getType() == "Home"){
                        myemailtype = 1;
                    }if(orgsetget.getType() == "Work"){
                        myemailtype = 2;
                    }if(orgsetget.getType() == "Other"){
                        myemailtype = 3;
                    }if(orgsetget.getType() == "Other Mobile"){
                        myemailtype = 4;
                    }
                   
                    operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, myemailtype)
                            .withValue(ContactsContract.CommonDataKinds.Organization.DATA, orgsetget.getName())
                            .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, orgsetget.getTitle())
                            .build());
                }
           
                for(int i=0;i<imarylst.size();i++){
                    imsetget = imarylst.get(i);
                   
                    if(imsetget.getProtocol() == "AIM"){
                        myemailtype = 1;
                    }if(imsetget.getProtocol() == "Windows Live"){
                        myemailtype = 2;
                    }if(imsetget.getProtocol() == "Yahoo"){
                        myemailtype = 3;
                    }if(imsetget.getProtocol() == "Skype"){
                        myemailtype = 4;
                    }if(imsetget.getProtocol() == "QQ"){
                        myemailtype = 5;
                    }if(imsetget.getProtocol() == "Google Talk"){
                        myemailtype = 6;
                    }if(imsetget.getProtocol() == "ICQ"){
                        myemailtype = 7;
                    }if(imsetget.getProtocol() == "Jabber"){
                        myemailtype = 8;
                    }
                   
                   
                    operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.Im.PROTOCOL,myemailtype)
                            .withValue(ContactsContract.CommonDataKinds.Im.DATA,imsetget.getValue())
                            .build());
                }
          
           ArrayList<Email> emails = contatsetget.getEmails();
            if(emails != null){
            for(Email email : emails){
                if(email.getType() == "Home"){
                        myemailtype = 1;
                    }if(email.getType() == "Work"){
                        myemailtype = 2;
                    }if(email.getType() == "Other"){
                        myemailtype = 3;
                    }if(email.getType() == "Other Mobile"){
                        myemailtype = 4;
                    }
                    Log.i(tag, "get email type....."+myemailtype);
                    Log.i(tag, "get email value....."+email.getValue());
                    operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.Email.TYPE,myemailtype)
                            .withValue(ContactsContract.CommonDataKinds.Email.DATA,email.getValue())
                            .build());
                }
            }
          
            for(int k=0;k<phonarylst.size();k++){
                phonesetget = phonarylst.get(k);
                Log.i(tag, "phone no..."+ phonesetget.getNo());
                Log.i(tag, "phone type..."+ phonesetget.getType());
                if(phonesetget.getType() == "Home"){
                    mytype = 1;
                }if(phonesetget.getType() == "Mobile"){
                    mytype = 2;
                }if(phonesetget.getType() == "Work"){
                    mytype = 3;
                }if(phonesetget.getType() == "Work Fax"){
                    mytype = 4;
                }if(phonesetget.getType() == "Home Fax"){
                    mytype = 5;
                }if(phonesetget.getType() == "Pager"){
                    mytype = 6;
                }if(phonesetget.getType() == "Other"){
                    mytype = 7;
                }if(phonesetget.getType() == "Callback"){
                    mytype = 8;
                }if(phonesetget.getType() == "Car"){
                    mytype = 9;
                }if(phonesetget.getType() == "Company Main"){
                    mytype = 10;
                }if(phonesetget.getType() == "ISDN"){
                    mytype = 11;
                }if(phonesetget.getType() == "Main"){
                    mytype = 12;
                }if(phonesetget.getType() == "Other Fax"){
                    mytype = 13;
                }if(phonesetget.getType() == "Radio"){
                    mytype = 14;
                }if(phonesetget.getType() == "Telex"){
                    mytype = 15;
                }if(phonesetget.getType() == "TTY/TDD"){
                    mytype = 16;
                }if(phonesetget.getType() == "Work Mobile"){
                    mytype = 17;
                }if(phonesetget.getType() == "Work Pager"){
                    mytype = 18;
                }if(phonesetget.getType() == "Assistant"){
                    mytype = 19;
                }if(phonesetget.getType() == "MMS"){
                    mytype = 20;
                }
               
                  operations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                            .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,phonesetget.getNo())
                            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, mytype)
                            .build());
            }
           
           
        try {
            contentResolver.applyBatch(ContactsContract.AUTHORITY, operations);

            Log.i(tag, "inserted contact number is..."+phonesetget.getNo().toString());
            final Integer mycontid = getContactIDFromNumber(phonesetget.getNo().toString(),mContext);
            Log.i(tag, "inserted contact is..."+mycontid);
           
            //Utility.mycheckcontlst.add(mycontid.toString());
           
             SQDataSourceContcts sqdatasource = new SQDataSourceContcts(mContext);
             sqdatasource.open();
           
             SQDataChecked sqcheck = new SQDataChecked(mContext);
             sqcheck.opencheck();
           
            if(!TextUtils.isEmpty(selectedImagePath)){
                Cursor cursor_photo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + mycontid, null, null);
                   while (cursor_photo.moveToNext()) {
                       photoid = cursor_photo.getString(cursor_photo.getColumnIndex(Contacts.PHOTO_ID));
                       
                        if(photoid != null){
                            sqdatasource.createcontsetget(mycontid.toString(),strfamilyname,phonesetget.getNo().toString(),photoid);   
                            sqcheck.createcontsetgetcheck(mycontid.toString(),strfamilyname,phonesetget.getNo().toString(),photoid);
                        }
                   }
                   Log.i(tag, "photoId......"+photoid);
                   System.out.println("photoId..."+photoid);
            }else{
                sqdatasource.createcontsetget(mycontid.toString(),strfamilyname,phonesetget.getNo().toString(),"00");
                sqcheck.createcontsetgetcheck(mycontid.toString(),strfamilyname,phonesetget.getNo().toString(),"00");
            }
            sqdatasource.close();
            sqcheck.close();
       
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
            alertDialogBuilder
                .setMessage("Contact added successfully")
                .setCancelable(false)
                .setPositiveButton("Ok",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                       
                        selectedImagePath = "";
                        Intent iadd = new Intent(mContext,ImportContacts.class);
                        iadd.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        iadd.putExtra("addcontid", mycontid.toString());
                        ((Activity) mContext).setResult(RESULT_OK,iadd);    
                        ((Activity) mContext).finish();
                       
                    }
                  });
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
           
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static int getContactIDFromNumber(String contactNumber,Context context)
    {
        contactNumber = Uri.encode(contactNumber);
        int phoneContactID = new Random().nextInt();
        Cursor contactLookupCursor = context.getContentResolver().query(Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,contactNumber),new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID}, null, null, null);
            while(contactLookupCursor.moveToNext()){
                phoneContactID = contactLookupCursor.getInt(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
                }
            contactLookupCursor.close();

        return phoneContactID;
    }
   
    public void revertContactClick(View v) {
       
        Intent iback = new Intent(AddCont.this, ImportContacts.class);
        iback.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(iback);
    }

    public void addContactimageClick(View v) {
        PopupMenu();
    }

    public void PopupMenu() {
        View popUpView = getLayoutInflater().inflate(
                R.layout.photouploaddialog1, null); // inflating popup layout
        mpopup = new PopupWindow(popUpView, LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT, true); // Creation of popup
        mpopup.setAnimationStyle(R.style.DialogAnimation);
        mpopup.showAtLocation(popUpView, Gravity.BOTTOM, 0, 0); // Displaying

        Button btnOk = (Button) popUpView.findViewById(R.id.btn_take_photo);
        btnOk.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mpopup.dismiss();
               
                PackageManager pm = getPackageManager();
                if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
                    File mFile = new File(Environment.getExternalStorageDirectory() + "/GetContact_images");
                    if(!mFile.exists()) {
                        mFile.mkdirs();
                    }
                    mFile = new File(mFile.getAbsolutePath() + "/temp.jpg");
                    Intent i = new Intent(
                            android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
                    startActivityForResult(i, CAMERA_RESULT);

                } else {
                    Utility.showDialogwithTitle(mContext, "Camera is not available");
                }
            }
        });

        Button btnchooselibrary = (Button) popUpView
                .findViewById(R.id.btn_choose_from_library);
        btnchooselibrary.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                try {
                    Intent i = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(i, RESULT_LOAD_IMAGE);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });

        Button btnCancel = (Button) popUpView.findViewById(R.id.photo_cancel);
        btnCancel.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mpopup.dismiss();
            }
        });
    }

   
    private void loadAndDisplayImage(File mFile) {
        new AsyncTask<File, Void, Bitmap>() {
            byte[] bitmapdata;
            ProgressDialog pbr;

            protected void onPreExecute() {
                System.gc();
                pbr = new ProgressDialog(AddCont.this);
                pbr.setMessage("Loading...");
                pbr.show();
            };

            @Override
            protected Bitmap doInBackground(File... params) {
                Bitmap mBitmap = Utility.decodeFile(params[0], 256);

                if(mBitmap != null) {
                    try {
                        Bitmap result = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
                        Canvas c = new Canvas(result);
                        c.drawBitmap(mBitmap, 0f, 0f, null);
                        c.drawBitmap(mBitmap, 0f, mBitmap.getHeight()-(mBitmap.getHeight()/6), null);
                       
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        result.compress(Bitmap.CompressFormat.JPEG, 90, stream);
                        bitmapdata = stream.toByteArray();

                        if (bitmapdata != null) {
                            MyWrite(bitmapdata);
                        }
                        mBitmap.recycle();
                        mBitmap = null;
                        System.gc();
                        return result;
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                }
                return null;
            }

            @SuppressLint("NewApi")
            protected void onPostExecute(Bitmap result) {
                if (result != null) {
                    if(pbr != null && pbr.isShowing()) {
                        pbr.dismiss();
                    }
                    //imguser.setScaleType(ScaleType.FIT_XY);
                    imguser.setImageBitmap(result);
                    mpopup.dismiss();
                }
            };
        }.execute(mFile);
    }

   
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            final Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver()
                    .query(selectedImage, filePathColumn, null,
                            null, null);
            cursor.moveToFirst();
            int columnIndex = cursor
                    .getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            //strimagepath = picturePath;
            File f = new File(picturePath);
            selectedImagePath = f.getAbsolutePath();
            loadAndDisplayImage(f);
        }

        if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
           
            final File mFile = new File(Environment.getExternalStorageDirectory() + "/GetContact_images/temp.jpg");
            if(!mFile.exists()) {
                Utility.showDialogwithTitle(mContext,"Image not captured successfully");
                return;
            }
            selectedImagePath = mFile.getAbsolutePath();
            loadAndDisplayImage(mFile);
        }
    }
   

    public void MyWrite(byte[] buffer) {
        System.gc();
        File sdCard = Environment.getExternalStorageDirectory();
        File directory = new File(sdCard.getAbsolutePath() + "/Getcontactimage");
        directory.mkdirs();
        // Now create the file in the above directory and write the contents
        // into it
        System.out.println("Image path=" +selectedImagePath);
        File file;
        file = new File(directory, currentDateandTime);

        // File file = new File(directory, "sample.jpg");
        selectedImagePath = file.getAbsolutePath();
        System.out.println("Path=" + selectedImagePath);
       
        try {
            if(!file.exists())
            file.createNewFile();
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
       
       
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(file);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        BufferedOutputStream osw = new BufferedOutputStream(fOut);
        try {
            // osw.write(path);
            osw.write(buffer);
            // osw.write(buffer, offset, length);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            osw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            osw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

   
    public void getContactGrouplist() {

        try {
            mygrouplist = new ArrayList<String>();

            ContentResolver cr = getContentResolver();
            Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, null,
                    null, null, null);
            final String[] GROUP_PROJECTION = new String[] {
                    ContactsContract.Groups._ID, ContactsContract.Groups.TITLE };
            cursor = getContentResolver().query(
                    ContactsContract.Groups.CONTENT_URI, GROUP_PROJECTION,
                    null, null, ContactsContract.Groups.TITLE);

            while (cursor.moveToNext()) {

                String gId = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.Groups._ID));

                String gTitle = (cursor.getString(cursor
                        .getColumnIndex(ContactsContract.Groups.TITLE)));

                if(mygrouplist.contains(gTitle)){
                    mygrouplist.remove(gTitle);   
                }else{
                    mygrouplist.add(gTitle);   
                }
                Log.i(tag, "grp name is...." + gTitle);
                Log.i(tag, "grp id is...." + gId);
                Log.i(tag, "mygrouplist is...." + mygrouplist);
               
            }
           
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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...