Thursday 8 August 2013

Display Image with adding Overlay

write below code in your xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/splashscreenbg"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollingmain"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/include1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" >

        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dip" >

            <TableRow
                android:id="@+id/angletakephoto"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="1dip"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:clickable="true"
                android:gravity="center"
                android:paddingTop="20dp" >

                <Button
                    android:id="@+id/buttonphoto"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_weight="1"
                    android:background="@drawable/savebtnselector"
                    android:onClick="takePhotoClick"
                   android:layout_gravity="center_vertical"
                    android:text="@string/btnphoto"
                    android:textColor="#ffffff" />

                <TextView
                    android:id="@+id/Text"
                    android:layout_width="15dp"
                    android:layout_height="wrap_content" />

                <Button
                    android:id="@+id/buttonphotofromlibrary"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:layout_weight="1"
                    android:background="@drawable/savebtnselector"
                    android:onClick="takePhotofromLibraryClick"
                     android:layout_gravity="center_vertical"
                    android:text="@string/btnphotofromlib"
                    android:textColor="#ffffff" />
            </TableRow>

            <TableRow
                android:id="@+id/anglephoto"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="1dip"
                android:layout_marginTop="10dp"
                android:clickable="true"
                android:gravity="center" >

                <FrameLayout
                    android:layout_width="match_parent"
                    android:layout_height="fill_parent"
                    android:layout_marginBottom="5dp"
                    android:layout_gravity="center_horizontal">

                    <ImageView
                        android:id="@+id/imageViewphoto"
                        android:layout_width="290dp"
                        android:layout_height="300dp"
                        android:adjustViewBounds="true"
                        android:layout_gravity="center"
                        android:src="@drawable/defaultprofileimg" />

                </FrameLayout>
            </TableRow>
        </TableLayout>
    </ScrollView>

</RelativeLayout>



in your main Activity 

public void takePhotoClick(View view) {
        PackageManager pm = getPackageManager();
        if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            File mFile = new File(Environment.getExternalStorageDirectory() + "/My_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 {
            Toast.makeText(getBaseContext(), "Camera is not available",
                    Toast.LENGTH_LONG).show();
        }

    }

    public void takePhotofromLibraryClick(View view) {
        Intent i = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_IMAGE);

    }


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

            protected void onPreExecute() {
                System.gc();
                pbr = new ProgressDialog(SaveAngle.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);
                        Bitmap withstring = getThumb("name", "title", mBitmap.getWidth() + 50, mBitmap.getHeight()/6);
                        Canvas c = new Canvas(result);
                        c.drawBitmap(mBitmap, 0f, 0f, null);
                        c.drawBitmap(withstring, 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;
            }

            protected void onPostExecute(Bitmap result) {
                if (result != null) {
                    if(pbr != null && pbr.isShowing()) {
                        pbr.dismiss();
                    }
                    imguser.setScaleType(ScaleType.CENTER_INSIDE);
                    imguser.setImageBitmap(result);
                }
            };
        }.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);
            strimagepath = f.getAbsolutePath();
            loadAndDisplayImage(f);
        }

        if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
           
            final File mFile = new File(Environment.getExternalStorageDirectory() + "/My_images/temp.jpg");
            if(!mFile.exists()) {
                Toast.makeText(getBaseContext(), "Image not captured successfully.", Toast.LENGTH_SHORT).show();
                return;
            }
            strimagepath = mFile.getAbsolutePath();
            loadAndDisplayImage(mFile);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        imguser = null;
    }



    @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);
            strimagepath = f.getAbsolutePath();
            loadAndDisplayImage(f);
        }

        if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
           
            final File mFile = new File(Environment.getExternalStorageDirectory() + "/My_images/temp.jpg");
            if(!mFile.exists()) {
                Toast.makeText(getBaseContext(), "Image not captured successfully.", Toast.LENGTH_SHORT).show();
                return;
            }
            strimagepath = mFile.getAbsolutePath();
            loadAndDisplayImage(mFile);
        }
    }




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

        // File file = new File(directory, "sample.jpg");
        strimagepath = file.getAbsolutePath();
        System.out.println("Path=" + strimagepath);
       
        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();
        }
    }



