Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Wednesday 11 July 2018

Difference between run, with, let, also and apply in kotlin

Hello dear friends today we are learn about what difference in run, with, let, also and apply . This is master function of the kotlin.

Kotlin  let: 

let take the object is invoked upon as the parameter and return the result of the lambda expression. In other word we also said let is a non-nomadic version of map. It is accept the object as a parameters and returns the result of the lambda. like...

Example 1: 
var student= Student("samset",100)
var result = student.let{ it.rollno=50}

Log.e(" student roll no : "+student)
Log.e("result student roll no : "+result)

OUTPUT:
100
50

here it keyword copy of the property inside the let. let function scope only inside the expression cannot be used outside of the expression.

Example 2: 

 var strlength = str.let { "$it my function".length}
 println("strlength is $strlength") // strlength is 30


class MyTestClass{

   fun testfunction(){
     val str : String = "welcome to kotlin"
     val myresult = str.let{
      
    print(this) // this is instance of MyTestClass 
    print(it)   // it is the  String = "welcome to kotlin" on which we have called let

}
}
}

Chaining let functon:


val strmain="welcome"

// Evolve the value and send to the next chain
 strmain.let{
   println("This is main original string $it") // "welcome"
   it.reversed() // evolve it as parameter to send to next let
}.let{
println("This is reverse string $it") // "emoclew"
it.length   // evolve it as parameter to next let
}.let{
   println("The length of string is $it")  // 7
}

 Outer let:
After nested let used now we are use outer let:

var str="Smaset"
     
      str = str.let{ outer->
        
        outer.let{ inner->
                println(" Inner let is "$inner)
      }
     "Outerlet is $outer"
      }

    println(str)


OUTPUT:

Inner let is samset
Outer let is samset

let check Null:

    var strmain = String? = "welcome"
   strmain ?.let{ println(it)}  // prints welcome
 
    strmain =null
    strmain ?.let{ println(it)} // nothing happens

Kotlin run:

Kotlin run is another interesting function. The following example demonstrates its use cases. run does not return values and does not support it keyword.
var str  =  "Hello welcome to kotlin"
    println(str) //  "Hello welcome to kotlin"
      val str  = "This is a run function" str
}
println(str) // This is a run function

OUTPUT:
  Hello welcome to kotlin
   This is a run function


let with run

      var mytext : String? = null
     
    p?.let{ println(" Text is $mytext ")} ?:
        run { println("Text was null so set default value :"+ mytext ="Default text")}

        println(mytext)


OUTPUT:

Text was null so set default value : Default text 

Kotlin let vs also
also is something same like let but this is return only original value. Rhe also expression return the data class object whereas th let expression return nothing (Unit) as we didn't specify anything explicitly see example for understanding...


   data class Student(var name: String,var rollno : int)
   var stud  = Student("Samset",101)
   
   var s  =  stud.let{ it.name = "sanjoo"}
   var salso  =  stud.also{ it.name = "sanjoo"}

println(s)
println(salso)
println(stud)

OUTPUT:

sanjoo
sanjoo


























Friday 6 July 2018

Jetpack Navigation

Hello guys today we are learn about how to manage fragment navigation with jetpack library but before learn about navigation first you learn about What is Jetpack library?.


JetPack:
Android JetPack is a set of android components designed with Kotlin in mind, available with Android Studio 3.2.


Google’s annual I/O developer conference is where the company unveils their latest tools and features for Android developers, and this year is no exception. Today, the company announced Android Jetpack, a set of components to accelerate app development. Jetpack is designed with Kotlin in mind to help you simplify your code. The latest Android Studio 3.2 canary available today also features new tools for Jetpack.

Accelerating app development with Android JetPack

Android Jetpack is a set of Android components, tools, and guidance inspired by the backward compatibility of the Support Library and the ease of use of the Android Architecture Components. Jetpack components can broadly be categorized into four categories: Architecture, UI, Foundation, and Behavior.
Architecture components include activities like lifecycle management, ViewModel, data binding, and more. UI components include animation and transitions, fragments, layouts, and more. Foundation components include AppCompat, Multidex, testing, and more. Behavior components include media and playback, permissions, notifications, sharing and more.





WorkManager

This library provides an API for constraint-based background jobs that must be executed, replacing the need for jobs or SyncAdapters. It works on devices without Google Play Services, can create graphs of work, and can query the state of your work.

Navigation

