In this tutorial, we will learn how to pin Latitude and Longitude or Co-Ordinates in External maps in Xamarin.Forms. The Co-Ordinates a...

Pin Coordinates To External Maps In Xamarin.Forms Pin Coordinates To External Maps In Xamarin.Forms

A blog about android developement


In this tutorial, we will learn how to pin Latitude and Longitude or Co-Ordinates in External maps in Xamarin.Forms. The Co-Ordinates are pinned with Google Maps in Android and Apple Maps in iOS. 

External Maps Plugin: 

This plugin is used to pin specific geo-location and Navigating user from current location to that specified location. James Montemongo had written a plugin to navigate users. But this plugin doesn’t have functionality to pin the specified location. So I have rewritten the plugin and you can find the plugin from GitHub and Nuget. 

Platform Support: 

It has the support for Android and iOS Platforms. 
  • Xamarin.iOS - iOS 7+ 
  • Xamarin.Android - API 10+ 

Coding Part: 

Steps: 

I have split this part into 3 steps as in the following. 
Step 1: Creating new Xamarin.Forms Projects. 
Step 2: Setting up the plugin for Xamarin.Forms Application. 
Step 3: Implementing the functionality to pin location.

Step 1

Create New Project by Selecting New -> Project -> Select Xamarin Cross Platform App and Click OK.
Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .Net Standard and Click OK.

Step 2

We will start coding for External Maps. Create New Xamarin Forms Project. Open Nuget Package Manager against the solution and do search for External Maps Plugin or Paste the following Nuget Installation.
Install-Package ExternalMapsPlugin -Version 1.0.0
Add this Plugin against Android & iOS Platforms.

Step 3

Open your XAML file and paste the following code. I have added a clicked event for the button to trigger or pin the specific co-ordinate to the map.
<code class="xml language-xml"><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MapsPluginSample"
             x:Class="MapsPluginSample.MainPage">

 <Button Text="Pin Co-Ordinate" 
            Clicked="OnButtonClicked"
            VerticalOptions="Center" 
            HorizontalOptions="Center" />

</ContentPage>
Open your MainPage.xaml.cs and add button click as shown below.
private void OnButtonClicked(object sender, EventArgs e)
{
 
}

Add Pinto method to locate co-ordinates in External Maps.

private void OnButtonClicked(object sender, EventArgs e)
{
       CrossMapsPlugin.Current.PinTo("Vannarapettai", 10.7653, 79.0687, 8);
}
Here, Vannarapettai is the label for your location 10.7653, 79.0687 is Latitude & Longitude of the location respectively. 8 is the zoom level of your Application.

Demo

The Following screenshots demonstrates how this plugin works. You can download the source code of this article and post your comments about this article and Plugin.

AndroidiOS

Download Code

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

Introduction: In this article, we will learn how to send Mail directly from Xamarin Android Application without any Intents. For this, ...

How to Send Mail directly from Android Application in Xamarin.Android How to Send Mail directly from Android Application in Xamarin.Android

A blog about android developement



Introduction:

In this article, we will learn how to send Mail directly from Xamarin Android Application without any Intents. For this, we can MailKit to send mail directly.

MailKit:

MailKit is a cross-platform mail client library built on top of MimeKit. MailKit is a personal open source project that I have put thousands of hours into perfecting with the goal of making it the very best email framework for .NET.

Coding Part:

Steps:

I have split this article into 3 steps as in the following.
Step 1: Creating new Xamarin.Android Projects.
Step 2: Setting up the plugin for Xamarin.Android Application.
Step 3: Implementing Mail functionalities in Xamarin.Android Application.

Step 1: Creating new Xamarin.Android Projects

Create New Project by Selecting New  Project  Select Android App and Click OK.

fig1

Step 2: Setting up the plugin for Xamarin.Android Application

In this step, we will include the Mailkit plugin for Xamarin.Android Project. Open Nuget Package Manager against the project and do search for Mailkit and click install to add the library or Paste the following in Package Manager Console to install the Nuget plugin.

Install-Package MailKit
fig2

Step 3: Implementing Mail Functionalities in Xamarin.Android Application

In this part, we will see how to implement Mail functions to send mail.

  • Open your MainActivity.cs and Import the Following Packages.
    using MimeKit;
    using MailKit.Net.Smtp;
    
  • Then add/create an Async task class named as “MailAsyncTask” and add implement the override functions.
    • OnPreExecute
    • OnPostExecute
    • DoInBackground
  • Then add/paste the following code in DoInBackground method.
    var message = new MimeMessage();
    message.From.Add(new MailboxAddress("From", mainActivity.edtFrom.Text));
    message.To.Add(new MailboxAddress("To", mainActivity.edtTo.Text));
    message.Subject = mainActivity.edtSubject.Text;
    
    message.Body = new TextPart("plain")
    {
     Text = mainActivity.edtMessage.Text
    };
    
    using (var client = new SmtpClient())
    {
     // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
     client.ServerCertificateValidationCallback = (s, c, h, e) => true;
    
     client.Connect(host, port, false);
    
     // Note: only needed if the SMTP server requires authentication
     client.Authenticate(username, password);
     client.Send(message);
     client.Disconnect(true);
    }
  • Here, we should provide host address, port and username & password if the SMTP server needs authentication.
  • The Mail Connections needed to be run with separate thread. So, I had done the call with “AsyncTask”. You can find the full code below.

Full code of the MailAsyncClass:

The following code shows how to implement Direct Mail functions in Xamarin.Android with AsyncTask.

class MailAsyncTask : AsyncTask
{
 string username = "mail-id or username", password = "password", host = "smtp.gmail.com";
 int port = 25;
 MainActivity mainActivity;
 ProgressDialog progressDialog;

 public MailAsyncTask(MainActivity activity)
 {
  mainActivity = activity;
  progressDialog = new ProgressDialog(mainActivity);
  progressDialog.SetMessage("Sending...");
  progressDialog.SetCancelable(false);
 }