private Bitmap getThumb(String strangle, String strnote, int width, int height) {

        //Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.transperet_bg);
        Bitmap bmOverlay = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bmOverlay);
        Paint paint = new Paint();

        paint.setColor(Color.WHITE);
        paint.setTextSize(20);
        paint.setFlags(Paint.ANTI_ALIAS_FLAG);
        // if the background image is defined in main.xml, omit this line
        canvas.drawARGB(140, 0, 0, 0);
        //canvas.drawBitmap(mBitmap, 0, 0, null);
        // draw the text and the point
        paint.setTextAlign(Paint.Align.LEFT);
       
        canvas.drawText("Name", 10, 20, paint);
       
        strnote = edtnote.getText().toString();
        if (TextUtils.isEmpty(strnote)) {
            strnote = "Note";
        }
        canvas.drawText(strnote, 10, 50, paint);
        paint.setTextAlign(Paint.Align.RIGHT);
       
        canvas.drawText("name", width-60, 50, paint);
        canvas.drawText("Application name", width-60, 20, paint);
       
        canvas.drawPoint(30.0f, height/2, paint);
        return bmOverlay;
    }




write decodeFile this function in your common class 

public static Bitmap decodeFile(File f, int size) {
         System.out.println("Decoding file");
            try {
                // decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(new FileInputStream(f), null, o);

                // Find the correct scale value. It should be the power of 2.
                //final int REQUIRED_SIZE = 70;
                //final int REQUIRED_SIZE = 300;
                int width_tmp = o.outWidth, height_tmp = o.outHeight;
                int scale = 1;
                while (true) {
                    if (width_tmp / 2 < size || height_tmp / 2 < size)
                        break;
                    width_tmp /= 2;
                    height_tmp /= 2;
                    scale *= 2;
                }

                // decode with inSampleSize
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
            } catch (FileNotFoundException e) {
                System.out.println("Error :: " + e.getMessage());
            }
            return null;
        }



Select Big size image from SDCard getting VM Budget Error ????

Select Big size image from SDCard or from Capture from Camera and display getting VM Budget Error so try below code

to select image from sdcard 

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

startActivityForResult(i, RESULT_LOAD_IMAGE);


Take picture from camera

PackageManager pm = getPackageManager();
        if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            File mFile = new File(Environment.getExternalStorageDirectory() + "/My_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 {
            Toast.makeText(getBaseContext(), "Camera is not available",
                    Toast.LENGTH_LONG).show();
        }



after get image in onActivityResult

@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]);
           String picturePath = cursor.getString(columnIndex);
            //strimagepath = picturePath;
            File f = new File(picturePath);
        String   strimagepath = f.getAbsolutePath();
            loadAndDisplayImage(f);
        }

        if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) {
          
            final File mFile = new File(Environment.getExternalStorageDirectory() + "/My_images/temp.jpg");
            if(!mFile.exists()) {
                Toast.makeText(getBaseContext(), "Image not captured successfully.", Toast.LENGTH_SHORT).show();
                return;
            }
        String  strimagepath = mFile.getAbsolutePath();
            loadAndDisplayImage(mFile);
        }
    }


new loadAndDisplayImage function here

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

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

            @Override
            protected Bitmap doInBackground(File... params) {
                Bitmap mBitmap = decodeFile(
params, 256);
                return null;
            }

            protected void onPostExecute(Bitmap result) {
                if (result != null) {
                    if(pbr != null && pbr.isShowing()) {
                        pbr.dismiss();
                    }
                    imguser.setScaleType(ScaleType.CENTER_INSIDE);
                    imguser.setImageBitmap(result);
                }
            };
        }.execute(mFile);
    }


