Tuesday, 26 April 2016

This is a common Utils class for used every where.

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface;
import android.hardware.Camera;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Patterns;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/** * This is a common class for used every where. * * @author Mayank * @since 1.4 */public class Utils {
    public static final String IS_SOCIAL_REGISTER = "Register";
    public static final String SOCIAL_IS_REGISTER_TYPE = "RegisterType";
    public static final String SOCIAL_PROVIDER = "SocialProvider";
    public static final String IS_SOCIAL_LOGIN = "SocialType";
    public static final String TAG = "URateIt";
    public static final String APP_PREFS = "app_prefs";
    public static final String APP_PREFS_NOTIFICATION_KEY = "app_prefs_notification";
    public static final String NOTIFICATION_KEY = "notification_key";
    public static final String ACCESS_KEY = "access_key";
    public static final String ACCESS_KEY_NOT_FOUND = "access_key_not_defined";
    public static final String USER_KEY = "user_key";
    public static final String USER_KEY_NOT_FOUND = "user_key_not_defined";
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    public static final String IMAGE_DIRECTORY_NAME = "URateIt";
    public static final int MEDIA_TYPE_AUDIO = 3;
    public static final String root = "/mnt/sdcard/Android/data";
    public static String PREFS_FILE_NAME = "URateItPref";
    public static ProgressDialog loadingDialogGlobal;
    public static Uri fileUri;
    static SharedPreferences prefs;
    private static File audioFolder;
    private static File videoFolder;
    private static File imageFolder;

    public static void setAPIAccessKey(String access_key, Context context) {
        SharedPreferences prefs;
        prefs = context.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(ACCESS_KEY, access_key);
        editor.commit();
    }

    /**     * check EditText is empty or not     *     * @param edText pass EditText for check is empty or not     * @return true or false     */    public static boolean isEmptyEditText(EditText edText) {
        if (edText.getText().toString().trim().length() > 0)
            return false;
        else            return true;
    }

    /**     * set custom fonts for custom text changes     *     * @param mContext     * @param mTextView     * @param font     */    public static void setCustomFontStyle(Context mContext, TextView mTextView, String font) {
        Typeface face = Typeface.createFromAsset(mContext.getAssets(), "fonts/" + font + ".ttf");
        mTextView.setTypeface(face);
    }

    public static void setTypeface(Context mContext, EditText mEditText) {
        Typeface face = Typeface.createFromAsset(mContext.getAssets(), "SEGOEUIL.ttf");
        mEditText.setTypeface(face);
    }

    public static void setTypeface(Context mContext, TextView mTextView) {
        Typeface face = Typeface.createFromAsset(mContext.getAssets(), "SEGOEUIL.ttf");
        mTextView.setTypeface(face);
    }

    public static void setTypeface(Context mContext, Button mbButton) {
        Typeface face = Typeface.createFromAsset(mContext.getAssets(), "SEGOEUIL.ttf");
        mbButton.setTypeface(face);
    }

    // -----------------------------------------------
    /**     * Get the access key from shared preferences     *     * @param context application context     * @return access key     */    public static String getAPIAccessKey(Context context) {
        SharedPreferences prefs;
        prefs = context.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
        return prefs.getString(ACCESS_KEY, ACCESS_KEY_NOT_FOUND);
//        return "58623a74e11d56d61a2ee098fe993d1754e5a5fc737b7";    }

    // -----------------------------------------------
    /**     * Set the user key on shared preferences     *     * @param context application context     */    public static void setUserAccessKey(String user_key, Context context) {
        SharedPreferences prefs;
        prefs = context.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(USER_KEY, user_key);
        editor.commit();
    }

    // -----------------------------------------------
    /**     * Get the user key from shared preferences     *     * @param context application context     * @return user key     */    public static String getUserAccessKey(Context context) {
        SharedPreferences prefs;
        prefs = context.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
        return prefs.getString(USER_KEY, USER_KEY_NOT_FOUND);

//        return "f0cec1614a73303267f22ce6050ee09954e5dcb8c0c7a";    }

    /**     * set String Preference Value     *     * @param context     * @param prefName Preference name     * @param Value    Preference value     */    public static void setPrefrencesString(Context context, String prefName, String Value) {
        prefs = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(prefName, Value);
        editor.commit();
    }

    /**     * get String Preference Value     *     * @param context     * @param prefName     * @return     */    public static String getPrefrencesString(Context context, String prefName) {
        prefs = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE);
        if (prefs.contains(prefName))
            return prefs.getString(prefName, "");
        else            return "";
    }

    /**     * set Integer Preference Value     *     * @param context     * @param prefName     * @param Value     */    public static void setPrefrencesInteger(Context context, String prefName, int Value) {
        prefs = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(prefName, Value);
        editor.commit();
    }

    /**     * get Integer Preference Value     *     * @param context     * @param prefName     * @return     */    public static int getPrefrencesInteger(Context context, String prefName) {
        prefs = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE);
        return prefs.getInt(prefName, 0);
    }

    /**     * remove all the preferences of your app. Note: only remove all which set     * by using this sdk.     *     * @param context     */    public static void clearAllPrefrencesData(Context context) {
        prefs = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.commit();
    }

    /**     * Network operations of HttpClient     *     * @param serverUrl     * @return     */    public static String NetworkOperation(String serverUrl) {
        String result = null;
        JSONObject jsonResult;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(serverUrl);
            HttpResponse response = client.execute(get);
            HttpEntity resp_entity = response.getEntity();
            result = EntityUtils.toString(resp_entity);

            if (response.getStatusLine().getStatusCode() != 200) {
                jsonResult = new JSONObject();
                jsonResult.put("response_code", "9999");
                jsonResult.put("response_message", "Server error occurred while processing request. Please try again.");
                result = jsonResult.toString();
                return result;
            }
        } catch (Exception e) {
            try {
                jsonResult = new JSONObject();
                jsonResult.put("response_code", "9999");
                jsonResult.put("response_message", "Server error occurred while processing request. Please try again.");
                result = jsonResult.toString();
                return result;
            } catch (JSONException jsone) {
            }
        }
        return result;
    }

    public static void setNotificationKey(String access_key, Context context) {
        SharedPreferences prefs;
        prefs = context.getSharedPreferences(APP_PREFS_NOTIFICATION_KEY, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(NOTIFICATION_KEY, access_key);
        editor.commit();
    }

    public static String getNotificationKey(Context context) {
        SharedPreferences prefs;
        prefs = context.getSharedPreferences(APP_PREFS_NOTIFICATION_KEY, Context.MODE_PRIVATE);
        return prefs.getString(NOTIFICATION_KEY, null);
    }

    /**     * Checks whether network (WIFI/mobile) is available or not.     *     * @param context application context.     * @return true if network available,false otherwise.     */    public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

    /**     * check the email address is valid or not.     *     * @param email pass email id in string     * @return true when its valid otherwise false     */    public static boolean isEmailIdValid(String email) {
        String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
        CharSequence inputStr = email;

        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);

        if (matcher.matches())
            return true;
        else            return false;
    }

    /**     * get unique id     *     * @param context     * @return     */    public static String getUniqueId(Context context) {
        String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return androidId;
    }

    /**     * get device id     *     * @param context     * @return     */    public static String getDeviceID(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }

    /**     * show no internet available dialog     *     * @param mContext     */    public static void ShowNoInternetDialog(final Context mContext) {
        new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT)
                .setMessage("No internet available.")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mContext.startActivity(new Intent(Settings.ACTION_SETTINGS));
                    }
                }).create().show();
    }


