Sunday, December 24, 2017

Android Material SearchView with Recent Search Suggestions

Welcome to this post.

In this post, I am going to cover Android Search View with Recent Search Suggestion.

In a previous post, I already cover Android Material SearchView. In that post, I use a 3rd party library. If you want to use 3rd party library to add search functionality, see this post. Android Material SearchView

But Now I don't want to use any 3rd party library.
In this post, I use:
  • Search Widget
Let's start:
create a new activity:(In my case, I named it: SearchActivity)
First jump into XML code-

Friday, November 17, 2017

Android Runtime permission

Welcome to this post.

In this post, I am going to discussing a new topic that is android runtime permission.

What is runtime permission?
Basically, when we want to access some data on the device or want to make a network request from our app, we need user permission.Basically, we need to write the permissions on the AndroidMenifest.xml
AndroidMenifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
if the user installs the app, the user must accept the permissions that we write on AndroidMenifest.xml
But in Android 6.0 API 23
The Android team want to give more control to the user and now user can install without accepting all the permission.
For an example, we want to access to the storage(external storage), so we need permission first. Now we promote to the user to accept the permission in the app runtime to access the storage.
If the user does not accept the permission that means we do not access the storage.

Tuesday, November 14, 2017

Saturday, November 11, 2017

Android Settings Series (part 1)

Welcome to this Series post.
In this series post, we are going to create a complete Settings for a productive app.

Basic overview of our final settings?

Our final settings contains-
  •  multiple preference screen 
In a previous post, I  cover android settings with a single preference screen (Android App Settings with Preference Fragment Compat).

we create 3 screen that's are-
  • General
  • Backup 
  • Advance
So we create multiple preference screen in the same XML file and after user click, we replace the fragment.
That's the deal,
Lets Start-

Saturday, November 4, 2017

Google Chrome Custom Tab on your Android App

Welcome to this post.
In this post, we are going to learn how to use google chrome custom tab in our app.

In our app, we basically use webview for loading a web address. Or sometimes we make an intent that opens other browser and loads the web address.

But why we use Chrome custom tab?
Chrome custom tabs offer apps additional management over their internet expertise and build transitions between native and web content more seamless while not having to resort to a WebView.

Is any customization support? 
yes. Chrome custom tab supports some customization-

  • Toolbar color 
  • Enter and exit animations 
  • Add custom actions to the Chrome toolbar and overflow menu 

It also allows the developer to pre-start Chrome and pre-fetch content for faster loading.

Ok, Lets Start
First, add the below line in your build.gradle file
//chrome custom tab
compile 'com.android.support:customtabs:26.1.0'
Now create a method-
private void customTab(String url){
}
create a builder object
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
set toolbar color
builder.setToolbarColor(R.attr.colorPrimary);
set title is shown or not
builder.setShowTitle(false);
now build chrome custom intent
CustomTabsIntent customTabsIntent = builder.build();
now launch the URL
customTabsIntent.launchUrl(this, Uri.parse(url));
full code of this method
private void customTab(String url){
        CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
        builder.setToolbarColor(R.attr.colorPrimary);
        builder.setShowTitle(false);
        // add share action to menu list
        builder.addDefaultShareMenuItem();
        CustomTabsIntent customTabsIntent = builder.build();
        customTabsIntent.launchUrl(this, Uri.parse(url));

    }
you can use this method anywhere. you just pass a web address.

Now make some customization- 
Menu:
add menu action button for default share action button
builder.addDefaultShareMenuItem();
want to custom share action button
builder.setActionButton(icon, description, pendingIntent, tint);
here, add a menu item
builder.addMenuItem(menuItemTitle, menuItemPendingIntent);

Animation:
add enter and exit animation
builder.setStartAnimations(this, R.anim.slide_in_right, R.anim.slide_out_left);
builder.setExitAnimations(this, R.anim.slide_in_left, R.anim.slide_out_right);
 that's it today post.
Want to customize more, then don't forget to check the official document of chrome custom tab

Thank you for reading this post.
Happy coding