decodeFile function is here

 public static Bitmap decodeFile(File f, int size) {
         System.out.println("Decoding file");
            try {
                // decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(new FileInputStream(f), null, o);

                // Find the correct scale value. It should be the power of 2.
                //final int REQUIRED_SIZE = 70;
                //final int REQUIRED_SIZE = 300;
                int width_tmp = o.outWidth, height_tmp = o.outHeight;
                int scale = 1;
                while (true) {
                    if (width_tmp / 2 < size || height_tmp / 2 < size)
                        break;
                    width_tmp /= 2;
                    height_tmp /= 2;
                    scale *= 2;
                }

                // decode with inSampleSize
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
            } catch (FileNotFoundException e) {
                System.out.println("Error :: " + e.getMessage());
            }
            return null;
        }

Use SharedPrefrence from Common Class

public static void setSharedKey(String key, String value, Context context) {
        SharedPreferences spre = context.getSharedPreferences(
                context.getPackageName(), Context.MODE_PRIVATE);
        SharedPreferences.Editor prefEditor = spre.edit();
        prefEditor.putString(key, value);
        //prefEditor.clear();
        prefEditor.commit();
    }

    public static String getSharedKey(String key, Context context) {
        SharedPreferences spre = context.getSharedPreferences(
                context.getPackageName(), Context.MODE_PRIVATE);
        return spre.getString(key, "");
    }



Declare this above two method in your common class 

to set shared preference

Utility.setSharedKey("key", "value", mContext);

to get shared preference

String mypref = Utility.getSharedKey("key", MainActivity.this);

 

Convert date from date to any date

Convert date from date to any date using below function

public static String convertDate(String date, String fromFormat,
            String toFormat)
    {
        String formattedDate = "";
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fromFormat);
            Date d = simpleDateFormat.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(d);
            simpleDateFormat = new SimpleDateFormat(toFormat);
            simpleDateFormat.setCalendar(calendar);
            formattedDate = simpleDateFormat.format(calendar.getTime());

        } catch (Exception e) {
            if (e != null)
                e.printStackTrace();
        }
        return formattedDate;
    }


now you can use this function like below

//for example :-mydate = 12/01/2000

String mydate =  convertDate("mydate", "MM/dd/yyyy", "dd MMMM yyyy");

Get all contact details from contact id

//globly declaration above oncreate method

static ArrayList<Address> addresarylst; static ArrayList<Email> emailarylst;  
static ArrayList<Im> imarylst;
static ArrayList<Organization> orgarylst;
static ArrayList<Phone> phonearylst;


Method to get Name,Number and photoid from contact is

public String getNumber(String contid){
       Cursor cursor_phone = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + contid, null, null);
       while (cursor_phone.moveToNext()) {
         String  cont_phone = cursor_phone.getString(cursor_phone.getColumnIndex(Phone.NUMBER));
       } System.out.println("cont_phone"+cont_phone);
    return cont_phone;
   }
   
   public String getName(String contid){
       Cursor cursor_name = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + contid, null, null);
       while (cursor_name.moveToNext()) {
          String cont_name = cursor_name.getString(cursor_name.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
       } System.out.println("cont_name..."+cont_name);
    return cont_name;
   }
  
   public String getPhoto(String contid){
       Cursor cursor_photo = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + contid, null, null);
       while (cursor_photo.moveToNext()) {
         String  photoId = cursor_photo.getString(cursor_photo.getColumnIndex(Contacts.PHOTO_ID));
       } System.out.println("photoId..."+photoId);
    return photoId;
   }


Method to Get Email Id from contact id

