Thursday, 9 June 2022

Optimize capture camera image in java

 

Step-1
private void captureCameraImage() {
try {
PackageManager pm = getPackageManager();
int hasPerm = pm.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName());
if (hasPerm == PackageManager.PERMISSION_GRANTED) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile;
try {
photoFile = AppUtils.getInstance().createImageFile("tenancy_image");
if (photoFile != null) {
Uri photoURI;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
photoURI = Uri.fromFile(photoFile);
} else {
photoURI = FileProvider.getUriForFile(this,
getBaseContext().getPackageName() + ".provider",
photoFile);
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
mPhotoFile = photoFile;
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(takePictureIntent, PICK_IMAGE_CAMERA);
}
} catch (IOException e) {
e.getMessage();
}
}
} else
AppUtils.getInstance().showSnack(scrollView, "Camera Permission error");

} catch (Exception e) {
AppUtils.getInstance().showSnack(scrollView, "Camera Permission error");
e.printStackTrace();
}
}
Step-2
if (requestCode == PICK_IMAGE_CAMERA && resultCode == RESULT_OK) {
try {
mPhotoFile = mCompressor.compressToFile(mPhotoFile);
InputStream ims = new FileInputStream(mPhotoFile);
Bitmap bitmap = BitmapFactory.decodeStream(ims);
imgCamera.setVisibility(View.GONE);
imgView.setImageBitmap(bitmap);
validateSubmitActivation();

} catch (FileNotFoundException e) {
e.getMessage();
return;
} catch (IOException e) {
e.printStackTrace();
}
}


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageUtil {
private ImageUtil() {

}

static File compressImage(File imageFile, int reqWidth, int reqHeight,
Bitmap.CompressFormat compressFormat, int quality, String destinationPath)
throws IOException {
FileOutputStream fileOutputStream = null;
File file = new File(destinationPath).getParentFile();
if (!file.exists()) file.mkdirs();
try {
fileOutputStream = new FileOutputStream(destinationPath);
// write the compressed bitmap at the destination specified by destinationPath.
decodeSampledBitmapFromFile(imageFile, reqWidth, reqHeight).compress(compressFormat, quality,
fileOutputStream);
} finally {
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
}

return new File(destinationPath);
}

static Bitmap decodeSampledBitmapFromFile(File imageFile, int reqWidth, int reqHeight)
throws IOException {
// First decode with inJustDecodeBounds=true to check dimensions
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;

Bitmap scaledBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);

//check the rotation of the image and display it properly
ExifInterface exif;
exif = new ExifInterface(imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
scaledBitmap =
Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(),
matrix, true);
return scaledBitmap;
}

private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth,
int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

final int halfHeight = height / 2;
final int halfWidth = width / 2;

// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight & (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}

return inSampleSize;
}
}


import android.content.Context;
import android.graphics.Bitmap;

import java.io.File;
import java.io.IOException;

public class FileCompressor {
//max width and height values of the compressed image is taken as 612x816
private int maxWidth = 612;
private int maxHeight = 816;
private Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.JPEG;
private int quality = 80;
private String destinationDirectoryPath;

public FileCompressor(Context context) {
destinationDirectoryPath = context.getCacheDir().getPath() + File.separator + "images";
}

public FileCompressor setMaxWidth(int maxWidth) {
this.maxWidth = maxWidth;
return this;
}

public FileCompressor setMaxHeight(int maxHeight) {
this.maxHeight = maxHeight;
return this;
}

public FileCompressor setCompressFormat(Bitmap.CompressFormat compressFormat) {
this.compressFormat = compressFormat;
return this;
}

public FileCompressor setQuality(int quality) {
this.quality = quality;
return this;
}

public FileCompressor setDestinationDirectoryPath(String destinationDirectoryPath) {
this.destinationDirectoryPath = destinationDirectoryPath;
return this;
}

public File compressToFile(File imageFile) throws IOException {
return compressToFile(imageFile, imageFile.getName());
}

public File compressToFile(File imageFile, String compressedFileName) throws IOException {
return ImageUtil.compressImage(imageFile, maxWidth, maxHeight, compressFormat, quality,
destinationDirectoryPath + File.separator + compressedFileName);
}

public Bitmap compressToBitmap(File imageFile) throws IOException {
return ImageUtil.decodeSampledBitmapFromFile(imageFile, maxWidth, maxHeight);
}
}

Tuesday, 13 October 2020

Check and Parse dynamic Json Data - JSONObject/ JSONArray in Kotlin

When we don't know about which kind of json data (JSONObject/ JSONArray) receiving from web service. In such scenario how to handle json parsing in kotlin-


 val jsonObject = JSONObject(response)
 val jObj = jsonObject.optJSONObject("result_key")

    if (jObj.get("json_key") is JSONArray){ 
      val rejProArr: JSONArray = jObj.getJSONArray("json_key")
  } else if (jObj.get("json_key") is JSONObject) { 
       val rejProObject: JSONObject = jObj.optJSONObject("json_key")
  }
Here json_key either JSONArray or JSONObject, So we can parse accordingly to avoid crash.