Many applications are composed of multiple activities, but sharing data between activities and implementing transitions has been a pain-point for in-app navigation. The Navigation component will help you structure your in-app user interface as a single-Activity app. It supports Fragments out of the box so all the benefits of Architecture Components such as Lifecycle and ViewModel are there while the Navigation component handles FragmentTransitions for you. Furthermore, you can declare transitions that Navigation will automatically handle, you can build with the correct Up and Back behavior automatically, you can easily provide full support for deep links, and you can connect Navigation to UI widgets like the navigation drawer and bottom navigation. Lastly, the Navigation Editor in the latest Android Studio allows you to visually manage navigation properties

Paging

The Paging component, when combined with RecyclerView, allows you to add fast, infinite scrolling to your app. The idea is that the component simplifies managing data in pages, ie. pulling chunks of data in succession as quickly as possible and returning results for the user to view.

Slices

Lastly, the Slices component will simplify the process of implementing the Slices API introduced with Android P. It’s an API that lets you surface your app’s UI inside of the Google App as a search result.

Now you create a sample project and follow  below instructions :
If you had create new project then add these two line dependency and two line top of gradle in app level gradle like..

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'androidx.navigation.safeargs'
implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha02'
implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-alpha02'

Complete gradle file like :
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'androidx.navigation.safeargs'
android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.samset.jetpacknavigation"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-alpha1'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.0'
    implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha02'
    implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-alpha02'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0-alpha1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'
}
and project level gradle look like this 
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = '1.2.50'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0-alpha18'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0-alpha02'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        google()
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}
and now open open gradle.properties file and paste these two line

android.enableJetifier=trueandroid.useAndroidX=true

And now you create navigation xml
First you right click on res folder and create new resource file and now select resource type is "Navigation" and enter file name navigation_graph and press OK


Create tow or three fragment and follow some instructions

FragmentOne.kt

class FragmentOne : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_one, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        /*
        * here i am navigate(transaction fragment first to second)
        * fragment with direction function you can choose another function
        * you can see second fragment tranction i am use another funtions for the transaction
        *
        * */
        btnNext1.setOnClickListener{
            var directions=FragmentOneDirections.action_fragmentSecond()
            // if you send data in bundle you can pass directly here
            directions.setMydata("Hello I am passed data from fragment one")
            var  controller=it.findNavController()
            controller.navigate(directions)
        }
    }
}

In FragmentOne i am use simple fragment transaction and you can pass data.

FragmentSecond.kt

class FragmentSecvond : Fragment() {
    internal var infos = User()
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_secvond, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        arguments?.let {
            var values=FragmentSecvondArgs.fromBundle(it)
            tvnames.text=values.mydata
        }
        /*
        * here i am set custom data in bundle with seralizable
        * */
        btnNext2.setOnClickListener{
            infos.username=" i am samset"
            infos.mobilenumber="98110540xxx"
            val bundle = Bundle()
            bundle.putSerializable("data",infos)
            val navController = it.findNavController()
            navController.navigate(R.id.fragmentThird,bundle)
        }
    }
}

In secondfragment you can see how to pass custom serialisable data to thirdfragment.


NOTE:-
If you want Maintain fragment backstack then override this method in your MainActivity

override fun onSupportNavigateUp()=findNavController(R.id.mainNavigationFragment).navigateUp()


If you want  not maintain the backstack specific fragment then you add one line of code in navigation_graph like..

<fragment
    android:id="@+id/fragmentSecvond"
    android:name="com.samset.jetpacknavigation.fragments.FragmentSecond"
    android:label="fragment_fragment_secvond"
    tools:layout="@layout/fragment_fragment_secvond">
    <argument
        android:name="mydata"
        android:defaultValue="defaulttext"
        app:type="string" />
    <action
        android:id="@+id/action_fragmentSecvond_to_fragmentThird"
        app:clearTask="true"   // add this line for clear backstack
        app:destination="@id/fragmentThird" />

</fragment>

You can also be change the action "Pop To" behavior from attribute pannel( from xml app:popUpTo="@+id/FragmentOne). This way when user will click back, he will be navigated to FragmentOne instead of the original destination.

<fragment
    android:id="@+id/fragmentThird"
    android:name="com.samset.jetpacknavigation.fragments.FragmentThird"
    android:label="fragment_fragment_third"
    tools:layout="@layout/fragment_fragment_third">
    <action
        android:id="@+id/action_fragmentThird_to_fragmentFourth"
        app:destination="@id/fragmentFourth" />
    <action
        app:popUpTo="@id/action_fragmentSecond" // add this line and change pop to destination
        android:id="@+id/action_fragmentThird_to_fragmentOne"
        app:destination="@id/fragmentOne" />

</fragment>


Thank you

Full SourceCode JetPack-Navigation