 protected override void OnPreExecute()
 {
  base.OnPreExecute();
  progressDialog.Show();
 }

 protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
 {
  try
  {
   var message = new MimeMessage();
   message.From.Add(new MailboxAddress("From", mainActivity.edtFrom.Text));
   message.To.Add(new MailboxAddress("To", mainActivity.edtTo.Text));
   message.Subject = mainActivity.edtSubject.Text;

   message.Body = new TextPart("plain")
   {
    Text = mainActivity.edtMessage.Text
   };

   using (var client = new SmtpClient())
   {
    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

    client.Connect(host, port, false);

    // Note: only needed if the SMTP server requires authentication
    client.Authenticate(username, password);
    client.Send(message);
    client.Disconnect(true);
   }
   return "Successfully Sent";
  }
  catch (System.Exception ex)
  {
   return ex.Message;
  }
 }

 protected override void OnPostExecute(Java.Lang.Object result)
 {
  base.OnPostExecute(result);
  progressDialog.Dismiss();
  mainActivity.edtFrom.Text = null;
  mainActivity.edtTo.Text = null;
  mainActivity.edtSubject.Text = null;
  mainActivity.edtMessage.Text = null;
  Toast.MakeText(mainActivity, "Email Succesfully Sent...", ToastLength.Short).Show();
 }
}

The Mail class can be executed by the following code

new MailAsyncTask(this).Execute();

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

In this article, we will learn to load Base64 String Images into Images in Xamarin.Forms without using any External Plugins like FFMpe...

Loading Base64 Images In Xamarin.Forms Loading Base64 Images In Xamarin.Forms

A blog about android developement


In this article, we will learn to load Base64 String Images into Images in Xamarin.Forms without using any External Plugins like FFMpeg Image Loader Plugin.

Base64 Images

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding. To know more about Base64 Click Here.

Platform Support

The approach used here is done with Portable Library. So, it supports all the 3 (Android, iOS, and UWP) Platforms supported by Xamarin.Forms.
Without much introduction, we will skip into the coding part of this article.

Steps

I have explained the method to load base64 image in Image with 3 steps as shown below.
Step 1 - Creating new Xamarin.Forms Projects.
Step 2 - Creating a user interface with Xamarin.Forms.
Step 3 - Implementing the functionality to load Base64 Image.
Step 1 Creating new Xamarin.Forms Projects.
Create New Project by Selecting New >> Project >> Select Xamarin Cross-Platform App and Click OK.
Xamarin
Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .NET Standard and Click OK.
Xamarin
Step 2 Creating a user interface with Xamarin.Forms
Add Image Control to your Page, and here, I am going to add the control in MainPage.xaml. You can paste the codes shown below to create user interface for your page.
<?xml version="1.0" encoding="utf-8" ?>  
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
 xmlns:local="clr-namespace:Base64" 
 x:Class="Base64.MainPage">  
    <ContentPage.Content>  
        <Image x:Name="xfImage" 
   VerticalOptions="Center"
   HorizontalOptions="Center" /> 
 </ContentPage.Content>  