//    Sanjay Added methods for image and video capture or pick from gallery 18/2/2015
    /**     * for clear previous stored data     *     * @param context     */    public static void clearPreviousData(Context context) {
        Appconfig.SocialID = "";
        Appconfig.FullName = "";
        Appconfig.Email = "";
        Appconfig.AvatarImgURL = "";
    }

    /**     * for close the keyboard     *     * @param mContext     * @param v     */    public static void closeKeyboard(Context mContext, View v) {
        InputMethodManager inputManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void showGlobalLoading(Context mContext) {
        // TODO Auto-generated method stub        loadingDialogGlobal = new ProgressDialog(mContext, ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
        loadingDialogGlobal.requestWindowFeature(Window.FEATURE_NO_TITLE);
        loadingDialogGlobal.setMessage("Loading...");
        loadingDialogGlobal.setCancelable(false);
        loadingDialogGlobal.show();
    }

    /**     * Captures image in Common Directory     *     * @param mContext     * @param CAMERA_CAPTURE_IMAGE_REQUEST_CODE     * @param camera     */    public static void captureImage(Context mContext, int CAMERA_CAPTURE_IMAGE_REQUEST_CODE, String camera) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        if (camera.equalsIgnoreCase("Front")) {
            intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_FRONT);
        } else if (camera.equalsIgnoreCase("Back")) {
            intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_BACK);
        }

        ((Activity) mContext).startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
    }

    public static Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    public static File getOutputMediaFile(int type) {
        // External sdcard location        createFolderDirectory();
//        File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), IMAGE_DIRECTORY_NAME);//        // Create the storage directory if it does not exist//        if (!mediaStorageDir.exists()) {//            if (!mediaStorageDir.mkdirs()) {//                Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "//                        + IMAGE_DIRECTORY_NAME + " directory");//                return null;//            }//        }        // Create a media file name        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(imageFolder.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(videoFolder.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
        } else if (type == MEDIA_TYPE_AUDIO) {
            mediaFile = new File(audioFolder.getPath() + File.separator + "AUD_" + timeStamp + ".mp3");
        } else {
            return null;
        }
        return mediaFile;
    }

    public static void createFolderDirectory() {
        // root/ pkg/ type/ lang/ gender/
        File packageFolder = createFolder(root, "packagename");
        createFolder(packageFolder.getPath(), IMAGE_DIRECTORY_NAME);
        audioFolder = createFolder(root + "/packagename/" + IMAGE_DIRECTORY_NAME, "audio");        videoFolder = createFolder(root + "/packagename/" + IMAGE_DIRECTORY_NAME, "video");        imageFolder = createFolder(root + "/packagename/" + IMAGE_DIRECTORY_NAME, "images");        System.out.println("file directory created...");
    }

    public static File createFolder(String path, String folderName) {
        File SDCardRoot = new File(path, folderName);
        if (!SDCardRoot.exists()) {
            SDCardRoot.mkdir();
        }
        return SDCardRoot;
    }

    public static void pickImage(Context mContext, int CAMERA_PICK_IMAGE_REQUEST_CODE) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        ((Activity) mContext).startActivityForResult(intent, CAMERA_PICK_IMAGE_REQUEST_CODE);
    }

    public static void recordVideo(Context mContext, int CAMERA_CAPTURE_VIDEO_REQUEST_CODE, String camera) {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        if (camera.equalsIgnoreCase("Front")) {
            intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_FRONT);
        } else if (camera.equalsIgnoreCase("Back")) {
            intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_BACK);
        }
        ((Activity) mContext).startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
    }

    public static void pickVideo(Context mContext, int CAMERA_PICK_VIDEO_REQUEST_CODE) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("video/*");
        ((Activity) mContext).startActivityForResult(intent, CAMERA_PICK_VIDEO_REQUEST_CODE);
    }

    /**     * getpath of picked image or video     *     * @param context     * @param uri     * @return     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

            }
            // DownloadsProvider            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is ExternalStorageProvider.     */    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is DownloadsProvider.     */    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**     * Get the value of the data column for this Uri. This is useful for     * MediaStore Uris, and other file-based ContentProviders.     *     * @param context       The context.     * @param uri           The Uri to query.     * @param selection     (Optional) Filter used in the query.     * @param selectionArgs (Optional) Selection arguments used in the query.     * @return The value of the _data column, which is typically a file path.     */    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is MediaProvider.     */    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**     * @param uri The Uri to check.     * @return Whether the Uri authority is Google Photos.     */    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    /**     * Function to display simple Alert Dialog or Toast     *     * @param context - application context     * @param title   - alert dialog title     * @param message - alert message     * @param toast   - show as toast or dialog     */    public static void showAlertDialog(Context context, String title, String message, boolean toast) {
        if (toast) {
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        } else {

            AlertDialog alertDialog = null;
            if (!((Activity) context).isFinishing()) {
                if (alertDialog == null)
                    alertDialog = new AlertDialog.Builder(context).create();
                // Setting Dialog Title                alertDialog.setTitle(title);
                // Setting Dialog Message                alertDialog.setMessage(message);
                // Setting OK Button                alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                // Showing Alert Message                alertDialog.show();
            }
        }
    }

    /**     * use for getting device height     *     * @param mContext     * @return height of your device     */    public static int getDeviceHeight(Context mContext) {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay()
                .getMetrics(displaymetrics);
        return displaymetrics.heightPixels;
    }

    /**     * use for getting device width     *     * @param mContext     * @return width of your device     */    public static int getDeviceWidth(Context mContext) {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay()
                .getMetrics(displaymetrics);
        return displaymetrics.widthPixels;
    }

    public static void hideKeyboard(Context mContext, View v) {
        // TODO Auto-generated method stub        InputMethodManager imm = (InputMethodManager) mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static boolean isWebsiteUrlValid(String url) {
        return Patterns.WEB_URL.matcher(url).matches();
    }

    /**     * set login type     *     * @param mContext     * @param string     */    public static void setLoginStatus(Context mContext, String string) {
        setPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_urateit), false);
        setPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_linkedin), false);
        setPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_facebook), false);
        setPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_twitter), false);

        if (string.equals(mContext.getResources().getString(R.string.pref_is_login_urateit))) {
            setPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_urateit), true);
        } else if (string.equals(mContext.getResources().getString(R.string.pref_is_login_linkedin))) {
            setPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_linkedin), true);
        } else if (string.equals(mContext.getResources().getString(R.string.pref_is_login_facebook))) {
            setPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_facebook), true);
        } else if (string.equals(mContext.getResources().getString(R.string.pref_is_login_twitter))) {
            setPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_twitter), true);
        }
    }

    /**     * set Boolean Preference Value     *     * @param context     * @param prefName     * @param Value     */    public static void setPrefrencesBoolean(Context context, String prefName, Boolean Value) {
        prefs = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(prefName, Value);
        editor.commit();
    }

    /**     * get log in status     *     * @param mContext     * @return     */    public static boolean getLoginStatus(Context mContext) {
        if (getPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_urateit))) {
            return true;
        } else if (getPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_linkedin))) {
            return true;
        } else if (getPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_facebook))) {
            return true;
        } else if (getPrefrencesBoolean(mContext, mContext.getResources().getString(R.string.pref_is_login_twitter))) {
            return true;
        } else {
            return false;
        }

    }

    /**     * get Boolean Preference Value     *     * @param context     * @param prefName     * @return     */    public static boolean getPrefrencesBoolean(Context context, String prefName) {
        prefs = context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE);
        return prefs.getBoolean(prefName, false);
    }

    public static ArrayList<String> getNameEmailDetails(Context context) {
        ArrayList<String> emlRecs = new ArrayList<String>();
        HashSet<String> emlRecsHS = new HashSet<String>();
        ContentResolver cr = context.getContentResolver();
        String[] PROJECTION = new String[]{ContactsContract.RawContacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts.PHOTO_ID,
                ContactsContract.CommonDataKinds.Email.DATA,
                ContactsContract.CommonDataKinds.Photo.CONTACT_ID};
        String order = "CASE WHEN "                + ContactsContract.Contacts.DISPLAY_NAME
                + " NOT LIKE '%@%' THEN 1 ELSE 2 END, "                + ContactsContract.Contacts.DISPLAY_NAME
                + ", "                + ContactsContract.CommonDataKinds.Email.DATA
                + " COLLATE NOCASE";
        String filter = ContactsContract.CommonDataKinds.Email.DATA + " NOT LIKE ''";
        Cursor cur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION, filter, null, order);
        if (cur != null) {
            if (cur.moveToFirst()) {
                do {
                    // names comes in hand sometimes                    String name = cur.getString(1);
                    String emlAddr = cur.getString(3);

                    // keep unique only                    if (emlRecsHS.add(emlAddr.toLowerCase())) {
                        emlRecs.add(name + ", " + emlAddr);
                    }
                } while (cur.moveToNext());
            }
            cur.close();
        }
        return emlRecs;
    }


    /**     * use to show datepicker     *     * @param mContext     * @param format    of the date format     * @param mTextView in which you have to set selected date     */    public static void showDatePickerDialog(final Context mContext, final String format, final TextView mTextView) {

        final Calendar dateTime = Calendar.getInstance();

        new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {

//                SimpleDateFormat dateFormatter = new SimpleDateFormat(format);                dateTime.set(year, monthOfYear, dayOfMonth);

                String dateText = dayOfMonth + "-" + monthOfYear + "-" + year + " " + dateTime.get(Calendar.HOUR) + ":" + new DecimalFormat("#0").format(dateTime.get(Calendar.MINUTE));
                mTextView.setText(dateText);
                Appconfig.schedule = dateText;

                new DecimalFormat("#0").format(dateTime.get(Calendar.MINUTE));
            }
        }, dateTime.get(Calendar.YEAR), dateTime.get(Calendar.MONTH),
                dateTime.get(Calendar.DAY_OF_MONTH)).show();
    }

}