Wednesday, October 4, 2017

Monday, October 2, 2017

Android Common Code

All the common android code list that used almost every android project.

Here is the list of all code in this post:
  • Support vector drawable
  • PreferenceFragment support
  • Java 8 support
Support vector drawable:
to support vector drawable add below line on the build.gradle file
compile 'com.android.support:support-vector-drawable:26.1.0'
also adds below line on those activities where you use vector drawable.
static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}

PreferenceFragment support:
add the following line on the build.gradle file
compile 'com.android.support:preference-v14:26.1.0'
adds also add below line on the style.XML file
<item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
note: This line is for Material Theme support.

Java 8 support:
to support Java 8 add following line on the build.gradle file
// Keep the following configuration in order to target Java 8.
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}












Wednesday, September 27, 2017

Sunday, September 24, 2017

Android Share Action Provider

Welcome to my Blog.
In this post, I am going to talk about android share action provider.

android shareActionProvider tutorial @androidSketchPad


What is Share Action Provider?
Share action provider is just a provider for share some action. we just create a that enable data sharing and also to show a submenu with sharing activities if the hosting item is placed on the overflow menu.

In this post, I will show you how can you add this feature in your app. Let's start What we need to do for adding share action provider? It's very simple step. We just need to create a view on menu.xml file add reference it from the java class. That's it.

First, create an XML file on res -> menu folder
<item android:id="@+id/action_share"
        android:title="@string/share"
        app:showAsAction="ifRoom"
        app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>


Code analysis:
1. android:id -> we need an id for the call this view
2. android:title -> set a title, for this view3. app:showAsAction -> here I use "If room". Also available some other action too.
here a short list of action and their work

  • If room -> if there is enough space on action bar then it will 
  • show always -> it will show this view always in the action bar 
  • never -> for this action, this view will never show
  • collapseActionView -> This item's action view collapses to a normal menu item. 
  • with text -> this will show the icon with text that defines on android: title on the XML file.
4. actionProviderClass -> here we need to set action provider class. We are working on Share action provider, so we need to set-
android.support.v7.widget.ShareActionProvider

Time for java code-
Create a global variable of Share action Provider Class;
ShareActionProvider myShareActionProvider;
Now come on onCreateOptionsMenu() method initializes this by using getActionProvider() method class of MenuItemCompat
myShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
set a share intent
myShareActionProvider.setShareIntent(createShareIntent());
Creta a method that's return Intent
private Intent createShareIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        String s = "welocme to android sketchPad";
        shareIntent.putExtra(Intent.EXTRA_TEXT, s);

        return shareIntent;
    }
Now we create another method that name update share action provider: note: don't forget to cheek shareActionProvider is not null
private void resetShareActionProvider(String word) {
        if (myShareActionProvider != null) {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, word);

            myShareActionProvider.setShareIntent(shareIntent);
        }
    }
Now you can use this method anywhere you want and update intent for this share action provider.

we just finished all code for adding share action prover. But ...

we can do this also various way, here is another one,
Create a global Variable of ShareActionProvider and initialize it on the on Create menu option (same as previous) now create an Intent where you have data and bind your data on and set this intent to ShareActionProvider variable
see the code:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String s = "welome to Android SketchPad";
shareIntent.putExtra(Intent.EXTRA_TEXT, s);

if (myShareActionProvider != null) {
    myShareActionProvider.setShareIntent(shareInten);
}
       
If you are using loader manager then do this task on the onLoadFinished() method

Fix app crashing: 
If you use proguard in your project, then your app will be crashed on release mode. To fix this you need to add below line on the proguard-project.txt
-keep class android.support.v7.widget.ShareActionProvider { *; }

Final screen shot:
share action provider @android SketchPad


Another One:
Share action Provider 2@android SketchPad


That's it:
That's the ending of today code. now you can add this option to your app. In this post, I just show you a basic tutorial about share action provider. In share action provider I just share text, but you can share image, document, video, audio and much more.

Thanks for reading this post.
Happy coding.

Monday, September 18, 2017

Android Splash Screen right way