</ContentPage>
Step 3 implementing the functionality to load Base64 Image
In Xamarin.Forms, we can assign the source for Images by many ways like File Path, Image URL, From Resource Folder or Stream of Image.
We can convert the Base64 string into Stream of Image. That is array of Bytes (byte[]). We will use this method to assign Base64 image to Image Controls using the following code.
byte[] Base64Stream = Convert.FromBase64String(base64Image);  
xfImage.Source = ImageSource.FromStream(() => new MemoryStream(Base64Stream));
Full Code of MainPage.xaml.cs
namespace Base64 {  
    public partial class MainPage: ContentPage {  
        string base64Image = "iVBORw0KGgoAAAANSUhEUgAAAHwAAAB8CAMAAACcwCSMAAAAZlBMVEUAAAD///+cnJz7+/vz8/MdHR329vbw8PBRUVHh4eEaGhqsrKzn5+dZWVnk5OQyMjLZ2dmOjo6ysrIoKCjR0dFiYmKjo6NKSkoNDQ3ExMQ4ODi5ubmHh4cWFhbLy8tBQUF6enpvb2/Qp8GOAAAFzUlEQVRogcWb56KyOhBFIyBFQUGkiQXe/yVvQPFQUvYEvN/+q7CYlMnMJGG7fyhm8pDrnZ71Mbd65cf6efLc/wPuhlXeRLf0wUZ6pLeoyauQ+gUkuFPd/ZRJlfr3yvkN3L20pRw8qGwvuP0g3K0aPXhQU4F8CB5aLxzd6WWFG8HDRNHPMqUJgNfCPRP0G++thNtHQ3SPP9pr4NfCHN2puBrDvWYdulOjansFvLqtZzN2qwzgtrUFupMl7XkZPGy3YjPWymadBB4TvYpar5gCrwEvTlFZ4/DjtuhORxT+A7aYLoD/hC2kL+E/YovoC/jlV2zGLjr483dsxp5qeLBiEdMrDVRwz/8lmzHfU8DvlDelLz/yX7SmusvhhIEe5XHYLRh2GOcRgX6UwWPUqT6s08SCUwK74zKWwFELmuUqFTYoPRLDwQX8JY4O6jNIt0Tw00P/IJcvWR53MThTHn9d9gdvoEezQAR+Nz1Ib5bwK/TgSxUPBmDQ9w1pB7gNffZDbndvANhzQ1A3wGvoMUuG/SiH3sKGuOYDd6FpVuiybxtLMiJ3AscMX6yJC4ELcj2BQ4b7+rKDg425aAzHhrquxzsl0Js+A/4Nb5AHynksIFKFefnmD25DD9y0+TbXCfSy9heODbcIqbQ44OpUf+EZ9P9GjX3LbjB4NsA97P8JAoeDIe8DBycnMtjh4d77jA4OZsPbWt6+4R44QLE+R/P6s9fD0Txh09HeZxAMXoq2neeM5T0cLoBs6OFY3+ls58AVkA19O9fL4fATnHP4+nb38FpOeuJwvKGA9Rxz1L3KisMJOVKhqaXudpQi1pHDKcU+nZ8hFQ4tDm8I/3/IMoa3CD3IOqfF4AytV6Eq4RMrhxGH057I5PSQZAafaxxOLIQUsrwhoNbm0x2z99RnJFkquWK6t+lwVjZL44OG+hZDODf+PsXHd4OXmMK59ZEV9Ju3rhfnkVmN2hjeKS2yNivMC3er4Gv1r+E7OPSYqTy//CiLipvp15+5kyHv2z3SqLWqZ8xHnG27Thhfq2PTFlhVYqSCw7F0ZdA+S56xIJK0w+ulIXpqDqfUW8/WVRXCnmqKJXcOR4NX7lrUO6O9wiNcuM45HIx8brN6q1R2lWHdX3P49QD88ZCA6E5ujVh/uHK4B5RRsqc2eps2vqW3iOcgbGdrY4CDcEdOrUA79CK7y1h0cX5GaPGRjhrjkz5d0qTnidHJI66ruj8vPTxQfmJuiOYKVOPuEPRwV/Uf8fYvKE8xnHz3XZmQd3qpT5CUUmTrXf7RweX1xxVt/rFdumxdP3BbtqpiVRilZFuUZ/sDl7V7azrOx6oUdvXwQPxx6m0FVGLLgi9cnDIZ+DWRhFXw1+4PLlpWXzR3LpfIieUjuCMYFqtm+ETLdk2dEVzQMe1mbEHE8JlGH/hiRpSKI01UufMVbtjEH7a25pFcgVT8UM3LPsMu+gAPHuLfN1E8bdfv1uB3O3PW6xu2+qLdv47zC3cmPvYBBKoENeN3n787ZH+7yJMxuVeXnaiajKi/OTzavB8vf4dNLZ9svIyODozg8XjMyY/vGSgYuZlxKW98ZmJcPyxbazMlY+8+Ll1PjqrQckYjZTsZPDTN1WGdQymcWDyla+a0Zwez4JTVTLOYcH4krfkle745tjiM98NzYf6ctYA7P6MvDx4sz0CiZ23I7GWxXHD68/QTui/IdUXnXsOVp9pFEm5RCE/8KlNHI/nC/ENy0Jp0HlEvSVwkgdv5hr6ulKUf0sP1z838/Fm6ASy/VqDK7CmK5HGw6kJFTq7lLvVQpfjKqySn1Qu8upKluURTr7rRcdPke7rrQ45lvImSWrpTZPqLU0b3prCbU8iVsZBufQrdGcMuy7kX0ryLwNt68DXB0ALH3g27KEeCc5cbW5FmJ2kfWTEh26BdDbXDOsluwlrt4ZYldUjLc+iXYm0vrvOk9c/7Q6/92W+TvI49eoJldCP38xUfmb/hPxbhSmN+ggQuAAAAAElFTkSuQmCC";  
        public MainPage() {  
            InitializeComponent();  
            byte[] Base64Stream = Convert.FromBase64String(base64Image);  
            xfImage.Source = ImageSource.FromStream(() => new MemoryStream(Base64Stream));  
        }  
    }  
}
The longest string shown here is the base 64 is encoded to the image
  • Convert.FromBase64String(base64Image) is used to convert base64 string byte[].
  • ImageSource.FromStream(() => new MemoryStream(Base64Stream)) is used to convert the byte[] to Image Stream and Stream is assigned to Image Control.

When considering how to build iOS and Android applications, many people think that the native languages, Objective-C, Swift, and Java, ...

Xamarin - Introduction Xamarin - Introduction

A blog about android developement


When considering how to build iOS and Android applications, many people think that the native languages, Objective-C, Swift, and Java, are the only choice. However, over the past few years, an entire new ecosystem of platforms for building mobile applications has emerged.

Xamarin is unique in this space by offering a single language – C#, class library, and runtime that works across all three mobile platforms of iOS, Android, and Windows Phone (Windows Phone’s native language is already C#), while still compiling native (non-interpreted) applications that are performant enough even for demanding games. 

Each of these platforms has a different feature set and each varies in its ability to write native applications – that is, applications that compile down to native code and that interop fluently with the underlying Java subsystem. For example, some platforms only allow apps to be built in HTML and JavaScript, whereas some are very low-level and only allow C/C++ code. Some platforms don’t even utilize the native control toolkit.  

In Androidmads, we will not cover the basics of Xamarin App development. But, we will cover the advanced concepts of Xamarin as well as we will assist you, if you find any help with Xamarin Basics. And also we will see about Flutter App development.

Introduction: In this article, we will learn how to create and use Clearable EditText without using any Third party library. It is very e...

Clearable EditText in Android Clearable EditText in Android

A blog about android developement

Introduction:

In this article, we will learn how to create and use Clearable EditText without using any Third party library. It is very easy to implement and useful control for our application development.

Coding Part:

Steps:

I have split this part into 3 steps as in the following.
  1. Creating New Project with Empty Activity.
  2. Setting up the Library.
  3. Implementation of Custom Control in Android.

Step 1: Creating New Project with Android Studio

  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and select your activity template.
  3. Click “finish” button to create new project in Android Studio.

Step 2: Setting up the Firebase Library

In this part, we will see how to setup the library for the project.
  1. Open your app level build.gradle file and add the following lines in dependencies to apply required libraries to your project.
    dependencies {
        ...
        implementation 'com.android.support:appcompat-v7:26.1.0'
        implementation 'com.android.support.constraint:constraint-layout:1.1.2'
        implementation 'com.android.support:support-annotations:27.1.1'
        implementation 'com.android.support:design:26.1.0'
    }
  2. Then click “Sync Now” to setup your project.

Step 3: Implementation of Clearable EditText:

