Pages

Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Wednesday, June 7, 2017

Alertdialog in Android using Kotlin

In this Post, I show you how to display an alert dialog in android using Kotlin and Anko library. In this Demo app will create simple Alert and Alert with Action Button.

Application developing tools :

Android Studio 3.0 Canary 3
Android 25 version
Build Tools Version - 25.0.2
Kotlin Version - 1.1.2-4
Anko Library Version - 0.10.1

Follow Steps :
1. Create New Application
2. Apply plugin and Add dependency in build.gradle file
3. Add button in layout file
4. Add code in Activity

Kotlin Android Extensions plugin (automatically bundled into the Kotlin plugin in Android Studio) solves the issue: replacing findViewById with a brief and straightforward code.

Anko is a Kotlin library which makes Android application development faster and easier. It makes your code clean and easy to read, and lets you forget about rough edges of the Android SDK for Java.
we using Anko Commons: a lightweight library full of helpers for intents, dialogs, logging and so on;.

In General, Simple Text Alert with one button.

 val simpleAlert = AlertDialog.Builder(this@MainActivity).create()
        simpleAlert.setTitle("Alert")
        simpleAlert.setMessage("Show simple Alert")

        simpleAlert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", {
            dialogInterface, i ->
            Toast.makeText(applicationContext, "You clicked on OK", Toast.LENGTH_SHORT).show()
        })

        simpleAlert.show()

Anko Library provide simple way to show simple text Alert with one button.
 alert("Show simple Alert","Alert") {
            positiveButton("OK") {
                toast("You clicked on OK")
            }
        }.show()


let's start!

Create New Application






appyly plugin and add dependency in app-module build.gradle file

 

Apply Plugin
apply plugin: 'kotlin-android-extensions'
Add Dependency (Anko Commons Library)
    compile "org.jetbrains.anko:anko-commons:0.10.1"

Layout Files : main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context="com.limbani.alertdialogdemo.MainActivity">

    <Button
        android:id="@+id/simpleAlert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Simple Alert" />

    <Button
        android:id="@+id/alertTwoButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Alert with two Button" />

    <Button
        android:id="@+id/alertThreeButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Alert with three Button" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:text="Using Anko Library Example" />

    <Button
        android:id="@+id/ankoSimpleAlert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Simple Alert" />

    <Button
        android:id="@+id/ankoAlertTwoButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Alert with two Button" />

    <Button
        android:id="@+id/ankoAlertThreeButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Alert with three Button" />
</LinearLayout>

Activity :


MainActivity.kt here first three button show to simple way to show alert dialog and below three button show the alert dialog using Anko Library
package com.limbani.alertdialogdemo