Welcome to this post. In this post, I am going to discuss on Android Splash Screen.

splash Screen @androidSketchPad


In this whole post, I gonna cover those topics
1. How to create android Splash Screen
2. How to override default color when app launching (windows background)

When you click app icon, the app takes some time to start. To overcome this option android by default show a color until the activity is launched. By default, it is white in color. So later in this post, I will show you how to overcome this situation and how to change this default color.

Let's start-

Create an Activity named it as your choice

creating an activity android SketchPad


now design your layout file. I just provide my XML code.
<?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.blogspot.shudiptotrafder.soilscience.SplashActivity"
    tools:showIn="@layout/activity_splash"
    android:background="?attr/colorPrimary">

    <ImageView
        android:id="@+id/splash_imageView"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        app:srcCompat="@drawable/ic_lover"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginEnd="8dp"
        android:contentDescription="app icon"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="80dp"
        tools:ignore="HardcodedText" />

    <TextView
        android:id="@+id/splash_app"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="App Name"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginEnd="8dp"
        android:layout_marginTop="16dp"
        android:textSize="30sp"
        app:layout_constraintTop_toBottomOf="@+id/splash_imageView" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/splash_app"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginTop="16dp"
        android:id="@+id/splash_appAbout"
        android:text="This is a complete app"
        android:textSize="16sp"
        app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

and ic_lover.xml it as vector drawable, code here
<vector android:height="24dp"
    android:viewportHeight="512.0"
    android:viewportWidth="512.0"
    android:width="24dp"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <path
        android:fillColor="#FF6464"
        android:pathData="M0,173.5C0,96 62.9,33.1 140.4,33.1c34.4,0 65.9,12.4 90.3,32.9c14.7,12.3 36,12.3 50.7,0c24.4,-20.5 55.9,-32.9 90.3,-32.9C449.1,33.1 512,96 512,173.5v-4.1c0,136.1 -165.6,258.9 -230.4,301.8c-15.5,10.3 -35.7,10.3 -51.2,0C165.6,428.3 0,305.5 0,169.4" />
    <path
        android:fillColor="#D2555A"
        android:pathData="M0,173.5c0,-0.6 0.1,-1.2 0.1,-1.8C0.1,171 0,170.2 0,169.4V173.5z" />
    <path
        android:fillColor="#D2555A"
        android:pathData="M114.8,182.7c-0,0.6 -0.1,1.3 -0.1,1.9v-4.5C114.8,181 114.8,181.9 114.8,182.7c0.5,-66.9 29.4,-123.3 69.2,-142.5c-13.7,-4.5 -28.4,-7.1 -43.6,-7.1c-76.9,0 -139.3,61.9 -140.3,138.6c1.9,135.2 165.9,256.8 230.3,299.4c6.6,4.4 14.1,6.8 21.6,7.4C198.9,418.8 116,306 114.8,182.7z" />
    <path
        android:fillColor="#FF8B8B"
        android:pathData="M449.5,153.9m-32,0a32,32 0,1 1,64.1 0a32,32 0,1 1,-64.1 0" />
    <path
        android:fillColor="#FFC1C1"
        android:pathData="M408.4,92.8m-20,0a20,20 0,1 1,40.1 0a20,20 0,1 1,-40.1 0" />
</vector>

We finished our design option, see the preview
splash screen android SketchPad

it contains an ImageView and two TextView

now time for java coding, SplashScreen.java
public class SplashScreen extends AppCompatActivity {

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

    }

now create an instance of Thread class and in the run methods call sleep methods and pass value 1000 (1000 for 1s, the value of Mille seconds). Don't forget to put this sleep method on try-catch block. and finally, block on try-catch, create an Intent that brings us to MainActivity. At list call finish() method and this activity will be destroyed.
See the code-
Thread checkForData = new Thread(){
      @Override
      public void run() {
            super.run();
            try{
            sleep(1000);

         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             startActivity(new Intent(SplashActivity.this,
                            MainActivity.class));
             finish();
         }
     }
};
start this thread by calling start method
checkForData.start();
That's it. Splash Screen is created successfully. You can run a test for see result.