Create a class named as ClearableEditText extend with AppCompatEditText as Parent. Then open the class file and add the following code of lines.

public class ClearableEditText extends android.support.v7.widget.AppCompatEditText {

    private Drawable drawableTemp;
    private Drawable drawableRight;

    int actionX, actionY;

    private DrawableClickListener clickListener;

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

    public ClearableEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ClearableEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    public void setCompoundDrawables(Drawable left, Drawable top,
                                     Drawable right, Drawable bottom) {
        if (right != null) {
            drawableRight = right;
        }
        super.setCompoundDrawables(left, top, right, bottom);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        if (text.toString().length() > 0) {
            drawableRight = drawableTemp;
            setCompoundDrawables(null, null, drawableRight, null);
        } else {
            drawableTemp = drawableRight;
            setCompoundDrawables(null, null, null, null);
        }
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Rect bounds;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            actionX = (int) event.getX();
            actionY = (int) event.getY();
            if (drawableRight != null) {

                bounds = drawableRight.getBounds();
                int x, y;
                int extraTapArea = 13;

                /*
                  IF USER CLICKS JUST OUT SIDE THE RECTANGLE OF THE DRAWABLE
                  THAN ADD X AND SUBTRACT THE Y WITH SOME VALUE SO THAT AFTER
                  CALCULATING X AND Y CO-ORDINATE LIES INTO THE DRAWBABLE
                  BOUND. - this process help to increase the tappable area of
                  the rectangle.
                 */
                x = actionX + extraTapArea;
                y = actionY - extraTapArea;

                /*
                 Since this is right drawable subtract the value of x from the width
                 of view. so that width - tapped_area will result in x co-ordinate in drawable bound.
                */
                x = getWidth() - x;

                 /*x can be negative if user taps at x co-ordinate just near the width.
                  e.g views width = 300 and user taps 290. Then as per previous calculation
                  290 + 13 = 303. So subtract X from getWidth() will result in negative value.
                  So to avoid this add the value previous added when x goes negative.
                 */

                if (x <= 0) {
                    x += extraTapArea;
                }

                 /*
                 If result after calculating for extra tap-able area is negative.
                 assign the original value so that after subtracting
                 extra tapping area value doesn't go into negative value.
                 */

                if (y <= 0)
                    y = actionY;

                /*
                If drawable bounds contains the x and y points then move ahead.
                */
                if (bounds.contains(x, y) && clickListener != null) {
                    clickListener.onClick();
                    event.setAction(MotionEvent.ACTION_CANCEL);
                    return false;
                }
                return super.onTouchEvent(event);
            }

        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        drawableRight = null;
        super.finalize();
    }

    public void setDrawableClickListener(DrawableClickListener listener) {
        this.clickListener = listener;
    }

    public interface DrawableClickListener {
        void onClick();
    }
}

Here, I have created DrawableClickListener interface which is used to intimate users when they clicked the Drawable icon of the EditText control.

Open your activity_main.xml file and add the following lines.

<?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"
    android:layout_margin="10dp"
    tools:context="com.androidmads.materialedittext.MainActivity">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/text_input_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:errorEnabled="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.androidmads.materialedittext.ClearableEditText
            android:id="@+id/edit_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableEnd="@drawable/ic_close"
            android:drawableRight="@drawable/ic_close"
            android:hint="Enter your name" />

    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="68dp"
        android:text="Click Here..."
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/text_input_layout" />

</android.support.constraint.ConstraintLayout>

The Layout Preview looks like in the below screenshot

This control will shows the cancel “icon” when the control has typed text and “icon” will hide when the control has no text. Then open your MainActivity.java file and initialize your control like the following.

final TextInputLayout textInputLayout = findViewById(R.id.text_input_layout);
final ClearableEditText editText = findViewById(R.id.edit_text);
final Button button = findViewById(R.id.button);
The cancel icon will appear when the user types the data. Add the following Drawable click listener as look like in the following.
editText.setDrawableClickListener(new ClearableEditText.DrawableClickListener() {
 @Override
 public void onClick() {
  editText.setText(null);
 }
});

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

As discussed in our previous posts, we have learned how to perform email authentication and phone number authentication with firebase i...

Firebase Google plus Authentication in Android Firebase Google plus Authentication in Android

A blog about android developement

As discussed in our previous posts, we have learned how to perform email authentication and phone number authentication with firebase in android. In this article, we will how to perform Google Plus authentication in Android.

You can find my previous posts from following,

  1. Firebase Email Authentication

  2. Firebase Phone Authentication

Firebase G-Plus Authentication:

Firebase facilities Developers to manage Google plus Authentication in Easy way. Before starting, we have add or enable Google plus Authentication in Firebase console.

Firebase Setup:

Before start coding, we have to setup firebase for android and enable Phone Authentication. If you are new to firebase, the following link will be useful to know the method for setting up the project in firebase.

After setting up, open Authentication sign in method and enable phone authentication method as shown in the following figure.

You should Add SHA Fingerprint in your application. The following terminal will be used to get the SHA Fingerprint with Command Prompt in Windows for debug mode.

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Coding Part:

Steps:

I have split this part into 3 steps as in the following.

Step 1: Creating New Project with Empty Activity.

Step 2: Setting up the Firebase Library.

Step 3: Implementation of Firebase Google Plus Authentication.

Step 1: Creating New Project with Android Studio

  1. Open Android Studio and Select Create new project.

  2. Name the project as your wish and select your activity template.


  3. Click “finish” button to create new project in Android Studio.

Step 2: Setting up the Firebase Library

