Tuesday, 22 August 2017

Custom calendar with enable | disable selected Date in android




This Class makes it easy to add an Calendar to your Android application.
Since then many people are asking questions like how to use Decorators and how to disable some dates in . This post answers that.







Here is full code with image and xml file you need to add bg what ever you want . i am not sharing image for that .
package yang.com.paytmintegrating;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

@TargetApi(3)
public class MyCalendarActivity extends Activity implements OnClickListener {
    private static final String tag = "MyCalendarActivity";

    private TextView currentMonth;
    private Button selectedDayMonthYearButton;
    private ImageView prevMonth;
    private ImageView nextMonth;
    private GridView calendarView;
    private GridCellAdapter adapter;
    private Calendar _calendar;
    @SuppressLint("NewApi")
    private int month, year;
    @SuppressWarnings("unused")
    @SuppressLint({"NewApi", "NewApi", "NewApi", "NewApi"})
    private final DateFormat dateFormatter = new DateFormat();
    private static final String dateTemplate = "MMMM yyyy";

    /**     * Called when the activity is first created.     */    @Override    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_calendar_view);

        _calendar = Calendar.getInstance(Locale.getDefault());
        month = _calendar.get(Calendar.MONTH) + 1;
        year = _calendar.get(Calendar.YEAR);
        Log.d(tag, "Calendar Instance:= " + "Month: " + month + " " + "Year: "                + year);

        selectedDayMonthYearButton = (Button) this                .findViewById(R.id.selectedDayMonthYear);
        selectedDayMonthYearButton.setText("Selected: ");

        prevMonth = (ImageView) this.findViewById(R.id.prevMonth);
        prevMonth.setOnClickListener(this);

        currentMonth = (TextView) this.findViewById(R.id.currentMonth);
        currentMonth.setText(DateFormat.format(dateTemplate,
                _calendar.getTime()));

        nextMonth = (ImageView) this.findViewById(R.id.nextMonth);
        nextMonth.setOnClickListener(this);

        calendarView = (GridView) this.findViewById(R.id.calendar);

        // Initialised        adapter = new GridCellAdapter(getApplicationContext(),
                R.id.calendar_day_gridcell, month, year);
        adapter.notifyDataSetChanged();
        calendarView.setAdapter(adapter);
    }

    /**     * @param month     * @param year     */    private void setGridCellAdapterToDate(int month, int year) {
        adapter = new GridCellAdapter(getApplicationContext(),
                R.id.calendar_day_gridcell, month, year);
        _calendar.set(year, month - 1, _calendar.get(Calendar.DAY_OF_MONTH));
        currentMonth.setText(DateFormat.format(dateTemplate,
                _calendar.getTime()));
        adapter.notifyDataSetChanged();
        calendarView.setAdapter(adapter);
    }

    @Override    public void onClick(View v) {
        if (v == prevMonth) {
            if (month <= 1) {
                month = 12;
                year--;
            } else {
                month--;
            }
            Log.d(tag, "Setting Prev Month in GridCellAdapter: " + "Month: "                    + month + " Year: " + year);
            setGridCellAdapterToDate(month, year);
        }
        if (v == nextMonth) {
            if (month > 11) {
                month = 1;
                year++;
            } else {
                month++;
            }
            Log.d(tag, "Setting Next Month in GridCellAdapter: " + "Month: "                    + month + " Year: " + year);
            setGridCellAdapterToDate(month, year);
        }

    }

    @Override    public void onDestroy() {
        Log.d(tag, "Destroying View ...");
        super.onDestroy();
    }

    // Inner Class    public class GridCellAdapter extends BaseAdapter implements OnClickListener {
        private static final String tag = "GridCellAdapter";
        private final Context _context;

        private final List<String> list;
        private static final int DAY_OFFSET = 1;
        private final String[] weekdays = new String[]{"Sun", "Mon", "Tue",
                "Wed", "Thu", "Fri", "Sat"};
        private final String[] months = {"January", "February", "March",
                "April", "May", "June", "July", "August", "September",
                "October", "November", "December"};
        private final int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30,
                31, 30, 31};
        private int daysInMonth;
        private int currentDayOfMonth;
        private int currentWeekDay;
        private Button gridcell;
        private TextView num_events_per_day;
        private final HashMap<String, Integer> eventsPerMonthMap;
        private final SimpleDateFormat dateFormatter = new SimpleDateFormat(
                "dd-MMM-yyyy");

        // Days in Current Month        public GridCellAdapter(Context context, int textViewResourceId,
                               int month, int year) {
            super();
            this._context = context;
            this.list = new ArrayList<String>();
            Log.d(tag, "==> Passed in Date FOR Month: " + month + " "                    + "Year: " + year);
            Calendar calendar = Calendar.getInstance();
            setCurrentDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
            setCurrentWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
            Log.d(tag, "New Calendar:= " + calendar.getTime().toString());
            Log.d(tag, "CurrentDayOfWeek :" + getCurrentWeekDay());
            Log.d(tag, "CurrentDayOfMonth :" + getCurrentDayOfMonth());

            // Print Month            printMonth(month, year);

            // Find Number of Events            eventsPerMonthMap = findNumberOfEventsPerMonth(year, month);
        }

        private String getMonthAsString(int i) {
            return months[i];
        }

        private String getWeekDayAsString(int i) {
            return weekdays[i];
        }

        private int getNumberOfDaysOfMonth(int i) {
            return daysOfMonth[i];
        }

        public String getItem(int position) {
            return list.get(position);
        }

        @Override        public int getCount() {
            return list.size();
        }

        /**         * Prints Month         *         * @param mm         * @param yy         */        private void printMonth(int mm, int yy) {
            Log.d(tag, "==> printMonth: mm: " + mm + " " + "yy: " + yy);
            int trailingSpaces = 0;
            int daysInPrevMonth = 0;
            int prevMonth = 0;
            int prevYear = 0;
            int nextMonth = 0;
            int nextYear = 0;

            int currentMonth = mm - 1;
            String currentMonthName = getMonthAsString(currentMonth);
            daysInMonth = getNumberOfDaysOfMonth(currentMonth);

            Log.d(tag, "Current Month: " + " " + currentMonthName + " having "                    + daysInMonth + " days.");

            GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 1);
            Log.d(tag, "Gregorian Calendar:= " + cal.getTime().toString());

            if (currentMonth == 11) {
                prevMonth = currentMonth - 1;
                daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
                nextMonth = 0;
                prevYear = yy;
                nextYear = yy + 1;
                Log.d(tag, "*->PrevYear: " + prevYear + " PrevMonth:"                        + prevMonth + " NextMonth: " + nextMonth
                        + " NextYear: " + nextYear);
            } else if (currentMonth == 0) {
                prevMonth = 11;
                prevYear = yy - 1;
                nextYear = yy;
                daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
                nextMonth = 1;
                Log.d(tag, "**--> PrevYear: " + prevYear + " PrevMonth:"                        + prevMonth + " NextMonth: " + nextMonth
                        + " NextYear: " + nextYear);
            } else {
                prevMonth = currentMonth - 1;
                nextMonth = currentMonth + 1;
                nextYear = yy;
                prevYear = yy;
                daysInPrevMonth = getNumberOfDaysOfMonth(prevMonth);
                Log.d(tag, "***---> PrevYear: " + prevYear + " PrevMonth:"                        + prevMonth + " NextMonth: " + nextMonth
                        + " NextYear: " + nextYear);
            }

            int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
            trailingSpaces = currentWeekDay;

            Log.d(tag, "Week Day:" + currentWeekDay + " is "                    + getWeekDayAsString(currentWeekDay));
            Log.d(tag, "No. Trailing space to Add: " + trailingSpaces);
            Log.d(tag, "No. of Days in Previous Month: " + daysInPrevMonth);

            if (cal.isLeapYear(cal.get(Calendar.YEAR)))
                if (mm == 2)
                    ++daysInMonth;
                else if (mm == 3)
                    ++daysInPrevMonth;

            // Trailing Month days            for (int i = 0; i < trailingSpaces; i++) {
                Log.d(tag,
                        "PREV MONTH:= "                                + prevMonth
                                + " => "                                + getMonthAsString(prevMonth)
                                + " "                                + String.valueOf((daysInPrevMonth
                                - trailingSpaces + DAY_OFFSET)
                                + i));
                list.add(String
                        .valueOf((daysInPrevMonth - trailingSpaces + DAY_OFFSET)
                                + i)
                        + "-GREY"                        + "-"                        + getMonthAsString(prevMonth)
                        + "-"                        + prevYear);
            }

            // Current Month Days            /******             * @if(i < getCurrentDayOfMonth()) is this use for disable previous date to current date .             *             */            for (int i = 1; i <= daysInMonth; i++) {
                Log.d(currentMonthName, String.valueOf(i) + " "                        + getMonthAsString(currentMonth) + " " + yy);

                if (getCurrentMonth().equalsIgnoreCase("-1")){
                    list.add(String.valueOf(i) + "-GREY" + "-"                            + getMonthAsString(currentMonth) + "-" + yy);
                }else{
                    if (i == getCurrentDayOfMonth()) {
                        list.add(String.valueOf(i) + "-BLUE" + "-"                                + getMonthAsString(currentMonth) + "-" + yy);
                    } else if (i < getCurrentDayOfMonth() && getCurrentMonth().equalsIgnoreCase("0")) {
                        list.add(String.valueOf(i) + "-GREY" + "-"                                + getMonthAsString(currentMonth) + "-" + yy);
                    } else {
                        list.add(String.valueOf(i) + "-WHITE" + "-"                                + getMonthAsString(currentMonth) + "-" + yy);
                    }
                }
            }

            // Leading Month days            for (int i = 0; i < list.size() % 7; i++) {
                Log.d(tag, "NEXT MONTH:= " + getMonthAsString(nextMonth));
                list.add(String.valueOf(i + 1) + "-GREY" + "-"                        + getMonthAsString(nextMonth) + "-" + nextYear);
            }
        }

        /**         * NOTE: YOU NEED TO IMPLEMENT THIS PART Given the YEAR, MONTH, retrieve         * ALL entries from a SQLite database for that month. Iterate over the         * List of All entries, and get the dateCreated, which is converted into         * day.         *         * @param year         * @param month         * @return         */        private HashMap<String, Integer> findNumberOfEventsPerMonth(int year,
                                                                    int month) {
            HashMap<String, Integer> map = new HashMap<String, Integer>();

            return map;
        }

        @Override        public long getItemId(int position) {
            return position;
        }

        @Override        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            if (row == null) {
                LayoutInflater inflater = (LayoutInflater) _context                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(R.layout.screen_gridcell, parent, false);
            }

            // Get a reference to the Day gridcell            gridcell = (Button) row.findViewById(R.id.calendar_day_gridcell);
            gridcell.setOnClickListener(this);

            // ACCOUNT FOR SPACING            Log.d(tag, "Current Day: " + getCurrentDayOfMonth());
            String[] day_color = list.get(position).split("-");
            String theday = day_color[0];
            String themonth = day_color[2];
            String theyear = day_color[3];
            if ((!eventsPerMonthMap.isEmpty()) && (eventsPerMonthMap != null)) {
                if (eventsPerMonthMap.containsKey(theday)) {
                    num_events_per_day = (TextView) row
                            .findViewById(R.id.num_events_per_day);
                    Integer numEvents = (Integer) eventsPerMonthMap.get(theday);
                    num_events_per_day.setText(numEvents.toString());
                }
            }

            // Set the Day GridCell            gridcell.setText(theday);
            gridcell.setTag(theday + "-" + themonth + "-" + theyear);
            Log.d(tag, "Setting GridCell " + theday + "-" + themonth + "-"                    + theyear);

            if (day_color[1].equals("GREY")) {
                gridcell.setTextColor(getResources()
                        .getColor(R.color.lightgray));
                gridcell.setEnabled(false);

            }
            if (day_color[1].equals("WHITE")) {
                gridcell.setTextColor(getResources().getColor(
                        R.color.lightgray02));
            }
            if (day_color[1].equals("BLUE")) {
                gridcell.setTextColor(getResources().getColor(R.color.orrange));
            }
            return row;
        }

        @Override        public void onClick(View view) {
            String date_month_year = (String) view.getTag();
            selectedDayMonthYearButton.setText("Selected: " + date_month_year);
            Log.e("Selected date", date_month_year);
            try {
                Date parsedDate = dateFormatter.parse(date_month_year);
                Log.d(tag, "Parsed Date: " + parsedDate.toString());

            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        public int getCurrentDayOfMonth() {
            return currentDayOfMonth;
        }

        private void setCurrentDayOfMonth(int currentDayOfMonth) {
            this.currentDayOfMonth = currentDayOfMonth;
        }

        public void setCurrentWeekDay(int currentWeekDay) {
            this.currentWeekDay = currentWeekDay;
        }

        public int getCurrentWeekDay() {
            return currentWeekDay;
        }


        /***         * @Value_month = -1 :- previoous month         * @value_month = 0 :- current month         * @value_month = 1 :- next month         */        public String getCurrentMonth() {
            SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
            SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");

            Date date = new Date();

            Log.v("sandeep year ",year+"current Year "+ yearFormat.format(date));
            int temp_month = 0, current_month,current_year,temp_year;
            String Value_month = "-2";
            current_month = Integer.parseInt(dateFormat.format(date));
            current_year= Integer.parseInt(yearFormat.format(date));

            if (month < 10 ) {
                temp_month = Integer.parseInt(new String("0" + month));
            }else{
                temp_month=  month;
            }

            if (year==current_year){
                if (temp_month <current_month && year>=current_year) {
                    Value_month="-1";
                } else if(temp_month==current_month && year>=current_year){
                    Value_month="0";
                }else if (temp_month> current_month && year>=current_year){
                    Value_month="1";
                }
            }else if (year>current_year) {
                Value_month="1";
            }else{
                    Value_month="-1";
                }

            return Value_month;
        }
    }
}