oh! Your app is not working. I forget one thing that we are using vector drawable. If your app minimum API is 21 then you have no headache. but if you targeting lower API you need to use support library to support vector drawable for lower API. To do that add below line in your build.gradle file
compile 'com.android.support:support-vector-drawable:25.3.1'
Note: change the version according to you compile SDK version. See mine-
compileSdkVersion 25
buildToolsVersion "25.0.3"
One more thing to go. add below code in your activity class
static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
ok, run the app again.

Screen Short:
Splash Screen @android SketchPad

Note: Don't be confused I use another app splash screen. Both are used the same code.

Now come on the last topics of this post, create a new theme on style.xml and add windows background color
<style name="splashTheme" parent="AppTheme.NoActionBar">
        <item name="android:windowBackground">@color/colorPrimary</item>
</style>
use this theme on the splash screen activity. Open manifest file and override below code-
<activity
       android:name=".SplashScreen"
       android:label="@string/app_name"
       android:theme="@style/splashTheme">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
</activity>
and my color code is
<color name="colorPrimary">#3F51B5</color>
rerun your app and see the change.

See Screen Short:
Splash Screen2 @android SketchPad


A Bonus for you
I also show you how to animate this splash screen. This is the pretty basic animation example.
Let's do this
create an XML file on res -> anim folder.
splash_screen_animation.xml
<alpha
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="0"
    android:toAlpha="1"
    android:duration = "1000" />
Now load this animation, see code-
Animation set = AnimationUtils.loadAnimation(this,
                R.anim.splash_screen_animation);
In the upper activity code, we don't create view variable, because we don't need that time. But now we need those views add set this animation with those views. Create view and assign it by calling findViewById()
ImageView imageView = (ImageView) findViewById(R.id.splash_imageView);
TextView app = (TextView) findViewById(R.id.splash_app);
TextView appAbout = (TextView) findViewById(R.id.splash_appAbout);
set animation with those views and also start the animation
//set animation
imageView.setAnimation(set);
app.setAnimation(set);
appAbout.setAnimation(set);

//start animation
set.start();
That's it now run the app again and see the animation on your splash screen.

Are you confused about this class SplashScreen.java code?
See all the call code below:
public class SplashScreen extends AppCompatActivity {

    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

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

        ImageView imageView = (ImageView) findViewById(R.id.splash_imageView);
        TextView app = (TextView) findViewById(R.id.splash_app);
        TextView appAbout = (TextView) findViewById(R.id.splash_appAbout);


        Animation set = AnimationUtils.loadAnimation(this,
                R.anim.splash_screen_animation);

        //set animation
        imageView.setAnimation(set);
        app.setAnimation(set);
        appAbout.setAnimation(set);

        //start animation
        set.start();

        Thread checkForData = new Thread(){
            @Override
            public void run() {
                super.run();
                try{
                    sleep(1000);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    startActivity(new Intent(SplashActivity.this,
                            MainActivity.class));
                    finish();
               }
             }
         };
        checkForData.start();

    }
}


See full video:

Note: in this video, you can also see the app intro. Link is here: Create Android Material App Intro

That's it 
now you can create a splash screen and also override the loading screen. In this example, I use just the only color but you can also use drawable in the loading time. So it's your choice what you used un your project.

That finished this post.
Why you wasting your time, create an awesome splash screen for your existing or next project?

Thank you for reading this post.
Happy coding.

Android text to speech tutorial

Welcome to this post. In this post, we are going to discuss android text to speech.
Before the start, check the official documentation of Android text to speech.

In my case, I use this option with a fab (Floating action button). When the user clicks on this fab button this text to speech is triggered and user heard the speech.
Let's start,
Implement TextToSpeech.OnIntListener on your activity class.
public class DetailsActivity extends AppCompatActivity implements
        TextToSpeech.OnInitListener {
}

Create an instance of TextToSpeech Class
private TextToSpeech toSpeech;