In this part, we will see how to setup the library for the project.

  1. Open your project level build.gradle file and add the following lines in dependencies.

    dependencies {
        …
        classpath 'com.google.gms:google-services:4.0.1'
        …
    }
  2. Then add the following lines in allprojects in project level build.gradle file.

    allprojects {
        repositories {
            google()
            jcenter()
            maven {
                url "https://maven.google.com"
            }
        }
    }
  3. Then add the following lines in app level build.gradle file to apply google services to your project.

    dependencies {
        ...
        implementation 'com.google.firebase:firebase-auth:16.0.2'
        implementation 'com.google.android.gms:play-services-auth:15.0.1'
        implementation 'com.squareup.picasso:picasso:2.71828'
    }
    apply plugin: 'com.google.gms.google-services'
  4. Then click “Sync Now” to setup your project.

Step 3: Implementation of Firebase Google plus Authentication:

Initialize Google Sign in Client with Google Sign in options and Firebase Auth Client like shown in below snippet.

//first we initialized the Firebase Auth object
FirebaseAuth mAuth = FirebaseAuth.getInstance();

//Then we need a GoogleSignInOptions object
//And we need to build it as below
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  .requestIdToken(getString(R.string.default_web_client_id))
  .requestEmail()
  .build();

//Then we will get the GoogleSignInClient object from GoogleSignIn class
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

You must pass your server's client ID to the requestIdToken method. To find the OAuth 2.0 client ID: Open the Credentials page in the API Console. The Web application type client ID is your backend server's OAuth 2.0 client ID.

Then add the following code to initiate Google sign in.

//getting the google signin intent
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
//starting the activity for result
startActivityForResult(signInIntent, RC_SIGN_IN);

Add the onActivityResult as shown below

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);

 //if the requestCode is the Google Sign In code that we defined at starting
 if (requestCode == RC_SIGN_IN) {

  //Getting the GoogleSignIn Task
  Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
  try {
   //Google Sign In was successful, authenticate with Firebase
   GoogleSignInAccount account = task.getResult(ApiException.class);
   //authenticating with firebase
   firebaseAuthWithGoogle(account);
  } catch (ApiException e) {
   Log.v("API Exception", e.toString());
   Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
  }
 }
}

After a user successfully signs in, get an ID token from the GoogleSignInAccount object, exchange it for a Firebase credential, and authenticate with Firebase using the Firebase credential.

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
 Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

 //getting the auth credential
 AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

 //Now using firebase we are signing in the user here
 mAuth.signInWithCredential(credential)
                            .addOnCompleteListener(this, new OnCompleteListener() {
  @Override
  public void onComplete(@NonNull Task task) {
   if (task.isSuccessful()) {
    if (mAuth.getCurrentUser() != null) {
     startActivity(new Intent(LoginActivity.this, MainActivity.class));
     finish();
    }
   } else {
    // If sign in fails, display a message to the user.
    Log.w(TAG, "signInWithCredential:failure", task.getException());
    Toast.makeText(LoginActivity.this, "Authentication failed.",
     Toast.LENGTH_SHORT).show();
   }
  }
 });
}

If the user is authenticated with Google Plus Sign In successfully, then login screen is redirected to the next activity.

To retrieve user details like name, profile picture, mail id through Firebase, use the following snippets.

FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();

assert user != null;
textName.setText(user.getDisplayName());
textEmail.setText(user.getEmail());

Picasso.get().load(user.getPhotoUrl()).into(imageView);

Here, I have used Picasso Image Loading Library to load images. To more click here.

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

Introduction: In this article, we will learn how use Kenburnsview in Android using Kotlin. Kenburnsview is an awesome Android library ...

How to use KenburnsView in Kotlin How to use KenburnsView in Kotlin

A blog about android developement

Introduction:

In this article, we will learn how use Kenburnsview in Android using Kotlin. Kenburnsview is an awesome Android library that provides an extension to ImageView that creates an immersive experience by animating its Drawable using the Ken Burns Effect.

Coding Part:

I have divided the coding part into 3 steps as shown in the following.

  1. Creating new project with Kotlin Support.

  2. Setting up the project with Kenburnsview Library.

  3. Implementing KenburnsView with Kotlin.

Step 1: Creating new project with Kotlin:

  1. Open Android Studio and Select Create new project.

  2. Name the project as your wish and tick the Kotlin checkbox support.

  3. Then Select your Activity type (For Example: Navigation Drawer Activity, Empty Activity, etc.).

  4. Then Click “finish” button to create new project in Android Studio.

Step 2: Setting up the project with AndroidManifest:

We will add the following lines to your app level build.gradle to add KenburnsView library to your project.

dependencies { 
    …
    implementation 'com.flaviofaria:kenburnsview:1.0.7'
    …
}
repositories {
    mavenCentral()
}

Step 3: Implementation of KenburnsView with Kotlin

  1. We will start coding. Open your layout file. In my case, I have activity_main.xml included content_main.xml. So, I have opened content_main.xml.

  2. Then add the following lines.

    <?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"
              app:layout_behavior="@string/appbar_scrolling_view_behavior"
              tools:context="com.androidmads.kenburnsview.MainActivity"
              tools:showIn="@layout/activity_main">
    
        <com.flaviofaria.kenburnsview.KenBurnsView
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/img"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/img1" />
    
    </android.support.constraint.ConstraintLayout>
  3. Then open your MainActivity.java file and Initialize the KenburnsView Library as shown in the following.

    var mImg: KenBurnsView? = null
    mImg = findViewById(R.id.img)
  4. We can pause, resume and stop the ken burns effect by the library itself using the following snippets respectively.

    mImg!!.pause()
    mImg!!.resume()
    mImg!!.stop()
  5. We can perform our defined operations based on the transitions of KenburnsView using the following snippets.

    mImg!!.setTransitionListener(object : KenBurnsView.TransitionListener {
     override fun onTransitionStart(transition: Transition) {
    
     }
    
     override fun onTransitionEnd(transition: Transition) {
      if (imageId == R.drawable.img1) {
       imageId = R.drawable.img2
       mImg!!.setImageResource(R.drawable.img2)
      } else {
       imageId = R.drawable.img1
       mImg!!.setImageResource(R.drawable.img1)
      }
     }
    })
  6. Here, I have changed the image source to KenburnsView, when each image transitions end.