import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.alert
import org.jetbrains.anko.toast

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        simpleAlert.setOnClickListener {
            showSimpleAlert()
        }

        alertTwoButton.setOnClickListener {
            showAlertWithTwoButton()
        }

        alertThreeButton.setOnClickListener {
            showAlertWithThreeButton()
        }

        //Anko Example Button here
        ankoSimpleAlert.setOnClickListener {
            ankoShowSimpleAlert()
        }

        ankoAlertTwoButton.setOnClickListener {
            ankoShowAlertWithTwoButton()
        }

        ankoAlertThreeButton.setOnClickListener {
            ankoShowAlertWithThreeButton()
        }
    }

    //Anko Library Example code here
    private fun ankoShowAlertWithThreeButton() {
        alert("Show Alert with three Button", "Alert") {
            positiveButton("POSITIVE") {
                toast("You clicked on POSITIVE Button")
            }
            negativeButton("NEGATIVE") {
                toast("You clicked on NEGATIVE Button")
            }
            neutralPressed("NEUTRAL") {
                toast("You clicked on NEUTRAL Button")
            }
        }.show()
    }

    private fun ankoShowAlertWithTwoButton() {
        alert("how Alert with two Button","Alert") {
            positiveButton("YES") {
                toast("You clicked on YES")
            }
            negativeButton("NO") {
                toast("You clicked on NO")
            }
        }.show()
    }

    private fun ankoShowSimpleAlert() {
        alert("Show simple Alert","Alert") {
            positiveButton("OK") {
                toast("You clicked on OK")
            }
        }.show()
    }

    //General code here
    private fun showAlertWithThreeButton() {
        val alertDilog = AlertDialog.Builder(this@MainActivity).create()
        alertDilog.setTitle("Alert")
        alertDilog.setMessage("Show Alert with three Button")

        alertDilog.setButton(AlertDialog.BUTTON_POSITIVE, "POSITIVE", {
            dialogInterface, i ->
            Toast.makeText(applicationContext, "You clicked on POSITIVE Button", Toast.LENGTH_SHORT).show()
        })

        alertDilog.setButton(AlertDialog.BUTTON_NEGATIVE, "NEGATIVE", {
            dialogInterface, j ->
            Toast.makeText(applicationContext, "You clicked on NEGATIVE Button", Toast.LENGTH_SHORT).show()
        })
        alertDilog.setButton(AlertDialog.BUTTON_NEUTRAL, "NEUTRAL", {
            dialogInterface, k ->
            Toast.makeText(applicationContext, "You clicked on NEUTRAL Button", Toast.LENGTH_SHORT).show()
        })

        alertDilog.show()
    }

    private fun showAlertWithTwoButton() {
        val alertDilog = AlertDialog.Builder(this@MainActivity).create()
        alertDilog.setTitle("Alert")
        alertDilog.setMessage("Show Alert with two Button")

        alertDilog.setButton(AlertDialog.BUTTON_POSITIVE, "YES", {
            dialogInterface, i ->
            Toast.makeText(applicationContext, "You clicked on YES", Toast.LENGTH_SHORT).show()
        })

        alertDilog.setButton(AlertDialog.BUTTON_NEGATIVE, "NO", {
            dialogInterface, i ->
            Toast.makeText(applicationContext, "You clicked on NO", Toast.LENGTH_SHORT).show()
        })

        alertDilog.show()
    }

    private fun showSimpleAlert() {

        val simpleAlert = AlertDialog.Builder(this@MainActivity).create()
        simpleAlert.setTitle("Alert")
        simpleAlert.setMessage("Show simple Alert")

        simpleAlert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", {
            dialogInterface, i ->
            Toast.makeText(applicationContext, "You clicked on OK", Toast.LENGTH_SHORT).show()
        })

        simpleAlert.show()
    }
}

Test (Screenshot)




Resource
https://kotlinlang.org
Android Developer Blog
Anko Library
 
Thanks for reading this post.
Enjoy:)

Tuesday, June 6, 2017

Hello World App in Kotlin Android

Kotlin is a programing language and now officially support for Android Application development. For more Details for Kotlin check Android Developer Blog and Kotlin Documentation.
The Kotlin plug-in is now bundled with Android Studio 3.0. Also available for older version see my last post how to setup Kotlin Plugin in Android Studio.

Here simple Example app of the Say Hello World in Kotlin language. In App show one TextView and One Button click to show Toast to Say Hello World. Follow below steps to run first Hello World App.

Create New Application


Open Android Studio File>New>New Project



Select Include Kotlin support check box and click Next button.(This option available in Android Studio 3.0 Version.)


Select Phone and Tablet, Minimum SDK version and Click Next button.


Select Empty Activity and click Next button.


If you want to change Activity name then change here otherwise go with default MainActivity name and click Finish Button

After you need to check Kotlin plug-in in both root project and app-model build.gradle file.
root project build.gradle
 
buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


App-model build.gradle file add two apply plugin 'kotlin-android', 'kotlin-android-extensions' and add one dependency compile "org.jetbrains.anko:anko-commons:0.10.1".

Kotlin Android Extensions is a compiler extension that allows you to get rid of findViewById() calls in your code and to replace them with synthetic compiler-generated properties.