override onIint() methods and follow below steps:
 1. First, we need to check if Text to speech engine is installed or not
if (status != TextToSpeech.ERROR) {
}
2. If the status is not erroring then we set a default language, we set here the US as default.
int result = toSpeech.setLanguage(Locale.US);
3. now check language data is missing or not supported or not installed then we start for install this text to speech engine.
if (result == TextToSpeech.LANG_MISSING_DATA ||
    result == TextToSpeech.LANG_NOT_SUPPORTED ||
    result == TextToSpeech.ERROR_NOT_INSTALLED_YET) {

      Intent installIntent = new Intent();
      installIntent.setAction(
              TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
      startActivity(installIntent);

}
if you missing something check the full code of onInit() method
@Override
    public void onInit(int status) {

        if (status != TextToSpeech.ERROR) {

            int result = toSpeech.setLanguage(Locale.US);

            if (result == TextToSpeech.LANG_MISSING_DATA ||
                    result == TextToSpeech.LANG_NOT_SUPPORTED ||
                    result == TextToSpeech.ERROR_NOT_INSTALLED_YET) {

                Intent installIntent = new Intent();
                installIntent.setAction(
                        TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);

            }

        }
    }
Create a method and add a single parameter, word as String. In my case, I named it as setTTS() and parameter is word as String,
setTTS(String selectedWord)
private void setTTS(String selectedWord) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            toSpeech.speak(selectedWord, TextToSpeech.QUEUE_FLUSH, null, null);

        } else {
            toSpeech.speak(selectedWord, TextToSpeech.QUEUE_FLUSH, null);
        }

    }
Note: below methods is deprecated. So check if the device is lollipop and higher then use utterance as an extra parameter.

One more thing to go.
We need to shut down this TextToSpeech engine when the activity is destroyed. but before we need to check textToSpeech is null or not to avoid any error. If it is not null the call stop and shutdown method. see the code
@Override
protected void onDestroy() {
   super.onDestroy();
   if (toSpeech != null) {
       toSpeech.stop();
       toSpeech.shutdown();
    }
}

That's it 
you finished writing coding. Now call setTTS() method from anywhere in your project. You can use it as Button onClick or TextView onClick. Just pass a string parameter and call the method. As I told you, at the beginning of this post I am using this option in a fab button. you can that code by the following link. But don't be confused. This is the full activity code, so there is a lot of things with TextToSpeech. Click GitHub link.

Now you can use this code. Hope you understand this TextToSpeech logic. and you will be you use this option in your next or existing project.

Thanks for reading this post.
Happy coding.

Tuesday, September 5, 2017

How to connect firebase directly from android studio

welcome to firebase series.

In this post, we are going to learn about how to connect firebase from the android studio. This is the easiest methods ever.
we can directly connect firebase through the android studio.
Let's start-
open any project or create the new project
I am going throw picture by picture. Follow picture to picture for completing this process.

In android studio click tool and select firebase.
firebase1-androidSketchpad

after click that it will open this window
firebase2-androidSketchpad

Now click any option. In my case, I use analytics
firebase3-androidSketchpad


click log on any event. After it will open this window
firebase4-androidSketchpad

Click connect to firebase
firebase5-androidSketchpad


after the process is finished it will open this window.
firebase6-androidSketchpad

Edit project name (this is for firebase project. it will show in the firebase only)  change your location.
firebase7-androidSketchpad


click on connect to the firebase
firebase8-androidSketchpad

after the finish of this  process, it will show will connect firebase
firebase9-androidSketchpad


succesfully connected now click add analytics to your app
firebase10-androidSketchpad

click accept. it will change your gradle file
firebase11-androidSketchpad

wait for finishing the gradle build.
firebase12-androidSketchpad


after gradle finish, this will show Dependices set up correctly.
firebase13-androidSketchpad

you can add more function by clicking the same process.
firebase14-androidSketchpad

Now go to the firebase console
firebase15-androidSketchpad

this is our newly created process.
firebase15-androidSketchpad

That's it:
we successfully connected our project to firebase. This is the easiest methods ever. you don't need to add JSON file manually. All the file automatically add to your project.