Full Code of MainActivity:

You can find the full code implementation of MainActivty.kt in the following

class MainActivity : AppCompatActivity() {

    private var mImg: KenBurnsView? = null
    private var fab: FloatingActionButton? = null
    private var isPlaying = true
    private var imageId: Int = 0

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

        imageId = R.drawable.img1

        fab = findViewById(R.id.fab)
        mImg = findViewById(R.id.img)

        fab!!.setOnClickListener {
            if (isPlaying) {
                mImg!!.pause()
                fab!!.setImageResource(R.drawable.ic_play)
            } else {
                mImg!!.resume()
                fab!!.setImageResource(R.drawable.ic_pause)
            }
            isPlaying = !isPlaying
        }

        mImg!!.setTransitionListener(object : KenBurnsView.TransitionListener {
            override fun onTransitionStart(transition: Transition) {

            }

            override fun onTransitionEnd(transition: Transition) {
                if (imageId == R.drawable.img1) {
                    imageId = R.drawable.img2
                    mImg!!.setImageResource(R.drawable.img2)
                } else {
                    imageId = R.drawable.img1
                    mImg!!.setImageResource(R.drawable.img1)
                }
            }
        })
    }
}

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

Introduction: In this article, we will learn how to create a music previewer like Google play music and register the app as Music Play...

How to Create a Music Previewer in Android How to Create a Music Previewer in Android

A blog about android developement

musicpreviewer
Introduction:
In this article, we will learn how to create a music previewer like Google play music and register the app as Music Player to the phone. Registering mobile app as Music Player will show our app in suggestions while opening audio files.
Intent Filter:
Registering app as music player will be achieved by intent-filters in AndroidManifest.xml against our activity. To know more about Intent-Filters, read the link.
Coding Part:
Steps:
I have split this part into 3 steps as in the following.
Step 1: Creating New Project with Empty Activity.
Step 2: Implementation of Music Previewer UI.
Step 3: Setting up Manifest with Intent Filters.
Step 4: Implementation of Music Previewer in Android.
Step 1: Creating New Project with Android Studio
  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and select your activity template.
  3. Click “finish” button to create new project in Android Studio.
Step 2: Implementation of Music Previewer UI
In this part, we will see how to create a dialog for music previewer.
  1. We will create an activity named as MainActivity.java and we need this activity to be show like Dialog. So, we have add the following lines in styles.xml file.
    <resources>
    
        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.Dialog">
            <item name="windowNoTitle">true</item>
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="colorAccent">@color/colorAccent</item>
            <item name="windowMinWidthMajor">90%</item>
            <item name="windowMinWidthMinor">90%</item>
            <item name="android:windowCloseOnTouchOutside">false</item>
        </style>
    
    </resources>
  2. Theme.Appcompat.Light.Dialog is used to apply dialog like style to an activity.
  3. By default, the dialog style applied based on children width. To apply full width to the dialog, use windowMinWidthMinor key with value 90%.
  4. In the same way, windowCloseOnTouchOutside is used to handle dialog cancel on touch outside of the views. It is similar setCancelableOnTouchOutside method for dialogs.
  5. Then open your layout file (for example: activity_main.xml) and add the followings lines.
    <?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="70dp"
        android:layout_margin="10dp"
        android:background="@android:color/white"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="10dp"
        tools:context=".MainActivity">
    
            <ImageView
                android:id="@+id/song_art"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:scaleType="fitXY"
                android:contentDescription="@string/image_desc"
                android:src="@mipmap/ic_launcher" />
    
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="9"
                android:orientation="vertical"
                android:paddingLeft="10dp"
                android:paddingStart="10dp"
                tools:ignore="RtlSymmetry">
    
                <TextView
                    android:id="@+id/song_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/tv_song_title" />
    
                <TextView
                    android:id="@+id/song_artist"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:text="@string/tv_song_artist" />
            </LinearLayout>
    
            <ImageView
                android:id="@+id/play_pause"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:contentDescription="@string/image_desc"
                android:src="@drawable/ic_play" />
    
    </LinearLayout>
  6. Your layout shown like in the following figure.
    scrn 1
  7. Then click Run to view the output activity as dialog in the following figure.
scrn 2
Step 3: Setting up manifest with Intent-Filter:
In this step, we will learn How to apply intent-filter to register your music player app. The following line of codes will help us to register the app.
<activity android:name=".MainActivity">
 <intent-filter>
  <action android:name="android.intent.action.MAIN" />

  <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 <intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <data android:scheme="file"/>
  <data android:mimeType="audio/*"/>
 </intent-filter>