Camera Image Rotate Uri If Required in android

Image captured using camera intent gets rotated on some devices on Android?




Most phone cameras are landscape, meaning if you take the photo in portrait, the resulting photos will be rotated 90 degrees. In this case, the camera software should populate the Exif data with the orientation that the photo should be viewed in.
Note that the below solution depends on the camera software/device manufacturer populating the Exit data, so it will work in most cases, but it is not a 100% reliable solution.













private  
Uri rotateImageIfRequired(Context context,Bitmap img, Uri selectedImage) { // Detect rotation int rotation = getRotation(context, selectedImage); if (rotation != 0) { Matrix matrix = new Matrix(); matrix.postRotate(rotation); Bitmap rotatedImg = Bitmap.createBitmap(img, 0,
          0, img.getWidth(), img.getHeight(), matrix, true);
        img.recycle();
        return getImageUri(context,rotatedImg);
    }
    else{
        return selectedImage;
    }
}

/** * Get the rotation of the last image added. 
* @param context 
* @param selectedImage 
* @return */private  int getRotation(Context context, Uri selectedImage) {

    int rotation = 0;
    ContentResolver content = context.getContentResolver();

    Cursor mediaCursor = content.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[] { "orientation", "date_added" },
            null, null, "date_added desc");

    if (mediaCursor != null && mediaCursor.getCount() != 0) {
        while(mediaCursor.moveToNext()){
            rotation = mediaCursor.getInt(0);
            break;
        }
    }
    mediaCursor.close();
    return rotation;
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(),
                           inImage, "Title", null);
    return Uri.parse(path);
}

Wednesday, 1 March 2017

how to use proguard in Application android studio with Third-Party Libraries

Configering proguard to gradle

ProGuard is a tool to help minify, obfuscate, and optimize your code. It is not only especially useful for reducing the overall size of your Android application as well as removing unused classes and methods that contribute towards the intrinsic 64k method limit of Android applications. Because of the latter issue, ProGuard is often recommended to be used both in development and production especially for larger applications.
ProGuard can be enabled by using the minifyEnabled option for any build type. If you intend to use it for production, it is highly recommended you also enable it on your development. Without fulling testing ProGuard on your development builds, you may encounter unexpected crashes or situations where the app does not function as expected.buildTypes {
  debug {
    minifyEnabled true  // shrink
    useProguard false   // don't obfuscate

    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  }

  release {
    minifyEnabled true  // shrink
    useProguard true    // obfuscate

    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  }
}

Third-Party Libraries

ButterKnife

Note: The following ProGuard lines apply to ButterKnife v7.0. If you are using an older version of ButterKnife, the Proguard rules may be slightly different.
-keep class butterknife.** { *; }
-dontwarn butterknife.internal.**
-keep class **$$ViewBinder { *; }

-keepclasseswithmembernames class * {
    @butterknife.* <fields>;
}

-keepclasseswithmembernames class * {
    @butterknife.* <methods>;
}