org.jetbrains.anko:anko-commons:0.10.1 - Anko is a Kotlin library which makes Android application development faster and easier. It makes your code clean and easy to read, and lets you forget about rough edges of the Android SDK for Java. Anko Commons is a lightweight library full of helpers for intents, dialogs, logging and so on;
 
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.limbani.helloworld"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:25.3.1'
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile "org.jetbrains.anko:anko-commons:0.10.1"
}

MainActivity.kt file

package com.limbani.helloworld

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.toast

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn_hello.setOnClickListener {
            toast("Say Hello World")
            // For long toast
            // longToast("Say Hello World")
            printButtonClickLog()
        }
    }

    private fun printButtonClickLog() {
        Log.i("MainActivity", "Hello Button Clicked")
    }
}

activity_main.xml layout file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.limbani.helloworld.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:text="Hello World!"
        android:textSize="20sp" />

    <Button
        android:id="@+id/btn_hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Say Hello"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.helloworld">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshot of the app.


Resource
https://kotlinlang.org
Android Developer Blog
Anko Library
 
Thanks for reading this post.

Setup Kotlin Plugin for Android Studio 2.3

AndroidDev annouce officially adding support for the Kotlin programing language. Check here Android Developer Blog.

The Kotlin plug-in is now bundled with Android Studio 3.0. Kotlin was developed by JetBrains, the same people who created IntelliJ. Also Kotlin pluging available for Android Studio 2.3.2 version. See below how to add plugin Kotlin in Android Studio lower vsersion.

Let's Start to setup

Install Kotlin Plugin for Android Studio


In Windows PC : Open File>Setting>Plugins>Browse Repositories (Preferences > Plugins > Browse Repositories). Search Kotlin and Install.

 
When the install is complete, you will need to restart Android Studio to apply the new plugin.

Apply Kotlin Plugin to the project


First of all create a new Android Project. File>New>New Project and follow through project creation steps.

Next step to apply the Kotlin Plugin to both build.gradle files at the Project level and app-module level. There is an automated tools to do this, but sometimes the manual process of applying the plugin in our build.gradle files.

First we need to add the plugin to the root project build.gradle.

 
buildscript {
    ext.kotlin_version = "1.1.2-4" // replace with the latest (stable) version: https://github.com/JetBrains/kotlin/releases/latest

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

Second we need to add the plugin to the app-module build.gradle. To add apply plugin : kotlin-android in build.gradle file

  apply plugin: 'com.android.application'
  apply plugin: 'kotlin-android' // apply kotlin android plugin

Convert Java Code to Kotlin


We setup all we need, but our Empty Activity still in java. Here show how to convert java file to Kotline. Way to convert java file to Koitlin Select Code>Convert Java File to Kotlin or use shortcut - control + Alt + Shift + K  (Replace control to Command if you are using MAC)

MainActivity.java
package com.limbani.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

After converting code to Kotlin. MainActivity.kt look like below
package com.limbani.helloworld

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Thanks for reading this post. I will be writing tutorial for Kotlin language.

Resource
https://kotlinlang.org
Android Developer Blog
 

Wednesday, June 22, 2016

Firebase Analytics integrate in Android


Hello, Today writing post for how to integrate Firebase Analytics in Android Application. Firebase Analytics is a free to analytic for android application.

1. Download firebase SDK  (Google Play services SDK from the Android SDK Manager)
2. Create a project in the Firebase Consol and download json file
3. Android studio 1.5 or latter and Android 2.3 or newer.
4. Check firebase report.


1. Firebase SDK : First update your Google Play services from the Android SDK Manager.

Check in Extras

Google Play Services installed rev 30 or up
Google Repository installed rev 26  or up. both are required to updated.


2. Create Project in Firebase Consol

* Select Add Firebase to your android App



 *  Add Package name here and click ADD APP button. Here make sure to add that package name to use in application.

* Download google-services.json File and click continue




*Here you can see to how to init Firebase sdk in android application. Click Finish


3. Create Application in Android studio and integrate Firebase SDK

 In Android studio select New > New Project
* Add Application and package name (package name is same as added Firebase project)


 * Select here Android minimum sdk version


* Select Empty Activity


* Enter Activity Name


* Now Copy google-services.json file and past to project's module folder "app/" folder





*  Add rules to your root-level build.gradle file, to include the google-services plugin:


* Add dependency for Firebase Analytics to your app-level build.gardle file and add plugin bottom
after add dependency and plugin then click Sync Now Button





*Create App.java and create FirebaseAnalytics object in Application class


 
package com.limbani.firebaseanalyticsdemo;

import android.app.Application;

import com.google.firebase.analytics.FirebaseAnalytics;


public class App extends Application {

    private static FirebaseAnalytics mFirebaseAnalytics;
    @Override
    public void onCreate() {
        super.onCreate();
        this.mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
    }

    public static FirebaseAnalytics getFirebaseAnalytics() {
        return mFirebaseAnalytics;
    }
}

* MainActivity.java clas and add Firebase LogEven see in code. You can add more Event log see in FirebaseAnalytics.Event


package com.limbani.firebaseanalyticsdemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.google.firebase.analytics.FirebaseAnalytics;

public class MainActivity extends AppCompatActivity {

    private Button btn_click;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_click = (Button) findViewById(R.id.btn_click);

        btn_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Here Add Firebase LogEvent
                Bundle bundle = new Bundle();
                bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "btn_click");
                bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Next Activity");
                bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "Button");
                App.getFirebaseAnalytics().logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

                startActivity(new Intent(MainActivity.this, SecondActivity.class));
            }
        });
    }
}


* activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.limbani.firebaseanalyticsdemo.MainActivity">

    <Button
        android:id="@+id/btn_click"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Next Activity" />
</RelativeLayout<

* Create SeconActivity.java class and activity_second.xml file


package com.limbani.firebaseanalyticsdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }
}

* activity_second.xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.limbani.firebaseanalyticsdemo.SecondActivity">

</RelativeLayout>



* Edit AndroidManifest.xml File


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.firebaseanalyticsdemo">

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

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity"></activity>
    </application>

</manifest>


4. Check Report in Firebase :



Error Resolve

1. If you find error while sync time like faild to resolve firebase then you need to check 1st point to Google Play Service updated or not.


2. Execution faild for task ':app:processDebugGoogleServices'.
> File google-services.json is missing. ......
getting this error then you are missing to add google-services.json or miss placed this file. check 3rd point

Download Source code

Thank you :)

Wednesday, May 25, 2016

How to check FingerPrint feature available in android?

In android API 23 added Finger Print feature for lock or unlock your phone, authorize purchases, or sign in to apps.
So how to check fingerprint feature available or not in android device? check below.

Method 1 :
  if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
      Toast.makeText(this, "Finger print not supported", Toast.LENGTH_SHORT).show();
  }

Method 2 :
 
   FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(Context.FINGERPRINT_SERVICE);
   if (!fingerprintManager.isHardwareDetected()) {
       // Device doesn't support fingerprint authentication
       Toast.makeText(this, "Device doesn't support fingerprint authentication", Toast.LENGTH_SHORT).show();
   } else if (!fingerprintManager.hasEnrolledFingerprints()) {
       // User hasn't enrolled any fingerprints to authenticate with
      Toast.makeText(this, "User hasn't enrolled any fingerprints to authenticate with", Toast.LENGTH_SHORT).show();
   } else {
      // Everything is ready for fingerprint authentication
      Toast.makeText(this, "Everything is ready for fingerprint authentication", Toast.LENGTH_SHORT).show();
   }

This method required USE_FINGERPRINT permision. Add in Menifest file.
    
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
Thank you :)

Saturday, June 13, 2015

How to format datetime to RelativeTime from now in android


Hello everyone,