</activity>
This filters will lead the app to be in suggestions when we opening/selecting any audio files. The following figure for your reference.
scrn 3
Step 4: Implementation of Music Previewer in Android.
In this step, we will how to handle media options using Media Player API in Android (i.e., play, pause…).
  1. Media Player can be initialized as shown in the following.
    MediaPlayer mp = new MediaPlayer();
  2. The selected song’s path can be get using Intent and activity opening option can be identified with its action.
    if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
      try {
       assignSongDetails(getIntent().getData().getPath());
       mp.setDataSource(getIntent().getData().getPath());
       mp.prepare();
       mp.start();
      } catch (Exception e) {
       e.printStackTrace();
      }
     }
  3. Selected song can be played with start method in media player API.
    mp.start();
  4. Media Player can be paused using pause method in media player API.
    if (mp.isPlaying()) {
      mp.pause();
     }
     
  5. Then click Run or Shift + F10 to deploy the app in debug mode. Close your app and select any audio file you want to open and select your app. Now you can find your music player works fine.
  6. Next we will see, how to get the details of the selected audio file. MediaMetadataRetriever is used here.
  7. The MediaMetaDataRetriever can be initialized like below.
    metaRetriever = new MediaMetadataRetriever();
     metaRetriever.setDataSource(filePath);
  8. Song’s album can be retrieved using the following code.
    metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
  9. Song’s artist can be retrieved using the following code.
    metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
  10. In the same way, we can read the album art using the following method.
    byte[] art = metaRetriever.getEmbeddedPicture();
     Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
     imgSongArt.setImageBitmap(songImage);
     
  11. The media player can be stopped using stop method in media player API with onPause method of the activity.
    @Override
     protected void onPause() {
      super.onPause();
      assert mp != null;
      if (mp.isPlaying()) {
       mp.stop();
      }
     }
    scrn 4
    Full Code:
    You can find the full code implementation here.
    public class MainActivity extends AppCompatActivity {
    
        TextView tvSongTitle, tvSongArtist;
        ImageView playPause, imgSongArt;
        MediaPlayer mp = new MediaPlayer();
    
        MediaMetadataRetriever metaRetriever;
        byte[] art;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            tvSongTitle = findViewById(R.id.song_title);
            tvSongArtist = findViewById(R.id.song_artist);
            playPause = findViewById(R.id.play_pause);
            imgSongArt = findViewById(R.id.song_art);
    
            if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
                try {
                    assignSongDetails(getIntent().getData().getPath());
                    mp.setDataSource(getIntent().getData().getPath());
                    mp.prepare();
                    mp.start();
                    playPause.setImageResource(R.drawable.ic_pause);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            playPause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mp.isPlaying()) {
                        mp.pause();
                        playPause.setImageResource(R.drawable.ic_play);
                    } else {
                        mp.start();
                        playPause.setImageResource(R.drawable.ic_pause);
                    }
                }
            });
    
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    playPause.setImageResource(R.drawable.ic_play);
                }
            });
    
        }
    
        void assignSongDetails(String filePath) {
            metaRetriever = new MediaMetadataRetriever();
            metaRetriever.setDataSource(filePath);
            try {
                tvSongTitle.setText(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM));
                tvSongArtist.setText(metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST));
                try {
                    art = metaRetriever.getEmbeddedPicture();
                    Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
                    imgSongArt.setImageBitmap(songImage);
                } catch (Exception ex) {
                    imgSongArt.setImageResource(R.mipmap.ic_launcher);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            assert mp != null;
            if (mp.isPlaying()) {
                mp.stop();
            }
        }
    }
Download Code:
You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

Introduction:  In this article, we will learn how to generate QR Code in Android. Quick Response Code (QR Code in short) is a 2-Dimensi...

How To Generate QR Code In Android How To Generate QR Code In Android

A blog about android developement

QR-CODE  GENERATOR - Library

Introduction: 

In this article, we will learn how to generate QR Code in Android. Quick Response Code (QR Code in short) is a 2-Dimensional matrix type barcode used to store data. It is more popular because of its storage capacity and fast readability.

Zxing & QR Generator Library:

Zebra Crossing (Zxing) is an awesome library used to generate and read QR codes in mobile apps. But it is bigger in size. So, we have to go for another one, QR Generator which is a tiny, open source library. In this article, we will learn how to create & save the QR Code in Android programmatically.

Steps:

I have split this part into 4 steps as in the following.
  1. Creating a New Project with Empty Activity.
  2. Setting up the library and manifest.
  3. Generating QR Code.
  4. Saving QR Code.

Step 1 - Creating New Project with Empty Activity

  1. Open Android Studio and Select create a new project.
  2. Name the project as per your wish and select an Empty activity.
    Android
  3. Click finish button to create a new project in Android Studio.

Step 2 - Setting up the library and manifest

  1. Open App level gradle file and import the library.
    implementation 'androidmads.library.qrgenearator:QRGenearator:1.0.3'
  2. The, click “Sync Now”.
  3. Then, open your Manifest file and add the following permissions. It is used to save QR Code to file storage.
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  4. We need to handle runtime permissions from Android Version 6.0.

Step 3 - Generating QR Code

In this step, we will learn how to generate QR Code in Android. Open your MainActivity.java file and add the following lines.
QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension);
      - Here, inputValue is an input to be converted to QR Code.
      - Input Type also can be specified while initializing the library.
      - We can specify the dimensions also.
    Then, add the following lines to create QR Code and encode that into Bitmap Format.
    try {  
      // Getting QR-Code as Bitmap  
      bitmap = qrgEncoder.encodeAsBitmap();  
      // Setting Bitmap to ImageView  
      qrImage.setImageBitmap(bitmap);  
    } catch (WriterException e) {  
      Log.v(TAG, e.toString());  
    }
    qrImage is an ImageView used to preview the generated QR code bitmap.

Step 4 - Saving QR Code

QR Generator has an option to save the generated QR Code Bitmap to storage using the following lines.
// Save with location, value, bitmap returned and type of Image(JPG/PNG).  
QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
We can save QR Code in PNG & JPG format also. We have to handle runtime permissions from Android version 6.0.

Full Code

You can find the full code implementation here.
public class MainActivity extends AppCompatActivity {  
  
    String TAG = "GenerateQRCode";  
    EditText edtValue;  
    ImageView qrImage;  
    Button start, save;  
    String inputValue;  
    String savePath = Environment.getExternalStorageDirectory().getPath() + "/QRCode/";  
    Bitmap bitmap;  
    QRGEncoder qrgEncoder;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        qrImage = (ImageView) findViewById(R.id.QR_Image);  
        edtValue = (EditText) findViewById(R.id.edt_value);  
        start = (Button) findViewById(R.id.start);  
        save = (Button) findViewById(R.id.save);  
  
        start.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                inputValue = edtValue.getText().toString().trim();  
                if (inputValue.length() > 0) {  
                    WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);  
                    Display display = manager.getDefaultDisplay();  
                    Point point = new Point();  
                    display.getSize(point);  
                    int width = point.x;  
                    int height = point.y;  
                    int smallerDimension = width < height ? width : height;  
                    smallerDimension = smallerDimension * 3 / 4;  
  