Retrofit

-dontwarn retrofit.**
-keep class retrofit.** { *; }
-keepattributes Signature
-keepattributes Exceptions

OkHttp3

-keepattributes Signature
-keepattributes *Annotation*
-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
-dontnote okhttp3.**

# Okio
-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

Gson

-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }

Parcels

keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-keep class org.parceler.Parceler$$Parcels

Retrolambda

-dontwarn java.lang.invoke.*

References



Monday, 6 February 2017

How to pick image from camera or gallery in Android 7.0 ? (Intent-FileProvider) (FileNotFoundException )

file:// scheme is now not allowed to be attached with Intent on targetSdkVersion 24.




put on mainifaest file 



 <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>


this has to be there in your manifest.. for effect in the naugut android 7.0.
Again you need to add provider_paths.xml file in xml.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

//take a photo from gallery
public void gallery() {
    //set UUID to filename
    String PHOTO_FILE_NAME = UUID.randomUUID().toString()+".jpg";
    Utils.putValue(this, Constants.UserPortraitFilePath,PHOTO_FILE_NAME);
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
}
  //take a photo from camera
public void camera() {
    //check sdcard is usable or not
    if (Utils.hasSdcard()) {
        //set UUID to filename
        String PHOTO_FILE_NAME = UUID.randomUUID().toString()+".jpg";
        Utils.putValue(this,Constants.UserPortraitFilePath,PHOTO_FILE_NAME);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        //set file location to DreamGo/Image
        File path = Environment.getExternalStorageDirectory();
        File dir = new File(path, "DreamGo/Image");
        if(!dir.exists())
            dir.mkdirs();
        //Android N need use FileProvider get file 
        //uri because StrictMode System
        //getUriForFile(content,provider author,file)
        Uri photoURI = FileProvider.getUriForFile(context, "dream.go.provider",
                new File(dir.getAbsolutePath(), PHOTO_FILE_NAME));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
        startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
    }else {
        showToast("no storage device");
    }
}