Wednesday, 18 September 2019

Generate release key hash for facebook login in android

     
keytool -exportcert -alias ALIAS_NAME-keystore KEY_STORE_PATH| OPEN_SSL_PATH  sha1 -binary | OPEN_SSL_PATH  base64

example-
keytool -exportcert -alias ReleaseKey-keystore D:\Android Workspace\MyApp.jks | "C:\bin\openssl.exe"  sha1 -binary | "C:\bin\openssl.exe"  base64


Open command prompt and set the JDK PATH then run the above command to generate the HASH KEY

C:\Program Files\Java\jdk-12.0.2\bin> keytool -exportcert -alias ReleaseKey-keystore D:\Android Workspace\MyApp.jks | "C:\bin\openssl.exe"  sha1 -binary | "C:\bin\openssl.exe"  base64

you will get generated KEY HASH.



If you find open SSL issue then
Please follow these step, I hope your key working properly:

Openssl is not recognized as an internal or external command


1 You will need OpenSSL. You can download the binary from openssl-for-windows project on Google Code.


2 Unzip the folder, then copy the path to the bin folder to the clipboard.
For example, if the file is unzipped to the location C:\Users\openssl-0.9.8k_X64, then copy the path C:\Users\openssl-0.9.8k_X64\bin

and paste this path in your above command.

 

Wednesday, 11 September 2019

Set Badge count above notification icons



Layout.xml-   


<RelativeLayout

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:layout_weight="1">



    <TextView

        android:id="@+id/tv_notification"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:drawableTop="@drawable/notification_select"

        android:gravity="center"

        android:maxLines="1"

        android:text="Notification"

        android:textColor="@color/blue_color"

        android:textSize="10sp" />



    <com.nex3z.notificationbadge.NotificationBadge

        android:id="@+id/badge_count"

        android:layout_width="28dp"

        android:layout_height="28dp"

        android:layout_alignTop="@+id/tv_notification"

        android:layout_marginLeft="-30dp"

        android:layout_marginTop="-4dp"

        android:layout_toRightOf="@+id/tv_notification"

        app:badgeBackground="@drawable/badge_count"

        app:badgeTextSize="10dp"

        app:maxTextLength="2" />



</RelativeLayout>


Code- 

package com.nex3z.notificationbadge;



import android.content.Context;

import android.content.res.TypedArray;

import android.graphics.drawable.Drawable;

import android.util.AttributeSet;

import android.util.TypedValue;

import android.view.LayoutInflater;

import android.view.animation.Animation;

import android.view.animation.ScaleAnimation;

import android.widget.FrameLayout;

import android.widget.ImageView;

import android.widget.TextView;



public class NotificationBadge extends FrameLayout {

    private static final int DEFAULT_TEXT_COLOR = 0xFFFFFFFF;

    private static final int DEFAULT_TEXT_SIZE = 14;

    private static final boolean DEFAULT_ANIMATION_ENABLED = true;

    private static final int DEFAULT_ANIMATION_DURATION = 500;

    private static final int DEFAULT_MAX_TEXT_LENGTH = 2;

    private static final String DEFAULT_MAX_LENGTH_REACHED_TEXT = "...";



    private FrameLayout mContainer;

    private ImageView mIvBadgeBg;

    private TextView mTvBadgeText;

    private int mBadgeTextColor = DEFAULT_TEXT_COLOR;

    private float mBadgeTextSize = dpToPx(DEFAULT_TEXT_SIZE);

    private int mAnimationDuration = DEFAULT_ANIMATION_DURATION;

    private Animation mUpdate;

    private Animation mShow;

    private Animation mHide;

    private String mBadgeText;

    private boolean mIsBadgeShown;

    private boolean mAnimationEnabled = DEFAULT_ANIMATION_ENABLED;

    private int mMaxTextLength = DEFAULT_MAX_TEXT_LENGTH;

    private String mEllipsizeText = DEFAULT_MAX_LENGTH_REACHED_TEXT;



    public NotificationBadge(Context context, AttributeSet attrs) {

        super(context, attrs);



        LayoutInflater inflater = (LayoutInflater) context.getSystemService(

                Context.LAYOUT_INFLATER_SERVICE);

        inflater.inflate(R.layout.notification_badge, this, true);

        mContainer = (FrameLayout) findViewById(R.id.fl_container);

        mIvBadgeBg = (ImageView) findViewById(R.id.iv_badge_bg);

        mTvBadgeText = (TextView) findViewById(R.id.tv_badge_text);



        TypedArray a = context.getTheme().obtainStyledAttributes(

                attrs, R.styleable.NotificationBadge, 0, 0);

        try {

            mBadgeTextColor = a.getColor(R.styleable.NotificationBadge_badgeTextColor, DEFAULT_TEXT_COLOR);

            mTvBadgeText.setTextColor(mBadgeTextColor);



            mBadgeTextSize = a.getDimensionPixelSize(R.styleable.NotificationBadge_badgeTextSize, (int)dpToPx(DEFAULT_TEXT_SIZE));

            mTvBadgeText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mBadgeTextSize);



            mAnimationEnabled = a.getBoolean(R.styleable.NotificationBadge_animationEnabled, DEFAULT_ANIMATION_ENABLED);



            mAnimationDuration = a.getInt(R.styleable.NotificationBadge_animationDuration, DEFAULT_ANIMATION_DURATION);

            Drawable badgeBackground = a.getDrawable(R.styleable.NotificationBadge_badgeBackground);

            if (badgeBackground != null) {

                mIvBadgeBg.setImageDrawable(badgeBackground);

            }



            mMaxTextLength = a.getInt(R.styleable.NotificationBadge_maxTextLength, DEFAULT_MAX_TEXT_LENGTH);

            mEllipsizeText = a.getString(R.styleable.NotificationBadge_ellipsizeText);

            if (mEllipsizeText == null) {

                mEllipsizeText = DEFAULT_MAX_LENGTH_REACHED_TEXT;

            }

        } finally {

            a.recycle();

        }



        if (mAnimationEnabled) {

            initUpdateAnimation();

        }

    }



    public void clear() {

        if (mIsBadgeShown) {

            if (mAnimationEnabled) {

                mContainer.startAnimation(mHide);

            } else {

                mContainer.setVisibility(INVISIBLE);

            }

            mIsBadgeShown = false;

        }

    }



    public void show(String text) {

        mBadgeText = text;

        if (!mIsBadgeShown) {

            if (mAnimationEnabled) {

                mContainer.startAnimation(mShow);

            } else {

                mContainer.setVisibility(VISIBLE);

                mTvBadgeText.setText(text);

            }

            mIsBadgeShown = true;

        } else {

            mTvBadgeText.setText(text);

        }

    }



    public boolean isAnimationEnabled() {

        return mAnimationEnabled;

    }



    public void setAnimationEnabled(boolean animationEnabled) {

        mAnimationEnabled = animationEnabled;

        if (animationEnabled && (mUpdate == null || mShow == null || mHide == null)) {

            initUpdateAnimation();

        }

    }



    public void setMaxTextLength(int maxLength) {

        mMaxTextLength = maxLength;

    }



    public void setText(String text) {

        if (text != null && text.length() > mMaxTextLength) {

            mBadgeText = mEllipsizeText;

        } else {

            mBadgeText = text;

        }

        if (text == null || text.isEmpty()) {

            clear();

        } else {

            if (mIsBadgeShown) {

                if (mAnimationEnabled) {

                    mContainer.startAnimation(mUpdate);

                } else {

                    mTvBadgeText.setText(mBadgeText);

                }

            } else {

                show(text);

            }

        }

    }



    public void setNumber(int number) {

        if (number == 0) {

            clear();

        } else {

            setText(String.valueOf(number));

        }

    }



    public int getTextColor() {

        return mBadgeTextColor;

    }



    public void setTextColor(int textColor) {

        mBadgeTextColor = textColor;

        mTvBadgeText.setTextColor(textColor);

    }



    public void setTextSize(float textSize) {

        mBadgeTextSize = textSize;

        mTvBadgeText.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);

    }



    public void setBadgeBackgroundDrawable(Drawable drawable) {

        mIvBadgeBg.setImageDrawable(drawable);

    }



    public void setBadgeBackgroundResource(int resId) {

        mIvBadgeBg.setImageResource(resId);

    }



    private void initUpdateAnimation() {

        mUpdate = new ScaleAnimation(1, 1.2f, 1, 1.2f,

                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

        mUpdate.setDuration(mAnimationDuration / 2);

        mUpdate.setRepeatMode(Animation.REVERSE);

        mUpdate.setRepeatCount(1);

        mUpdate.setAnimationListener(new Animation.AnimationListener() {

            @Override

            public void onAnimationStart(Animation animation) {

                mTvBadgeText.setText(mBadgeText);

            }

            @Override

            public void onAnimationEnd(Animation animation) {}

            @Override

            public void onAnimationRepeat(Animation animation) {}

        });



        mShow = new ScaleAnimation(0, 1, 0, 1,

                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

        mShow.setDuration(mAnimationDuration / 2);

        mShow.setAnimationListener(new Animation.AnimationListener() {

            @Override

            public void onAnimationStart(Animation animation) {

                mContainer.setVisibility(VISIBLE);

                mTvBadgeText.setText(mBadgeText);

            }

            @Override

            public void onAnimationEnd(Animation animation) {}

            @Override

            public void onAnimationRepeat(Animation animation) {}

        });



        mHide = new ScaleAnimation(1, 0, 1, 0,

                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

        mHide.setDuration(mAnimationDuration / 2);

        mHide.setAnimationListener(new Animation.AnimationListener() {

            @Override

            public void onAnimationStart(Animation animation) {}

            @Override

            public void onAnimationEnd(Animation animation) {

                mContainer.setVisibility(INVISIBLE);

            }

            @Override

            public void onAnimationRepeat(Animation animation) {}

        });

    }



    private float dpToPx(float dp){

        return TypedValue.applyDimension(

                TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());

    }



}