private static ArrayList<Email> getEmails(String id,
            ContentResolver contentResolver) {
        Cursor emailCursor = contentResolver.query(
                ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Email.CONTACT_ID + QUESTION,
                new String[] { id }, null);
        while (emailCursor.moveToNext()) {
            String value = emailCursor
                    .getString(emailCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            int type = emailCursor
                    .getInt(emailCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
            String rowId = emailCursor
                    .getString(emailCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Email._ID));
            if (ContactsContract.CommonDataKinds.Email.TYPE_HOME == type
                    || ContactsContract.CommonDataKinds.Email.TYPE_WORK == type
                    || ContactsContract.CommonDataKinds.Email.TYPE_OTHER == type) {


            
Email emailsetget = new Email();
                emailsetget.setValue(value);
                emailsetget.setRowId(rowId);
                emailsetget.setType(String.valueOf(type));
                emailarylst.add(emailsetget);
            }
        }
        contmainsetget.setEmails(emailarylst);
        emailCursor.close();
        return emailarylst;
    }



here Email is your getter setter class as i define below

public class Email {
    private String type = null;
    private String value = null;
    private String rowId = null;
    public Email() {
        super();
    }
   
    public Email(String type,String value) {
        super();
        //this.rowId = rowid;
        this.value = value;
        this.type = type;
    }
   
    public String getRowId() {
        return rowId;
    }
    public void setRowId(String rowId) {
        this.rowId = rowId;
    }
   
    public String getValue() {
        return ContactUtility.replaceNull(value);
    }
    public String getType() {
        return ContactUtility.replaceNull(type);
    }
    public void setType(String type) {
        this.type = type;
    }
    public void setValue(String value) {
        this.value = value;
    }

} 

Method to get address from contact id



    private static ArrayList<Address> getAddresses(String id,
            ContentResolver contentResolver) {
       
        Cursor addressCursor = contentResolver
                .query(ContactsContract.Data.CONTENT_URI,
                        null,
                        ContactsContract.Data.CONTACT_ID + QUESTION_AND
                                + ContactsContract.Data.MIMETYPE + QUESTION,
                        new String[] {
                                id,
                                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE },
                        null);
        while (addressCursor.moveToNext()) {
            int type = addressCursor
                    .getInt(addressCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
            if (ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME == type
                    || ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK == type
                    || ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER == type) {
                String street = addressCursor
                        .getString(addressCursor
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
                String city = addressCursor
                        .getString(addressCursor
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
                String state = addressCursor
                        .getString(addressCursor
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
                String poBox = addressCursor
                        .getString(addressCursor
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
                String zip = addressCursor
                        .getString(addressCursor
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
                String country = addressCursor
                        .getString(addressCursor
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
                String rowId = addressCursor
                        .getString(addressCursor
                                .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal._ID));

              
Address addsetget = new Address();
                addsetget.setCity(city);
                addsetget.setCountry(country);
                addsetget.setPoBox(poBox);
                addsetget.setState(state);
                addsetget.setType(String.valueOf(type));
                addsetget.setZip(zip);
                addsetget.setStreet(street);
                addsetget.setRowId(rowId);
                addresarylst.add(addsetget);
            }
        }
        addressCursor.close();
        return addresarylst;
    }


here Address is your getter setter class ,which i define below

public class Address {
    private String type = null;
    private String street = null;
    private String city = null;
    private String state = null;
    private String zip = null;
    private String country = null;
    private String rowId = null;
    private String poBox;
    private String neighborhood;

    public Address() {
        super();
    }

    public Address(String type,String street,String city,String state,String zip,String country,String pobox,String negieobrhood){
        super();
        //this.rowId = rowid;
        this.type = type;
        this.street = street;
        this.city = city;
        this.state = state;
        this.zip = zip;
        this.country = country;
        this.poBox = pobox;
        this.neighborhood = negieobrhood;
    }
   
    public String getRowId() {
        return rowId;
    }
    public void setRowId(String rowId) {
        this.rowId = rowId;
    }
    public String getType() {
        return ContactUtility.replaceNull(type);
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getStreet() {
        return ContactUtility.replaceNull(street);
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public String getCity() {
        return ContactUtility.replaceNull(city);
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getState() {
        return ContactUtility.replaceNull(state);
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getZip() {
        return ContactUtility.replaceNull(zip);
    }
    public void setZip(String zip) {
        this.zip = zip;
    }
    public String getCountry() {
        return ContactUtility.replaceNull(country);
    }
    public void setCountry(String country) {
        this.country = country;
    }
    public String getPoBox() {
        return ContactUtility.replaceNull(poBox);
    }
    public void setPoBox(String poBox) {
        this.poBox = poBox;
    }

    public String getNeighborhood() {
        return neighborhood;
    }

    public void setNeighborhood(String neighborhood) {
        this.neighborhood = neighborhood;
    }
}


Method to get IM details from contact is

private static ArrayList<Im> getIms(String id,
            ContentResolver contentResolver) {
        //ArrayList<Im> IMs = new ArrayList<Im>();
        Cursor imCursor = contentResolver
                .query(ContactsContract.Data.CONTENT_URI,
                        null,
                        ContactsContract.Data.CONTACT_ID + QUESTION_AND
                                + ContactsContract.Data.MIMETYPE + QUESTION,
                        new String[] {
                                id,
                                ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE },
                        null);
        while (imCursor.moveToNext()) {
            String value = imCursor.getString(imCursor
                    .getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
            String protocol = imCursor
                    .getString(imCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL));
            String rowId = imCursor.getString(imCursor
                    .getColumnIndex(ContactsContract.CommonDataKinds.Im._ID));
         
Im  imsetget = new Im();
            imsetget.setProtocol(protocol);
            imsetget.setValue(value);
            imsetget.setRowId(rowId);
            imarylst.add(imsetget);
        }
        imCursor.close();
        return imarylst;
    }


here Im is your getter setter class ,as i define below 

public class Im {
    private String protocol = null;
    private String rowId = null;
    private String value = null;
   

    public Im() {
        super();
    }
   
    public Im(String type,String value) {
        super();
        this.protocol = type;
        this.value = value;
    }
   
    public String getRowId() {
        return rowId;
    }
    public void setRowId(String rowId) {
        this.rowId = rowId;
    }
    public String getProtocol() {
        return ContactUtility.replaceNull(protocol);
    }
    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }
    public String getValue() {
        return ContactUtility.replaceNull(value);
    }
    public void setValue(String value) {
        this.value = value;
    }

}



Method to get Organization detail from contact is
 

    private static ArrayList<Organization> getOrganizations(String id,
            ContentResolver contentResolver) {
        Cursor organizationCursor = contentResolver
                .query(ContactsContract.Data.CONTENT_URI,
                        null,
                        ContactsContract.Data.CONTACT_ID + QUESTION_AND
                                + ContactsContract.Data.MIMETYPE + QUESTION,
                        new String[] {
                                id,
                                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE },
                        null);

        while (organizationCursor.moveToNext()) {
            String name = organizationCursor
                    .getString(organizationCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
            String title = organizationCursor
                    .getString(organizationCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
            String rowId = organizationCursor
                    .getString(organizationCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Organization._ID));
            int type = organizationCursor
                    .getInt(organizationCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE));
            if (ContactsContract.CommonDataKinds.Organization.TYPE_WORK == type
                    || ContactsContract.CommonDataKinds.Organization.TYPE_OTHER == type) {
          
            
Organization   orgsetget = new Organization();
                orgsetget.setName(name);
                orgsetget.setTitle(title);
                orgsetget.setRowId(rowId);
                orgsetget.setType(String.valueOf(type));
                orgarylst.add(orgsetget);
            }
        }
        contmainsetget.setOrganizations(orgarylst);
        organizationCursor.close();
        return orgarylst;
    }


here Organization is your getter setter class as i define below

public class Organization {
    private String type = null;
    private String title = null;
    private String name = null;
    private String rowId = null;

    public Organization() {
        super();
    }
   
    public Organization(String type,String name,String title) {
        super();
        this.type = type;
        this.name = name;
        this.title = title;
    }

    public String getRowId() {
        return rowId;
    }
    public void setRowId(String rowId) {
        this.rowId = rowId;
    }
    public String getType() {
        return ContactUtility.replaceNull(type);
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getTitle() {
        return ContactUtility.replaceNull(title);
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getName() {
        return ContactUtility.replaceNull(name);
    }
    public void setName(String name) {
        this.name = name;
    }

}


Method to get Phone details form contact id

private static ArrayList<Phone> getPhones(String id,
            ContentResolver contentResolver) {
        Cursor phoneCursor = contentResolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + QUESTION,
                new String[] { id }, null);
        while (phoneCursor.moveToNext()) {
            String no = phoneCursor
                    .getString(phoneCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            String rowId = phoneCursor
                    .getString(phoneCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
            int type = phoneCursor
                    .getInt(phoneCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
            if (ContactsContract.CommonDataKinds.Phone.TYPE_WORK == type
                    || ContactsContract.CommonDataKinds.Phone.TYPE_HOME == type
                    || ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE == type
                    || ContactsContract.CommonDataKinds.Phone.TYPE_OTHER == type) {
              
Phone phonesetget = new Phone();
           
                phonesetget.setNo(no);   
                phonesetget.setRowId(rowId);   
                phonesetget.setType(String.valueOf(type));
               
                    phonearylst.add(phonesetget);   
            }
        }
        phoneCursor.close();
        return phonearylst;
    }

here Phone is your getter setter class as i define below

public class Phone {
    private String type = null;
    private String rowId = null;
    private String no = null;

    public Phone() {
        super();
    }

    public Phone(String type,String no){
        super();
        //this.rowId = rowid;
        this.type = type;
        this.no = no;
    }
   
    public String getRowId() {
        return rowId;
    }
    public void setRowId(String rowId) {
        this.rowId = rowId;
    }
    public String getType() {
        return ContactUtility.replaceNull(type);
    }
    public void setType(String type) {
        this.type = type;
    }
   
    public String getNo() {
        return ContactUtility.replaceNull(no);
    }
    public void setNo(String no) {
        this.no = no;
    }
}


Method to get FirstName LastName from contact id
 

 private static String[] getFirstNameLastName(String id,
            ContentResolver contentResolver) {
        String[] retValue = new String[2];
        retValue[0] = "";
        retValue[1] = "";

        Cursor nameCursor = contentResolver
                .query(ContactsContract.Data.CONTENT_URI,
                        null,
                        ContactsContract.Data.MIMETYPE + QUESTION_AND
                                + ContactsContract.RawContactsEntity.CONTACT_ID
                                + QUESTION,
                        new String[] {
                                ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,
                                id }, null);
        while (nameCursor.moveToNext()) {
            String given = nameCursor
                    .getString(nameCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
            String family = nameCursor
                    .getString(nameCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
            if (given != null) {
                retValue[0] = given;
            }
            if (family != null) {
                retValue[1] = family;
            }
        }
        nameCursor.close();
        return retValue;
    }


Method to get Note from contact id

@SuppressLint("NewApi")
    private static Note getNote(String id, ContentResolver contentResolver) {

        Cursor noteCursor = contentResolver
                .query(ContactsContract.Data.CONTENT_URI,
                        null,
                        ContactsContract.Data.CONTACT_ID + QUESTION_AND
                                + ContactsContract.Data.MIMETYPE + QUESTION,
                        new String[] {
                                id,
                                ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE },
                        null);
        if (noteCursor.moveToFirst()) {
            String value = noteCursor
                    .getString(noteCursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
            String rowId = noteCursor.getString(noteCursor
                    .getColumnIndex(ContactsContract.CommonDataKinds.Note._ID));
          
Note cont_note = new Note();
            cont_note.setRowId(rowId);
            Log.i(tag, "contact note value ...."+value);
            if(value.isEmpty()){
               
            }else{
                cont_note.setText(value);   
            }
        }
        noteCursor.close();

        return cont_note;
    }


here Note is your getter setter class as i define below

public class Note {
    private String rowId = null;
    private String text = null;

    public Note() {
        super();
    }
   
    public String getText() {
        return ContactUtility.replaceNull(text);
    }
    public void setText(String text) {
        this.text = text;
    }

    public String getRowId() {
        return rowId;
    }
    public void setRowId(String rowId) {
        this.rowId = rowId;
    }

}
 


Display Image from photoId

// contimg is your imageview 

if (photoId != null) {
              
                    Uri photoUri = ContentUris.withAppendedId(
                            ContactsContract.Data.CONTENT_URI,
                            Long.parseLong(photoId));
                    contimg.setImageURI(photoUri);
               
              
            } else {
               // set default image like define below //contimg.setImageResource(R.drawable.ic_contact_picture_holo_light);
            }

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