Thank you for reading this post.
Happy coding.


Wednesday, August 30, 2017

How to set sign in anonymously in Firebase

welcome to firebase series tutorial.

In this post, we are going learn about how to sign in anonymously in firebase.
But before starting, I am providing you some ideas why we need sign in anonymously?
If you are using real-time database and storage you need to create a rule for access database and storage.
By default the rule is
{


  "rules": {

    ".read": "auth != null",

    ".write": "auth != null"

  }

}
here auth means Authentication. So if your app hasn't any login option you sign in anonymously sign in from your app. So by doing this, that database and storage can be access only from your app. so you can protect your database. Or if you change the rule to access everyone there is a possibility to lose your database. anyone can delete your database with in a single request.

So we sign in anonymously in Firebase from our app to protect database and storage.

Let's start,
you already know how to connect Firebase for your project.
now go to firebase console and select authentication.
click this to go directly Firebase Console.
Now go to sign in method

firebase-auth

and click anonymous and enable it.
firebase-auth1

that's the ending of the configuration of firebase console
now time for coding
Note: I use kotlin as a default language.

add below line to your build.gradle file
implementation 'com.google.firebase:firebase-auth:11.2.0'
Now create an instance of FirebaseAuth class
see the code-
val mAuth = FirebaseAuth.getInstance()
use signInAnonymously() method and add a complete listener. if the task is successful we show a message that Authentication is successful and also user id. if failed then we will show a fail message.
mAuth.signInAnonymously()
     .addOnCompleteListener(this, { task ->
         if (task.isSuccessful) {
                val user = mAuth.currentUser
                Toast.makeText(this, "Authentication successful. user id ${user.uid}",
                                Toast.LENGTH_SHORT).show()

            } else {
                // If the sign in fails displays a message to the user.
                Toast.makeText(this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show()

                    }
                })
That's it coding see the final screen short in the firebase console
firebase-auth android sketchpad
you find some details about your user
1. creation date
2. signed in date
3. user id

That's it from this post hope this will help you to understand this concept.
and you will implement anonymous login option for your app and make a better security for your Firebase database and storage.
Happy coding

Saturday, August 19, 2017

Kotlin null safety

Welcome to kotlin Series

In this post, we are going to discuss a very important topic of Kotlin. The topic is kotlin null safety.
I think you already heard this keyword, null safety, Kotlin is a null safety language. right?
what is the null safety? In kotlin by default, you can not assign a value of a variable as null. All the variable must have a value.

but if you want an assign a variable as null, you have to use?
code-
val nullValue:String? = null
if you want to create a variable but want to assign a value later then use
var name:String?
name = "shudipto"
now print the value
println("Name: $name")
output:
Name: shudipto
now assign this value to null
name = null
print this new value
println(name)
Output:
null
Note: if you want to set this variable must have value then use below code-
print(name!!)
now we create a function that returns null
//null return function
fun returnNull():String? {
    return null
}
print this value:
 println("Function: ${returnNull()}")
Output:
 println("Function: ${returnNull()}")
now we use the force operator to assign the return value of this methods
val returnNull1:String ?= returnNull()
now if we want to learn the length of this variable we can use length method
//val returnNull2 = returnNull1.length
but this line shows an error because the value of the variable is null. This is the advantage of kotlin. If you are in java the here this line program will be crashed. but in kotlin, we can do by this way without any crash
val returnNull2 = returnNull1?.length
Now, this program will not crash. but you can do another thing that is if the value is null then you can save a string or default value I am using a string
val returnNull2 = returnNull1?.length ?: "value is null"
print the value
println("ReturnNull2: $returnNull2")
output:
ReturnNull2: value is null
see the variable value is null so the default value is assigned. you can also use this method for the specific data type variable:
val returnNull4:String = returnNull() ?: "No name"
print the value:
println(returnNull4)
Output:
No name
That's it. Hope you understand the concept. This is very important in Android App development. It prevent some unexpected crash.

Thank you very much.
Happy coding