API parsing MyClientPost For sending Image to server Part 3

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import util.Utils;

/** * This is used for post data from API. * * @author Mayank * @since 1.4 */public class MyClientPost extends AsyncTask<Map<String, Object>, String, String> {

    public ProgressDialog dialog;
    private String message;
    private Context context;
    private OnPostCallComplete onpostcallcomplete;
    private JSONObject jsonResult;

    public MyClientPost(Context context, String progressMessage, OnPostCallComplete onPostCallComplete2) {
        message = progressMessage;
        this.context = context;
        this.onpostcallcomplete = onPostCallComplete2;

        if (!(message.equals(""))) {
            dialog = new ProgressDialog(context);
            dialog.setMessage(progressMessage);
        }
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub        super.onPreExecute();
        if (!(message.equals(""))) {
            dialog.setCancelable(false);
            dialog.show();
        }
    }

    @Override
    protected String doInBackground(Map<String, Object>... params) {
        String result = null;

        if (!isCancelled()) {

            Map<String, Object> passed_params = params[0];
            // API call URL            String serverUrl = (String) passed_params.get("url");
            Log.v(Utils.TAG, "API url: " + serverUrl);
            // parameter data to send            @SuppressWarnings("unchecked")
            Map<String, String> methodParameter = (Map<String, String>) passed_params.get("method_parameters");
            try {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(serverUrl);

                Iterator<Entry<String, String>> iterator = methodParameter.entrySet().iterator();
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(methodParameter.size());
                while (iterator.hasNext()) {
                    Entry<String, String> param = iterator.next();
                    nameValuePairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                Log.v(Utils.TAG, "post latlng " + nameValuePairs.toString());
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
                post.setEntity(entity);
                HttpResponse response = client.execute(post);
                HttpEntity resp_entity = response.getEntity();
                result = EntityUtils.toString(resp_entity);
                // System.out.println("result in post 80: "+result);                if (response.getStatusLine().getStatusCode() != 200) {
                    Log.v(Utils.TAG, "post  status code " + response.getStatusLine().getStatusCode());
                    jsonResult = new JSONObject();
                    jsonResult.put("response_code", "9999");
                    jsonResult.put("response_message", "85 Server error occurred while processing request. Please try again.");
                    result = jsonResult.toString();
                    return result;
                }
            } catch (Exception e) {
                Log.v(Utils.TAG, "post exception " + e.getMessage());
                try {
                    jsonResult = new JSONObject();
                    jsonResult.put("response_code", "9999");
                    jsonResult.put("response_message", "94 Server error occurred while processing request. Please try again.");
                    result = jsonResult.toString();
                    return result;
                } catch (JSONException jsone) {
                    jsone.printStackTrace();
                }
            }
        }
        //System.out.println("result in post: "+result);        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub        super.onPostExecute(result);
        if (!(message.equals(""))) {
            if (dialog != null) {
                dialog.hide();
                dialog.dismiss();
            }
        }
        System.out.println("result in onPostExecute: " + result);
        try {
            onpostcallcomplete.response(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public interface OnPostCallComplete {
        public void response(String result) throws JSONException;
    }
}

Download Jar files from here.

https://drive.google.com/file/d/0B53Ze24TLSktWjQyeE9tbF9JVkk/view?usp=sharing

https://drive.google.com/file/d/0B53Ze24TLSktZGtFVzRQdFBvbFE/view?usp=sharing

https://drive.google.com/file/d/0B53Ze24TLSktck9JZDd5YkhoOW8/view?usp=sharing

Picasso: https://drive.google.com/file/d/0B53Ze24TLSktb1lzWmRFeUxEaXM/view?usp=sharing


Call from activity

        Map<String, String> get_params = new HashMap<String, String>();
        get_params .put("type", type);
        Map<String, Object> api_params = new HashMap<String, Object>();
        api_params.put("url", getResources().getString(URL, Utils.getAPIAccessKey(context), Utils.getUserAccessKey(context)));
        api_params.put("method_parameters", get_params );
        System.out.println(api_params.values().toString());
        MyClientPost posting = new MyClientPost(context, "Please wait", onGetCallComplete);
        posting.execute(api_params);
MyClientPost.OnPostCallComplete onGetCallComplete = new MyClientPost.OnPostCallComplete() { @Override public void response(String result) { try {  JSONObject jobj = new JSONObject(result);
String response_code = jobj.getString("response_code"); if (response_code.equals(getResources().getString(R.string.success_code))) { JSONArray userContacts = jobj.getJSONArray("arrayname");
for (int i = 0; i < arrayname.length(); i++) {
} } } } catch (JSONException e) { e.printStackTrace(); } } };