private static final int PHOTO_REQUEST_CAMERA = 0;//camera
private static final int PHOTO_REQUEST_GALLERY = 1;//gallery
private static final int PHOTO_REQUEST_CUT = 2;//image crop
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    String PHOTO_FILE_NAME = Utils.getValue(this, Constants.UserPortraitFilePath);
    File path = Environment.getExternalStorageDirectory();
    File dir = new File(path, "DreamGo/Image");
    if(!dir.exists())
        dir.mkdirs();
    switch (requestCode)
    {
        case PHOTO_REQUEST_GALLERY:
            if (data != null){
                //file from gallery
                File sourceFile = new File(getRealPathFromURI(data.getData()));
                //blank file DreamGo/Image/uuid.jpg
                File destFile = new File(dir.getAbsolutePath(), PHOTO_FILE_NAME);
                Log.e("photo",data.getData().getPath());
                try {
                    //copy file from gallery to DreamGo/Image/uuid.jpg
                    // otherwise crop method can't cut image without write permission
                    copyFile(sourceFile,destFile);
                    //Android N need use FileProvider to get file uri
                    Uri photoURI = FileProvider.getUriForFile(context, "dream.go.provider", destFile);
                    //cut image
                    crop(photoURI);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } 
}

Refer URL :- http://stackoverflow.com/questions/39313752/how-to-pick-image-for-crop-from-camera-or-gallery-in-android-7-0