Today I am write post for display Relative Time from now in application.
Some application we need to show Datetime in relative to now. Application like chat, post Artical and showing news headline.


Relative time from now mean, examples below:

10 second ago
1 min ago
5 hours ago
2 days ago


I find out some way to format Datetime to Relative time from now.

1. Using DateUtils API
2. Using android-ago library


1. Using DateUtils API 

First understand below methods and it's parameters

Method 1 : 


public static CharSequence getRelativeTimeSpanString (long time, long now, long minResolution)

Returns a string describing 'time' as a time relative to 'now'.
Time spans in the past are formatted like "42 minutes ago". Time spans in the future are formatted like "in 42 minutes".

Parameters:

time : the time to describe, in milliseconds
now : the current time in milliseconds
minResolution : the minimum timespan to report.
For example, a time 3 seconds in the past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of 0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS

See below Example code and Output one by one.
If you have Date-time is a string then first convert in Date Object see in code.


Exmaple  :


try {
 long now = System.currentTimeMillis();
 String datetime1 = "06/12/2015 03:58 PM";
 SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
 Date convertedDate = dateFormat.parse(datetime1);
  
 CharSequence relavetime1 = DateUtils.getRelativeTimeSpanString(
  convertedDate.getTime(),
        now,
        DateUtils.SECOND_IN_MILLIS);
   
 txt_time.append(relavetime1+"\n\n");
 System.out.println(relavetime1);
} catch (ParseException e) {
 e.printStackTrace();
}

If current Time is a "06/12/2015 03:58:10 PM" then output like below because we pass minResolutions parameters is SECOND_IN_MILLIS.


 Output : 
 10 second ago


See below case after change minResolutions parameters


Case 1. MINUTE_IN_MILLIS then output : "0 minutes ago"
Case 2. HOUR_IN_MILLIS then output : "0 hours ago"
Case 3. DAY_IN_MILLIS then output : "Today"
Case 4. WEEK_IN_MILLIS then output : "12 Jun 2015"


Method 2:


public static CharSequence getRelativeTimeSpanString (long time, long now, long minResolution, int flags)

Returns a string describing 'time' as a time relative to 'now'.
Time spans in the past are formatted like "42 minutes ago". Time spans in the future are formatted like "in 42 minutes".
Can use FORMAT_ABBREV_RELATIVE flag to use abbreviated relative times, like "42 mins ago".

Parameters:

time the time to describe, in milliseconds
now : the current time in milliseconds
minResolution : the minimum timespan to report.
For example, a time 3 seconds in the past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of 0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS
flags a bit mask of formatting options, such as FORMAT_NUMERIC_DATE or FORMAT_ABBREV_RELATIVE


Example code  1 :


try {
 long now = System.currentTimeMillis();
 String datetime1 = "06/12/2015 03:58 PM";
 SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
 Date convertedDate = dateFormat.parse(datetime1);
  
 CharSequence relavetime1 = DateUtils.getRelativeTimeSpanString(
  convertedDate.getTime(),
        now,
        DateUtils.SECOND_IN_MILLIS,
        DateUtils.FORMAT_ABBREV_RELATIVE);
   
 txt_time.append(relavetime1+"\n\n");
 System.out.println(relavetime1);
} catch (ParseException e) {
 e.printStackTrace();
}

If current Time is a "06/12/2015 03:58:10 PM" then output like below because we pass minResolutions parameters is SECOND_IN_MILLIS.


 Output : 
 10 secs ago


See below case if change minResolutions parameters


Case 1. MINUTE_IN_MILLIS then output : "0 mins ago"
Case 2. HOUR_IN_MILLIS then output : "0 hours ago"
Case 3. DAY_IN_MILLIS then output : "Today"
Case 4. WEEK_IN_MILLIS then output : "12 June"


Example code 2 :
If target datetime is "06/12/2015 06:00 PM" and current time is "06/12/2015 05:15 PM" output shows like below