                    qrgEncoder = new QRGEncoder(  
                            inputValue, null,  
                            QRGContents.Type.TEXT,  
                            smallerDimension);  
                    try {  
                        bitmap = qrgEncoder.encodeAsBitmap();  
                        qrImage.setImageBitmap(bitmap);  
                    } catch (WriterException e) {  
                        Log.v(TAG, e.toString());  
                    }  
                } else {  
                    edtValue.setError("Required");  
                }  
            }  
        });  
  
        save.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                boolean save;  
                String result;  
                try {  
                    save = QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);  
                    result = save ? "Image Saved" : "Image Not Saved";  
                    Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        });  
  
    }  
}

Download Code

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub.

Introduction: In this article, we will learn how perform AsyncTask in android with Kotlin. Async task is used to perform some async...

How to do AsyncTask in Kotlin How to do AsyncTask in Kotlin

A blog about android developement

kotlin_async
Introduction:
In this article, we will learn how perform AsyncTask in android with Kotlin. Async task is used to perform some asynchronous tasks without blocking the main thread. It is very useful in android development. Similar to java, the same code can be used in Kotlin with some minor modifications.
Coding Part:
I have divided the coding part into 3 steps as shown in the following.
  1. Creating new project with Kotlin Support.
  2. Setting up the project with AndroidManifest.
  3. Implementing Async tasks with Kotlin.
Without any delay, we will start coding for Kotlin AsyncTask.
Step 1: Creating new project with Kotlin:
  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and tick the Kotlin checkbox support.
  3. Then Select your Activity type (For Example: Navigation Drawer Activity, Empty Activity, etc.).
  4. Then Click “finish” button to create new project in Android Studio.
Step 2: Setting up the project with AndroidManifest:
Now, we will add the internet permission in Android Manifest file. Because we will see the example with URL Connection. Just open your AndroidManifest.xml file and add the following line.
<uses-permission android:name="android.permission.INTERNET"/>
Step 3: Implementing Async tasks with Kotlin
We will start coding. Here, I have used the following simple API to retrieve android version details.
  1. I have included a Button and TextView in my layout (activity_main.xml) file. Here, Button and TextView is used to call the API and display the result from the API
    <?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=".MainActivity"  
        tools:layout_editor_absoluteX="0dp"  
        tools:layout_editor_absoluteY="81dp">  
      
        <TextView  
            android:id="@+id/my_text"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="72dp"  
            android:text="AsyncTask Example"  
            android:textSize="18sp"  
            android:textStyle="bold"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toTopOf="parent" />  
      
        <ProgressBar  
            android:id="@+id/MyprogressBar"  
            style="?android:attr/progressBarStyle"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="32dp"  
            android:visibility="invisible"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toBottomOf="@+id/my_text" />  
      
        <Button  
            android:id="@+id/CallBtn"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="36dp"  
            android:text="Execute AsyncTask"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toBottomOf="@+id/MyprogressBar" />  
      
    </android.support.constraint.ConstraintLayout>
Then open your Activity file (in my case MainActivity.kt) and create a class with AsynTask as a parent.
AsyncTask has three main methods.
  1. onPreExecute – State before task performance
  2. doInBackground – State for task performance
  3. onPostExecute – State after task performance
Add the following code with your AsyncTask class. Here I have used
HttpURLConnection” to access the API Link.
BufferedReader” to read the response output of the API Link.
JSONObject” to parse the response from server.
Async Task Class can be called in the following method.
AsyncTaskExample(this).execute()
Full Code of MainActivity:
You can find the full code implementation of MainActivty.kt in the following
class MainActivity : AppCompatActivity() {

    private val tag: String = "MainActivity"

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

        CallBtn.setOnClickListener {
            AsyncTaskExample(this).execute()
        }
    }

    @SuppressLint("StaticFieldLeak")
    class AsyncTaskExample(private var activity: MainActivity?) : AsyncTask() {

        override fun onPreExecute() {
            super.onPreExecute()
            activity?.MyprogressBar?.visibility = View.VISIBLE
        }

        override fun doInBackground(vararg p0: String?): String {

            var result = ""
            try {
                val url = URL("http://demosmushtaq.16mb.com/api/post_sample.php?version_index=14")
                val httpURLConnection = url.openConnection() as HttpURLConnection

                httpURLConnection.readTimeout = 8000
                httpURLConnection.connectTimeout = 8000
                httpURLConnection.doOutput = true
                httpURLConnection.connect()

                val responseCode: Int = httpURLConnection.responseCode
                Log.d(activity?.tag, "responseCode - " + responseCode)

                if (responseCode == 200) {
                    val tempStream: InputStream = httpURLConnection.inputStream
                    result = convertToString(tempStream)
                }
            } catch (ex: Exception) {
                Log.d("", "Error in doInBackground " + ex.message)
            }
            return result
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            activity?.MyprogressBar?.visibility = View.INVISIBLE
            if (result == "") {
                activity?.my_text?.text = activity?.getString(R.string.network_error)
            } else {
                var parsedResult = ""
                var jsonObject: JSONObject? = JSONObject(result)
                jsonObject = jsonObject?.getJSONObject("data")
                parsedResult += "Code Name : " + (jsonObject?.get("code_name")) + "\n"
                parsedResult += "Version Number : " + (jsonObject?.get("version_number")) + "\n"
                parsedResult += "API Level : " + (jsonObject?.get("api_level"))
                activity?.my_text?.text = parsedResult
            }
        }

        private fun convertToString(inStream: InputStream): String {

            var result = ""
            val isReader = InputStreamReader(inStream)
            val bReader = BufferedReader(isReader)
            var tempStr: String?

            try {

                while (true) {
                    tempStr = bReader.readLine()
                    if (tempStr == null) {
                        break
                    }
                    result += tempStr
                }
            } catch (Ex: Exception) {
                Log.e(activity?.tag, "Error in convertToString " + Ex.printStackTrace())
            }
            return result
        }
    }
}

Download Code

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub.