APK Size Analyze by android studio

From android studio you can Analyze you apk size and based on this you can reduce images size and other resources size

So Open your project by android studio .Now select build option from menu and under the build option you can find APK analyze and then choose your project APK from build ->output folder

after selection this option studio open a new windows with all details report of you APK , which part taken what memory you can check easily from here , check below screen capture to understand more more details


1. Open from menu option








After Generate apk Analyze report looks like below with all information 


How can create a bitmap image using string file path of image Android


You need to use BitmapFactory class and based on below method declare you can easily convert bitmap from a string path of image , here i set 400,400 (Height and Width  of image but it is not good
idea to fix height and width ) you can use option/4 , option/2 that manes it takes 1/2 or 1/4 of the height , width ratio of original image height and width





public static Bitmap decodeBitmapFromResource(String imagePath) throws OutOfMemoryError {

        try {
            // First decode with inJustDecodeBounds=true to check dimensions
        //    File sd = Environment.getExternalStorageDirectory();
            File image = new File(imagePath);
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
            bitmap = Bitmap.createScaledBitmap(bitmap,400,400,true);

            return  bitmap;
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return null;
    }

How can handle image rotation problem after capture image from camera android


1. 1st you need to detect current orientation of the image based on below method, and the call rotateImage() with Rotation degree value .


String TAG="ImageRotate";

public static void ReRotateImage(String imgfilepath){
try {
             ei = new ExifInterface(imgfilepath);
             int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
             Log.e(TAG,"orientation: "+ orientation);
            // Crashlytics.setInt("PICTURE ORIENTAION",orientation);
             switch(orientation) {
             case ExifInterface.ORIENTATION_ROTATE_90:
                 //rotateImage(bitmap, 90);
                 Log.e(TAG,"ORIENTATION_ROTATE_90");
                 rotateImage(imgfilepath, 90);
                 break;
             case ExifInterface.ORIENTATION_ROTATE_180:
                // rotateImage(bitmap, 180);
                  Log.e(TAG,"ORIENTATION_ROTATE_180");
                 rotateImage(imgfilepath, 180);
                 break;
             case ExifInterface.ORIENTATION_ROTATE_270:
                    // rotateImage(bitmap, 180);
                      Log.e(TAG,"ORIENTATION_ROTATE_270");
                     rotateImage(imgfilepath, 270);
                     break;
             // etc.
                 default:
                     Log.e(TAG, "ORIENTATION_ROTATE_0");
                    // rotateImage1(imgfilepath, 0);
                     break;
         }
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
}


2. Method image rotated as per demand


private static Bitmap rotateImage(String strImagePath, int degree) {

       // Bitmap img = BitmapFactory.decodeFile(strImagePath);
       // Bitmap img=convertBitmapNew(strImagePath);//convertBitmap(strImagePath);

        Bitmap img=BitmapHelper.decodeFile(new File(strImagePath),1024,1024,true);

        /*NEW CODE*/
        if ((img.getWidth() >= 1024) && (img.getHeight() >= 1024)) {
    BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
    bmpOptions.inSampleSize = 1;
    while ((img.getWidth() >= 1024) && (img.getHeight() >= 1024)) {
        bmpOptions.inSampleSize++;
        img = BitmapFactory.decodeFile(strImagePath, bmpOptions);
    }
    LogUtils.showDebugLog(TAG+"camera", "Resize1: " + bmpOptions.inSampleSize);
}
        /*--------*/
       
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
       
        try {
            FileOutputStream bmpFile = new FileOutputStream(strImagePath);
            rotatedImg.compress(Bitmap.CompressFormat.JPEG, 100, bmpFile);
            bmpFile.flush();
            bmpFile.close();
        } catch (Exception e) {
            LogUtils.showDebugLog(TAG+"camera", "Error on saving file");
        }
        img.recycle();
        return rotatedImg;
    }

3. Convert Bit map


 public static Bitmap convertBitmap(String path)   {
        LogUtils.showDebugLog(TAG+"camera", "Entry Rotate: ");
        Bitmap bitmap=null;

        BitmapFactory.Options bfOptions=new BitmapFactory.Options();
       // bfOptions.inDither=false;                     //Disable Dithering mode
        bfOptions.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
        bfOptions.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
        bfOptions.inTempStorage=new byte[32 * 1024];

        /*New code 20/04/16*/
        bfOptions.inJustDecodeBounds = false;
        bfOptions.inPreferredConfig = Bitmap.Config.RGB_565;
        bfOptions.inDither = true;
        /******************/


        File file=new File(path);
        FileInputStream fs=null;
        try {
            fs = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            if(fs!=null)
            {
                bitmap= BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
            }
        } catch (IOException e) {

            e.printStackTrace();
        } finally{
            if(fs!=null) {
                try {
                    fs.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        }

        return bitmap;
    }


    public static Bitmap convertBitmapNew(String path){
        Bitmap bitmap=null;
        /******************************/
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path,options);
        options.inSampleSize = calculateInSampleSize(options, 1024, 1024);
        options.inJustDecodeBounds = false;

        bitmap= BitmapFactory.decodeFile(path,options);
        /******************/
        return bitmap;
    }

    public 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;
            }
        }
        LogUtils.showDebugLog(TAG,""+inSampleSize);

        return inSampleSize;
    }


this is you can call from a class as per i declared




How can make first latter caps of a string Android

By this method you can easily convert your 1st latter to caps , if 1st later already in caps then no changes happen  string always rerun with 1st latter caps


 public static String get1stLatterCaps(String mString)
    {


        String mFinalStr="";

        try {

            if (mString.length() > 0) {

                String mTempString = ("" + mString.charAt(0)).toUpperCase();
               //  Log.e(" mTempString ", " mTempString : " + mTempString);
               //  Log.e(" mString.charAt(0) ", " mString.charAt(0) : " + mString.charAt(0));


                if (mString.length() > 1) {

                    mFinalStr = mTempString + mString.substring(1, mString.length());
                  //   Log.e(" mStr ", " mStr  : " + mFinalStr);
                } else {
                    mFinalStr = mTempString;
                    // Log.e(" mStr ", " mStr  : " + mFinalStr);
                }

            } else {
                 Log.e(" empty String ", " empty String : ");
            }

            Log.e("mFinalStr ", " mFinalStr : " +mFinalStr);


            //mString.replace(""+mString.charAt(0),mTempString);
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }


        return mFinalStr;

    }

Create apk based on mobile device Density or layout CPU type android

Android application you can build APK for specific CPU . You just need to config your app gradle
with some properties and CPU name

you can splits function to achieve your goal . now you just put below function into your app gradle file  like below mention


splits {
  
    abi {
      
          // Enables building multiple APKs per ABI.   
           enable true       
         // By default all ABIs are included, so use reset() and include to specify that we only       
         // want APKs for x86, armeabi-v7a, and mips.
         // Resets the list of ABIs that Gradle should create APKs for to none.        reset()
         // Specifies a list of ABIs that Gradle should create APKs for.     
           include "x86", "armeabi-v7a"     
        // Specifies that we do not want to also generate a universal APK that includes all ABIs.  
           universalApk false   
   }
}


   In this code I config here 2 type CPU "x86" and "armeabi-v7a" and based on 
   this APK will be generate .  


   




Full gradle file details below 

apply plugin: 'com.android.application'
android {
    compileSdkVersion 29   
 buildToolsVersion "29.0.2"  
  defaultConfig {
        applicationId "com.ntss.test"   
     minSdkVersion 19     
   targetSdkVersion 29    
    versionCode 1   
     versionName "1.0"      
  testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"    }
    buildTypes {
        release {
            minifyEnabled false     
           proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'     
       }
    }

    splits{

        // Configures multiple APKs based on ABI.        abi {
            // Enables building multiple APKs per ABI.            enable true            // By default all ABIs are included, so use reset() and include to specify that we only            // want APKs for x86, armeabi-v7a, and mips.            // Resets the list of ABIs that Gradle should create APKs for to none.            reset()
            // Specifies a list of ABIs that Gradle should create APKs for.            include "x86", "armeabi-v7a"            // Specifies that we do not want to also generate a universal APK that includes all ABIs.            universalApk false        }
    }

}

dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'androidx.appcompat:appcompat:1.0.2'  
   implementation 'com.google.android.material:material:1.0.0' 
   implementation 'androidx.constraintlayout:constraintlayout:1.1.3'   
   implementation 'androidx.navigation:navigation-fragment:2.0.0'
   implementation 'androidx.navigation:navigation-ui:2.0.0' 
   implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
   testImplementation 'junit:junit:4.12'  
   androidTestImplementation 'androidx.test.ext:junit:1.1.0'  
   androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}



for more details you can see this like 













Android Auto view pager or Slide image very 3 second android

XML define of View Pager

// create custom view pager and declare into xml as below //


main activity XML



<com.AutoScrollViewPager    android:id="@+id/pagerView"    android:layout_width="match_parent"    android:layout_height="@dimen/dimens150dp"    app:layout_constraintStart_toStartOf="parent"    app:layout_constraintStart_toEndOf="parent"    app:layout_constraintTop_toTopOf="parent"    >



main activity java code


viewPager= findViewById(R.id.pagerView);
viewPager.startAutoScroll();
viewPager.setInterval(3000);
viewPager.setCycle(true);
viewPager.setStopScrollWhenTouch(true);

PagerAdapter adapter = new ViewPagerAdapter(HomeActivity.this,imageId,imagesName);
viewPager.setAdapter(adapter);





Custom pager view class 


import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.Interpolator;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;

public class AutoScrollViewPager extends ViewPager {

    public static final int        DEFAULT_INTERVAL            = 1500;

    public static final int        LEFT                        = 0;
    public static final int        RIGHT                       = 1;

    /** do nothing when sliding at the last or first item **/    public static final int        SLIDE_BORDER_MODE_NONE      = 0;
    /** cycle when sliding at the last or first item **/    public static final int        SLIDE_BORDER_MODE_CYCLE     = 1;
    /** deliver event to parent when sliding at the last or first item **/    public static final int        SLIDE_BORDER_MODE_TO_PARENT = 2;

    /** auto scroll time in milliseconds, default is {@link #DEFAULT_INTERVAL} **/    private long                   interval                    = DEFAULT_INTERVAL;
    /** auto scroll direction, default is {@link #RIGHT} **/    private int                    direction                   = RIGHT;
    /** whether automatic cycle when auto scroll reaching the last or first item, default is true **/    private boolean                isCycle                     = true;
    /** whether stop auto scroll when touching, default is true **/    private boolean                stopScrollWhenTouch         = true;
    /** how to process when sliding at the last or first item, default is {@link #SLIDE_BORDER_MODE_NONE} **/    private int                    slideBorderMode             = SLIDE_BORDER_MODE_NONE;
    /** whether animating when auto scroll at the last or first item **/    private boolean                isBorderAnimation           = true;
    /** scroll factor for auto scroll animation, default is 1.0 **/    private double                 autoScrollFactor            = 1.0;
    /** scroll factor for swipe scroll animation, default is 1.0 **/    private double                 swipeScrollFactor           = 1.0;

    private Handler handler;
    private boolean                isAutoScroll                = false;
    private boolean                isStopByTouch               = false;
    private float                  touchX                      = 0f, downX = 0f;
    private CustomDurationScroller scroller                    = null;

    public static final int        SCROLL_WHAT                 = 0;

    public AutoScrollViewPager(Context paramContext) {
        super(paramContext);
        init();
    }

    public AutoScrollViewPager(Context paramContext, AttributeSet paramAttributeSet) {
        super(paramContext, paramAttributeSet);
        init();
    }

    private void init() {
        handler = new MyHandler(this);
        setViewPagerScroller();
    }

    /**     * start auto scroll, first scroll delay time is {@link #getInterval()}     */    public void startAutoScroll() {
        isAutoScroll = true;
        sendScrollMessage((long)(interval + scroller.getDuration() / autoScrollFactor * swipeScrollFactor));
    }

    /**     * start auto scroll     *     * @param delayTimeInMills first scroll delay time     */    public void startAutoScroll(int delayTimeInMills) {
        isAutoScroll = true;
        sendScrollMessage(delayTimeInMills);
    }

    /**     * stop auto scroll     */    public void stopAutoScroll() {
        isAutoScroll = false;
        handler.removeMessages(SCROLL_WHAT);
    }

    /**     * set the factor by which the duration of sliding animation will change while swiping     */    public void setSwipeScrollDurationFactor(double scrollFactor) {
        swipeScrollFactor = scrollFactor;
    }

    /**     * set the factor by which the duration of sliding animation will change while auto scrolling     */    public void setAutoScrollDurationFactor(double scrollFactor) {
        autoScrollFactor = scrollFactor;
    }

    private void sendScrollMessage(long delayTimeInMills) {
        /** remove messages before, keeps one message is running at most **/        handler.removeMessages(SCROLL_WHAT);
        handler.sendEmptyMessageDelayed(SCROLL_WHAT, delayTimeInMills);
    }

    /**     * set ViewPager scroller to change animation duration when sliding     */    private void setViewPagerScroller() {
        try {
            Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
            scrollerField.setAccessible(true);
            Field interpolatorField = ViewPager.class.getDeclaredField("sInterpolator");
            interpolatorField.setAccessible(true);

            scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));
            scrollerField.set(this, scroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**     * scroll only once     */    public void scrollOnce() {
        PagerAdapter adapter = getAdapter();
        int currentItem = getCurrentItem();
        int totalCount;
        if (adapter == null || (totalCount = adapter.getCount()) <= 1) {
            return;
        }

        int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;
        if (nextItem < 0) {
            if (isCycle) {
                setCurrentItem(totalCount - 1, isBorderAnimation);
            }
        } else if (nextItem == totalCount) {
            if (isCycle) {
                setCurrentItem(0, isBorderAnimation);
            }
        } else {
            setCurrentItem(nextItem, true);
        }
    }

    /**     * <ul>
     * if stopScrollWhenTouch is true     * <li>if event is down, stop auto scroll.</li>
     * <li>if event is up, start auto scroll again.</li>
     * </ul>
     */    @Override    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getActionMasked();

        if (stopScrollWhenTouch) {
            if ((action == MotionEvent.ACTION_DOWN) && isAutoScroll) {
                isStopByTouch = true;
                stopAutoScroll();
            } else if (ev.getAction() == MotionEvent.ACTION_UP && isStopByTouch) {
                startAutoScroll();
            }
        }

        if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT || slideBorderMode == SLIDE_BORDER_MODE_CYCLE) {
            touchX = ev.getX();
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                downX = touchX;
            }
            int currentItem = getCurrentItem();
            PagerAdapter adapter = getAdapter();
            int pageCount = adapter == null ? 0 : adapter.getCount();
            /**             * current index is first one and slide to right or current index is last one and slide to left.<br/>
             * if slide border mode is to parent, then requestDisallowInterceptTouchEvent false.<br/>
             * else scroll to last one when current item is first one, scroll to first one when current item is last             * one.             */            if ((currentItem == 0 && downX <= touchX) || (currentItem == pageCount - 1 && downX >= touchX)) {
                if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                } else {
                    if (pageCount > 1) {
                        setCurrentItem(pageCount - currentItem - 1, isBorderAnimation);
                    }
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.dispatchTouchEvent(ev);
            }
        }
        getParent().requestDisallowInterceptTouchEvent(true);

        return super.dispatchTouchEvent(ev);
    }

    private static class MyHandler extends Handler {

        private final WeakReference<AutoScrollViewPager> autoScrollViewPager;

        public MyHandler(AutoScrollViewPager autoScrollViewPager) {
            this.autoScrollViewPager = new WeakReference<AutoScrollViewPager>(autoScrollViewPager);
        }

        @Override        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case SCROLL_WHAT:
                    AutoScrollViewPager pager = this.autoScrollViewPager.get();
                    if (pager != null) {
                        pager.scroller.setScrollDurationFactor(pager.autoScrollFactor);
                        pager.scrollOnce();
                        pager.scroller.setScrollDurationFactor(pager.swipeScrollFactor);
                        pager.sendScrollMessage(pager.interval + pager.scroller.getDuration());
                    }
                default:
                    break;
            }
        }
    }

    /**     * get auto scroll time in milliseconds, default is {@link #DEFAULT_INTERVAL}     *     * @return the interval     */    public long getInterval() {
        return interval;
    }

    /**     * set auto scroll time in milliseconds, default is {@link #DEFAULT_INTERVAL}     *     * @param interval the interval to set     */    public void setInterval(long interval) {
        this.interval = interval;
    }

    /**     * get auto scroll direction     *     * @return {@link #LEFT} or {@link #RIGHT}, default is {@link #RIGHT}     */    public int getDirection() {
        return (direction == LEFT) ? LEFT : RIGHT;
    }

    /**     * set auto scroll direction     *     * @param direction {@link #LEFT} or {@link #RIGHT}, default is {@link #RIGHT}     */    public void setDirection(int direction) {
        this.direction = direction;
    }

    /**     * whether automatic cycle when auto scroll reaching the last or first item, default is true     *     * @return the isCycle     */    public boolean isCycle() {
        return isCycle;
    }

    /**     * set whether automatic cycle when auto scroll reaching the last or first item, default is true     *     * @param isCycle the isCycle to set     */    public void setCycle(boolean isCycle) {
        this.isCycle = isCycle;
    }

    /**     * whether stop auto scroll when touching, default is true     *     * @return the stopScrollWhenTouch     */    public boolean isStopScrollWhenTouch() {
        return stopScrollWhenTouch;
    }

    /**     * set whether stop auto scroll when touching, default is true     *     * @param stopScrollWhenTouch     */    public void setStopScrollWhenTouch(boolean stopScrollWhenTouch) {
        this.stopScrollWhenTouch = stopScrollWhenTouch;
    }

    /**     * get how to process when sliding at the last or first item     *     * @return the slideBorderMode {@link #SLIDE_BORDER_MODE_NONE}, {@link #SLIDE_BORDER_MODE_TO_PARENT},     *         {@link #SLIDE_BORDER_MODE_CYCLE}, default is {@link #SLIDE_BORDER_MODE_NONE}     */    public int getSlideBorderMode() {
        return slideBorderMode;
    }

    /**     * set how to process when sliding at the last or first item     *     * @param slideBorderMode {@link #SLIDE_BORDER_MODE_NONE}, {@link #SLIDE_BORDER_MODE_TO_PARENT},     *        {@link #SLIDE_BORDER_MODE_CYCLE}, default is {@link #SLIDE_BORDER_MODE_NONE}     */    public void setSlideBorderMode(int slideBorderMode) {
        this.slideBorderMode = slideBorderMode;
    }

    /**     * whether animating when auto scroll at the last or first item, default is true     *     * @return     */    public boolean isBorderAnimation() {
        return isBorderAnimation;
    }

    /**     * set whether animating when auto scroll at the last or first item, default is true     *     * @param isBorderAnimation     */    public void setBorderAnimation(boolean isBorderAnimation) {
        this.isBorderAnimation = isBorderAnimation;
    }
}



//------------------------------------------------------------------------------------//

 class CustomDurationScroller below details 



import android.content.Context;
import android.view.animation.Interpolator;
import android.widget.Scroller;

public class CustomDurationScroller extends Scroller {

    private double scrollFactor = 1;

    public CustomDurationScroller(Context context) {
        super(context);
    }

    public CustomDurationScroller(Context context, Interpolator interpolator) {
        super(context, interpolator);
    }

    public void setScrollDurationFactor(double scrollFactor) {
        this.scrollFactor = scrollFactor;
    }

    @Override    public void startScroll(int startX, int startY, int dx, int dy, int duration) {
        super.startScroll(startX, startY, dx, dy, (int)(duration * scrollFactor));
    }
}


//----------------------------------------------------------------------------//





IRCTC Share Price Declines by 2% Despite 30% Jump in Q4 Net Profit; Board Announces Dividend of INR 2 per Share

Introduction: The share price of Indian Railway Catering and Tourism Corporation (IRCTC) experienced a decline of 2% in today's trading ...