Case 1. SECOND_IN_MILLIS then output : "in 45 mins" 
Case 2. MINUTE_IN_MILLIS then output : "in 45 mins"
Case 3. HOUR_IN_MILLIS then output : "in 0 hours"
Case 4. DAY_IN_MILLIS then output : "Today"
Case 5. WEEK_IN_MILLIS then output : "12 June"

2. Use Library - Android Ago

We can use this library for relative time from now.
It contain custom TextView class and auto refresh Relative time.

Just add custom TextView on your xml layout and like below.


<com.github.curioustechizen.ago.RelativeTimeTextView
    android:id="@+id/timestamp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/margin_primary" />


Add below code in your activity


RelativeTimeTextView tvTimestamp = (RelativeTimeTextView) convertView.findViewById(R.id.timestamp);
tvTimestamp.setReferenceTime(<here pass timestamp>);


that's it.
More information about Library See Here
Thank you :)


Thursday, April 23, 2015

Android BluetoothAdapter state change listner


In this post I have write code for BuletoothAdapter state change listener. When we use Bluetooth in application then we can check bluetooth is On or Off. But on run time we can use BroadcardReceiver.

Register a BroadcastReceiver to listen for any state changes of the BluetoothAdapter.


Add below code in Activity Class.

Create BroadcastReciver instance variable in your activity (also you can create separate class file)


private final BroadcastReceiver mbluetoothStateReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
   final String action = intent.getAction();

   if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
    final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
    switch (state) {
    case BluetoothAdapter.STATE_OFF:
     Toast.makeText(getApplicationContext(), "Bluetooth off", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_TURNING_OFF:
     Toast.makeText(getApplicationContext(), "Turning Bluetooth off...", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_ON:
     Toast.makeText(getApplicationContext(), "Bluetooth on", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_TURNING_ON:
     Toast.makeText(getApplicationContext(), "Turning Bluetooth on...", Toast.LENGTH_SHORT).show();
     break;
    }
   }
  }
 };


and Then add code to Register and Unregister BroadcastReceiver as follows


@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_bluetoothlistner);
 
  // Register broadcasts receiver for bluetooth state change
  IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
  registerReceiver(mbluetoothStateReceiver, filter);
 }
 
 @Override
 public void onDestroy() {
  super.onDestroy();
  // Unregister broadcast listeners
  unregisterReceiver(mbluetoothStateReceiver);
 }


Full code of the Activity

public class BluetoothStateListenerActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_bluetoothlistner);

  // Register broadcasts receiver for bluetooth state change
  IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
  registerReceiver(mbluetoothStateReceiver, filter);
 }

 private final BroadcastReceiver mbluetoothStateReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
   final String action = intent.getAction();

   if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
    final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
    switch (state) {
    case BluetoothAdapter.STATE_OFF:
     Toast.makeText(getApplicationContext(), "Bluetooth off", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_TURNING_OFF:
     Toast.makeText(getApplicationContext(), "Turning Bluetooth off...", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_ON:
     Toast.makeText(getApplicationContext(), "Bluetooth on", Toast.LENGTH_SHORT).show();
     break;
    case BluetoothAdapter.STATE_TURNING_ON:
     Toast.makeText(getApplicationContext(), "Turning Bluetooth on...", Toast.LENGTH_SHORT).show();
     break;
    }
   }
  }
 };

 @Override
 public void onDestroy() {
  super.onDestroy();
  // Unregister broadcast listeners
  unregisterReceiver(mbluetoothStateReceiver);
 }
}


Add below permission on AndroidManifest.xml file

<uses-permission android:name="android.permission.BLUETOOTH" />

Thank you :)

Wednesday, December 31, 2014

Android Action Bar Style Generator online

Online Tool

Android Action Bar Style Generator online

Its an amazing tool to lets you customize your action bar with preview and easy to use.

"The Android Action Bar Style Generator allows you to easily create a simple, attractive and seamless custom action bar style for your Android application. It will generate all necessary nine patch assets plus associated XML drawables and styles which you can copy straight into your project. "



Output we can download zip folder.



Open  Android Action Bar Style Generator

Thanks enjoy :)

Saturday, November 8, 2014

Show/Hide Password text in Android (Password type EditText View)


Sometime, we have password field in android appliction. In some special case we want show and hide password. see below simple tutorial demo for that.

1. Create XML file in layout folder "res/layout/activity_hideshowpassword.xml".

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#99afafaf"
        android:gravity="center"
        android:padding="10dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:shadowColor="@android:color/black"
            android:shadowDx="0.5"
            android:shadowDy="0.5"
            android:shadowRadius="1"
            android:text="Show/Hide Password"
            android:textColor="@android:color/white"
            android:textSize="22sp"
            android:textStyle="bold" />
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="20dp"
        android:text="Password"
        tools:context=".MainActivity" />

    <EditText
        android:id="@+id/edt_Password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="14dp"
        android:ems="10"
        android:inputType="textPassword" >

        <requestFocus />
    </EditText>

    <CheckBox
        android:id="@+id/chbox_showpassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="8dp"
        android:text="Show Password" />

</LinearLayout>


2. Create on activity java file "ShowHidePasswordActivity.java"

import android.app.Activity;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

public class ShowHidePasswordActivity extends Activity {

 private EditText edt_password;
 private CheckBox mCbShowPwd;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  setContentView(R.layout.activity_hideshowpassword);

  edt_password = (EditText) findViewById(R.id.edt_Password);
  mCbShowPwd = (CheckBox) findViewById(R.id.chbox_showpassword);

  //Add onCheckedListener
  mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (!isChecked) {
     //Show password
     edt_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
    } else {
     //Hide password
     edt_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
    }
   }
  });
 }
}




3.Add ShowHidePasswordActivity activity class in AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ShowHidePasswordActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 


4. ScreenShot




Download APK file Here
Enjoy :)
Thank you.

Friday, October 31, 2014

Image Cropping in android : While capture image or select from gallery

Hello everyone, I write example code for capture & select image from gallery and cropping image in android. see below example code.

1. Create XML file in layout folder "res/layout/activity_main.xml".


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_select_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:text="Select Image" />

    <ImageView
        android:id="@+id/img_photo"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginTop="10dp"
        android:scaleType="fitXY" />

</LinearLayout>
2. Create XML file in layout folder "res/layout/croping_selector.xml".


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/img_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/txt_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text=""
        android:textColor="@android:color/black"
        android:textSize="16sp" />

</LinearLayout>

3. Create an activity Java file "MainActivity.java".


package com.limbani.imagecropping;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private final static int REQUEST_PERMISSION_REQ_CODE = 34;
        private static final int CAMERA_CODE = 101, GALLERY_CODE = 201, CROPING_CODE = 301;

        private Button btn_select_image;
        private ImageView imageView;
        private Uri mImageCaptureUri;
        private File outPutFile = null;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            outPutFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

            btn_select_image = (Button) findViewById(R.id.btn_select_image);
            imageView = (ImageView) findViewById(R.id.img_photo);

            btn_select_image.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    selectImageOption();
                }
            });
        }

        private void selectImageOption() {
            final CharSequence[] items = { "Capture Photo", "Choose from Gallery", "Cancel" };

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Add Photo!");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {

                    if (items[item].equals("Capture Photo")) {

                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
                        mImageCaptureUri = Uri.fromFile(f);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                        startActivityForResult(intent, CAMERA_CODE);

                    } else if (items[item].equals("Choose from Gallery")) {

                        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, GALLERY_CODE);

                    } else if (items[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }

    @Override
    protected void onResume() {
        super.onResume();
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_REQ_CODE);
            return;
        }
    }

    @Override
    public void onRequestPermissionsResult(final int requestCode, final @NonNull String[] permissions, final @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_REQ_CODE: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Permission granted.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Permission denied.", Toast.LENGTH_SHORT).show();
                }
                break;
            }
        }
    }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && null != data) {

                mImageCaptureUri = data.getData();
                System.out.println("Gallery Image URI : "+mImageCaptureUri);
                CropingIMG();

            } else if (requestCode == CAMERA_CODE && resultCode == Activity.RESULT_OK) {

                System.out.println("Camera Image URI : "+mImageCaptureUri);
                CropingIMG();
            } else if (requestCode == CROPING_CODE) {

                try {
                    if(outPutFile.exists()){
                        Bitmap photo = decodeFile(outPutFile);
                        imageView.setImageBitmap(photo);
                    }
                    else {
                        Toast.makeText(getApplicationContext(), "Error while save image", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        private void CropingIMG() {

            final ArrayList<cropingoption> cropOptions = new ArrayList<cropingoption>();

            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setType("image/*");

            List<resolveinfo> list = getPackageManager().queryIntentActivities( intent, 0 );
            int size = list.size();
            if (size == 0) {
                Toast.makeText(this, "Cann't find image croping app", Toast.LENGTH_SHORT).show();
                return;
            } else {
                intent.setData(mImageCaptureUri);
                intent.putExtra("outputX", 512);
                intent.putExtra("outputY", 512);
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("scale", true);

                //TODO: don't use return-data tag because it's not return large image data and crash not given any message
                //intent.putExtra("return-data", true);

                //Create output file here
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile));

                if (size == 1) {
                    Intent i   = new Intent(intent);
                    ResolveInfo res = (ResolveInfo) list.get(0);

                    i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));

                    startActivityForResult(i, CROPING_CODE);
                } else {
                    for (ResolveInfo res : list) {
                        final CropingOption co = new CropingOption();

                        co.title  = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                        co.icon  = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                        co.appIntent= new Intent(intent);
                        co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                        cropOptions.add(co);
                    }

                    CropingOptionAdapter adapter = new CropingOptionAdapter(getApplicationContext(), cropOptions);

                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Choose Croping App");
                    builder.setCancelable(false);
                    builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
                        public void onClick( DialogInterface dialog, int item ) {
                            startActivityForResult( cropOptions.get(item).appIntent, CROPING_CODE);
                        }
                    });

                    builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel( DialogInterface dialog ) {

                            if (mImageCaptureUri != null ) {
                                getContentResolver().delete(mImageCaptureUri, null, null );
                                mImageCaptureUri = null;
                            }
                        }
                    } );

                    AlertDialog alert = builder.create();
                    alert.show();
                }
            }
        }

        private Bitmap decodeFile(File f) {
            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 = 512;
                int width_tmp = o.outWidth, height_tmp = o.outHeight;
                int scale = 1;
                while (true) {
                    if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_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) {
            }
            return null;
        }
    }


4. Create Java file "CropingOption.java"


package com.limbani.imagecropping;

import android.content.Intent;
import android.graphics.drawable.Drawable;

public class CropingOption {
    public CharSequence title;
    public Drawable icon;
    public Intent appIntent;
}

5. Create Java file "CropingOptionAdapter.java"


package com.limbani.imagecropping;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CropingOptionAdapter extends ArrayAdapter {
    private ArrayList mOptions;
    private LayoutInflater mInflater;

    public CropingOptionAdapter(Context context, ArrayList options) {
        super(context, R.layout.croping_selector, options);

        mOptions  = options;

        mInflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup group) {
        if (convertView == null)
            convertView = mInflater.inflate(R.layout.croping_selector, null);

        CropingOption item = (CropingOption) mOptions.get(position);

        if (item != null) {
            ((ImageView) convertView.findViewById(R.id.img_icon)).setImageDrawable(item.icon);
            ((TextView) convertView.findViewById(R.id.txt_name)).setText(item.title);

            return convertView;
        }

        return null;
    }
}

6. Add your activity class and user permission in "AndroidManifest.xml".


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.limbani.imagecropping">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


7. ScreenShot".







Thanks :)
Download Code