Wednesday 21 August 2013

Get json respone using POST method

If you have an web api with json response and with "method = post" and with parameters then do like below

in your oncreate method

GetAllCities getallcities = new GetAllCities();            getallcities.execute(this); 

outside of your oncreate method

@SuppressWarnings("rawtypes")
    public class GetAllCities extends AsyncTask {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            prodialog = new ProgressDialog(mContext);
            prodialog.setMessage("Loading");
            prodialog.show();
            prodialog.setCancelable(false);
        }

        @Override
        protected Object doInBackground(Object... params) {
            // TODO Auto-generated method stub
            String result;
            try {
                JsonHttpPost httpPost = new JsonHttpPost();
           
                result = httpPost.post1();
                Log.i(tag, "result" + result);
               
                cityparser = new CityParser();
                lstcitysetget = cityparser.citysetget(result);
               
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return lstcitysetget;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void onPostExecute(Object result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            prodialog.dismiss();
           // make your adapter here
                }
    } 



put below function in your JosnHTTP class

public String post1() {
        String result = null;
        try {
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(params, TIMEOUT_MILLISEC);
            HttpClient client = new DefaultHttpClient(params);
            System.out.println("Getting url: ");
            HttpPost post = new HttpPost(serverurl);

            try {
                JSONObject json = new JSONObject();
                json.put("action", "get_all_cities");
                post.setEntity(new ByteArrayEntity(json.toString().getBytes(
                        "UTF8")));

            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }

            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            } else {
                Log.d("Response Failed", "Response from server is failed");
            }

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



this is my parser class

public class CityParser {
   
    public List<String> citysetget(String result) {

        String city_id = "", state_id = "", city_name = "";

        //List<CityGetterSetter> citysetgetlst = new ArrayList<CityGetterSetter>();
        List<String> citysetgetlst = new ArrayList<String>();

        CityGetterSetter citysetget = null;
        try {
            JSONObject jsonObject = new JSONObject(result);

            if (jsonObject != null) {
                JSONArray objarry = jsonObject.optJSONArray("get_all_cities");

                if (objarry != null) {
                    JSONArray strU_ID = jsonObject
                            .getJSONArray("get_all_cities");

                    for (int i = 0; i < strU_ID.length(); i++) {

                        JSONObject obj = strU_ID.getJSONObject(i);
                        if (obj.has("city_id")) {
                            city_id = obj.getString("city_id");
                        }
                        if (obj.has("state_id")) {
                            state_id = obj.getString("state_id");
                        }
                        if (obj.has("city_name")) {
                            city_name = obj.getString("city_name");
                        }
                      
                        citysetget = new CityGetterSetter(city_name);
                    //    citysetgetlst.add(citysetget);
                        citysetgetlst.add(city_name);
                    }
                }
            }
            Log.i("City Paresr...", "city list.."+ citysetgetlst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return citysetgetlst;
    }
}




If more then one parameter then


    public String postSearch(String city,String purpose,String people) {
        String result = null;
        try {
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_MILLISEC);
            HttpConnectionParams.setSoTimeout(params, TIMEOUT_MILLISEC);
            HttpClient client = new DefaultHttpClient(params);
            System.out.println("Getting url: ");
            HttpPost post = new HttpPost(serverurlsearch);

            // String body = "{\"action\":\"get_all_cities\"}";
            try {
                JSONObject json = new JSONObject();
                json.put("action", "search_venues_by_purpose");
                json.put("city",city);
                json.put("purpose",purpose);
                json.put("people", people);
              
                post.setEntity(new ByteArrayEntity(json.toString().getBytes(
                        "UTF8")));

            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }

            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            } else {
                Log.d("Response Failed", "Response from server is failed");
            }

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



Wednesday 14 August 2013

Exit from whole application

When you want to exit from whole application use below code

         Intent intent = new Intent(Intent.ACTION_MAIN);
         intent.addCategory(Intent.CATEGORY_HOME);
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         startActivity(intent);
         finish();

Get Current Latitude and Longitude

To get current latitude and longitude 

create one class name CurrentLocListener 

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;


public class CurrentLocListener implements LocationListener {
   
    private static final String TAG = "CurrentLocListener - ";
   
    Context mContext;
   
    String latitude,longitude,token;
   
    public CurrentLocListener(Context context){
        mContext = context;
    }

    public void onLocationChanged(Location location) {
        Log.i("Lock Me If You Can", TAG + "onLocationChanged - Latitude: " + String.valueOf(location.getLatitude()) + " Longitude: " + String.valueOf(location.getLongitude()));
        Utility.setSharedKey("Latitude", String.valueOf(location.getLatitude()), mContext);
        Utility.setSharedKey("Longitude", String.valueOf(location.getLongitude()), mContext);
      
        //Intent mIntent = new Intent(General.ACTION_LOCATION_CHANGED);
        //mContext.sendBroadcast(mIntent);
    }

    public void onProviderDisabled(String provider) {
        Log.i("Lock Me If You Can", TAG + "onProviderDisabled - ");
    }

    public void onProviderEnabled(String provider) {
        Log.i("Lock Me If You Can", TAG + "onProviderEnabled - ");
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.i("Lock Me If You Can", TAG + "onStatusChanged - ");
    }
}
 


in your main activity create below method


public static void registerLocationListener(Context context) {
        LocationManager lManager = null;
        CurrentLocListener cListener = null;
        lManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);

        boolean isGpsEnabled = false;
        boolean isNetworkEnabled = false;

        isGpsEnabled = lManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = lManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isGpsEnabled) {
            cListener = new CurrentLocListener(context);
            lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                    cListener);
            Location location = lManager
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                setSharedKey("Latitude",
                        String.valueOf(location.getLatitude()), context);
                setSharedKey("Longitude",
                        String.valueOf(location.getLongitude()), context);
            }
        }
        if (isNetworkEnabled) {
            cListener = new CurrentLocListener(context);
            lManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                    0, 0, cListener);
            Location location = lManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
                setSharedKey("Latitude",
                        String.valueOf(location.getLatitude()), context);
                setSharedKey("Longitude",
                        String.valueOf(location.getLongitude()), context);
            }
        }
    }


 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, "");
    }
    


in your oncreate method write below code

registerLocationListener(mcontext);
latitude = Utility.getSharedKey("Latitude",mcontext);
longitude = Utility.getSharedKey("Longitude",mcontext);

give permissions in your menifest file

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

 

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");

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