Binding your extras more easier, more simpler for your Android project

Related tags

Kotlin Projects Ktan
Overview

Ktan

GitHub

Ktan make your intent / arguments more easier and readable. And most important, will help you bind all extras for your activity / fragment. And also support for java ❤️ .

How to use

  1. Add jitpack repository at root gradle

    allprojects {  
         repositories { 
             maven { url 'https://jitpack.io' } 
         }
    }  
  2. Implement our library

    // in your root gradle
    buildscript {
       dependencies {
          ...
          // add this classpath to use ksp
          classpath "com.google.devtools.ksp:com.google.devtools.ksp.gradle.plugin:$ksp_version"
       }
    }
    
    // in your app gradle
    plugins {
       ...
       // Add this to implement ksp
       id 'com.google.devtools.ksp'
    }
    
    ksp {
       // put this arg to turn on LiveData for all extra
       arg("com.ktan.processor.LIVE_DATA", "true")
    }
    
    android {
       buildTypes {
          release {
             sourceSets {
                main {
                   // Add this to implement ksp
                   java { srcDirs = ["src/main", "build/generated/ksp/release"] }
                }
             }
          }
          debug {
             sourceSets {
                main {
                   // Add this to implement ksp
                   java { srcDirs = ["src/main", "build/generated/ksp/debug"] }
                }
             }
          }
       }
    }
    
    dependencies {  
         // Ktan implementation
         implementation "com.github.adef145.Ktan:ktan:$latest_version"
         ksp "com.github.adef145.Ktan:ktan-processor:$latest_version"  
         
         // Optional: Parceler integration implementation
         implementation "com.github.adef145.Ktan:ktan-parceler:$latest_version"
    
         // Optional: LiveData integration implementation
         implementation("com.github.adef145.Ktan:ktan-livedata:$latest_version") {
             // put this line in case your targetSdkVersion below 32
             exclude group: 'androidx.appcompat'
         }
    }  

    For more detail about ksp, you can read in here

  3. Init Ktan on your Application.onCreate

    Kotlin

    class YourApplication : Application() {   
         
         override fun onCreate() { 
             Ktan.init(this) 
         }
    }  

    Java

    public class YourApplication extends Application {  
        @Override  
        public void onCreate() { 
            Ktan.init(this); 
        }
    }  
  4. Create extras for your Activity

    Kotlin

    @Extras
    class YourActivityExtras {  
         
         @Required // to define this extra is required and non null
         @Mutable // to define this extra is mutable (var)
         // define extra with default value 
         val id = IntExtra("id_extra", 0) 
         
         // define extra without default value and nullable 
         val name = StringExtra("name_extra")
    
         @Mutable // to define MutableLiveData instead of LiveData
         @Required // to define this extra is required and non null when observe
         @LiveExtra // to define this extra as LiveData when Binding 
         val nameLive = StringExtra("name_live_extra")
    }  

    Java

    @Extras
    public class YourActivityExtras {  
         
         @Required // to define this extra is required and non null
         @Mutable // to define this extra is mutable (var)
         // define extra with default value 
         public IntExtra id = new IntExtra("id_extra", 0); 
         
         // define extra without default value and nullable 
         public StringExtra name = StringExtra("name_extra");
    
         @Mutable // to define MutableLiveData instead of LiveData
         @Required // to define this extra is required and non null when observe
         @LiveExtra // to define this extra as LiveData when Binding
         public StringExtra nameLive = StringExtra("name_extra");
    }  

    With this class, ksp processor will create one file with name YourActivityExtrasKtan. And in this file, will contains 2 class YourActivityExtrasBinding and YourActivityExtrasRouter, also contains 2 extension function Intent.populateYourActivityExtras and Bundle.populateYourActivityExtras

    class YourActivityExtrasBinding(extras: YourActivityExtras = YourActivityExtras()) : ExtrasBinding() {
         
         var id: Int by requiredExtraOf(extras.id)
         val name: String? by extraOf(extas.name) // by default all extra is nullable if not annotated with Required
         val nameLive: MutableLiveData<String> by mutableLiveExtraOf(extas.name)
         
    }
    
    class YourActivityExtrasRouter(block: YourActivityExtras.() -> Unit) : KtanRouter() {
    
         var id: Int by requiredExtraOf(extras.id)
         var name: String? by extraOf(extas.name)
         var nameLive: String by extraOf(extas.nameLive)
    
         init {
             block.invoke(this)
         }
    
    }
    
    fun Intent.populateYourActivityExtras(block: YourActivityExtrasRouter.() -> Unit): Intent {
       YourActivityExtrasRouter(block).populate(this)
       return this
    }
    
    fun Bundle.populateYourActivityExtras(block: YourActivityExtrasRouter.() -> Unit): Bundle {
       YourActivityExtrasRouter(block).populate(this)
       return this
    }
  5. Bind your extras binding to your activity. And annotate with @Route in YourActivity

    Kotlin

    // Annotate this activity to create route file
    @Route(
       // define extras that will work for open YourActivity. Can multiple
       extras = [YorActivityExtras::class]
    )
    class YourActivity : AppCompatActivity() {  
         
         val extrasBinding: YourActivityExtrasBinding by bindExtras()  
    }  

    Java

    // Annotate this activity to create route file
    @Route(
         // define extras that will work for open YourActivity. Can multiple
         extras = {YourActivityExtras.class}
    )
    public class YourActivity extends AppCompatActivity {  
         
         private final YourActivityExtrasBinding extrasBinding = new YourActivityExtrasBinding();  
         
         @Override  
         protected void onCreate(@Nullable Bundle savedInstanceState) {
             ExtrasBindingKt.bindExtras(this, extrasBinding); 
         }
    }  

    With route annotation, the processor will create a file YourActivityRoute, and contains extension function to route this activity

    fun routeToYourActivity(
         context: Context, 
         yourActivityExtrasRouterBlock: YourActivityExtrasRouter.() -> Unit): Intent {
         return = Intent(context, YourActivity::class)
             .populateYourActivityExtras(yourActivityExtrasRouterBlock)
    }
    
    fun Activity.routeToYourActivity( 
         yourActivityExtrasRouterBlock: YourActivityExtrasRouter.() -> Unit): Intent {
         return routeToExampleActivity(this, yourActivityExtrasRouterBlock)
    }
    
    fun Fragment.routeToYourActivity( 
         yourActivityExtrasRouterBlock: YourActivityExtrasRouter.() -> Unit): Intent? {
         return context?.let { routeToExampleActivity(it, yourActivityExtrasRouterBlock) }
    }

    You can use this extension function to open YourActivity

  6. How to use your router

    Kotlin

    class YourActivity : AppCompatActivity() {  
    
         fun someMethod() {  
             startActivity(
                Intent(context, YourActivity::class).populateYourActivityExtras {
                   id = 1
                   name = "Set your name here"
                   nameLive = "Set your nameLive here"
                }
             }
             // or you can use extention function that created from @Route annotation
             startActivity(routeToYourActivity {
                id = 1
                name = "Set your name here"   
                nameLive = "Set your name live here"
             })
         }  

    Java

    public class YourActivity extends AppCompatActivity {  
    
         public void someMethod() {  
             startActivity(
                YourActivityExtrasKtanKt
                   .populateYourActivityExtras(new Intent(context, YourActivity.class), router -> {
                      router.setId(1);
                      router.setName("Set your name here");
                      router.setNameLive("Set your name live here");
                      return Unit.INSTANCE;
                   })
             ); 
             // or you can use extention function that created from @Route annotation
             startActivity(YourActivityRouteKt.routeToYourActivity(router -> {
                router.setId(1);
                router.setName("Set your name here");
                router.setNameLive("Set your name live here");
                return Unit.INSTANCE;
             }));
         }
    }  
  7. You can also use Ktan for your activity result

    Kotlin

    class YourActivity : AppCompatActivity() {
    
         fun setResultForPreviousActivity() {
             setResult(Activity.RESULT_OK, Intent().populateExampleActivityResultExtras {
                 id = idEditText.text.toString().toInt()
             })
         }
    
         override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
             super.onActivityResult(requestCode, resultCode, data)
             val resultBinding: ExampleActivityResultExtrasBinding? = data?.bindExtras()
             Toast.makeText(this, "This is the result ${resultBinding?.id}", Toast.LENGTH_SHORT).show()
         }
    }  
    
    @Extras
    class ExampleActivityResultExtras {
       val id = IntExtras("id", 0)
    }

    Java

    public class YourActivity extends AppCompatActivity {
    
         public void setResultForPreviousActivity() {
             setResult(Activity.RESULT_OK, ExampleActivityResultExtrasKtanKt.populateExampleActivityResultExtras(new Intent(), router -> {
                 router.setId(1);
                 return Unit.INSTANCE;
             }));
         }
    
         @Override
         public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
             super.onActivityResult(requestCode, resultCode, data);
             ExampleActivityResultExtrasBinding resultBinding = ExtrasBindintKt.bindExtras(data, new ExampleActivityResultExtrasBinding());
             Toast.makeText(this, "This is the result " + resultBinding.getId(), Toast.LENGTH_SHORT).show();
         }
    }  
    
    @Extras
    public class ExampleActivityResultExtras {
       public IntExtras id = new IntExtras("id", 0);
    }

Yap, that all how to use Ktan for your project. And no need handle for savedInstanceState, because for mutable extra with var by default will handle your onSavedInstanceState And also, will work for Fragment.

MIT License

Copyright (c) 2022 Ade Fruandta

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
You might also like...
📦📦Video downloader for Android - Download videos from Youtube, Facebook, Twitter, Instagram, Dailymotion, Vimeo and more than 1000 other sites
📦📦Video downloader for Android - Download videos from Youtube, Facebook, Twitter, Instagram, Dailymotion, Vimeo and more than 1000 other sites

youtube-dl-android 📦 An Android client for youtube-dl: https://github.com/rg3/youtube-dl Major technologies Language: Kotlin Architecture: MVVM Andro

Kadrekka is a library that aims to make Kotlin more accessible to the northern italian population

Kadrekka Kadrekka is a library that aims to make Kotlin more accessible to the northern italian population. It provides lots of utility functions to m

Helper functions for making Approvals-Java more Kotlin friendly

Approvals-Kt Helper functions for making Approvals-Java more Kotlin-friendly Usage Verify using Approvals-Kt import com.github.greghynds.approvals.Kot

From 8-10 October 2021 there was VTB MORE tech 3.0, where the DUCK team presented their solution.
From 8-10 October 2021 there was VTB MORE tech 3.0, where the DUCK team presented their solution.

InvestmentGuideVTB Ссылка на репозиторий с бэкендом приложения: https://github.com/disarrik/vtbBackend Процесс сегментация происходит в отдельном окне

Ktor is an asynchronous framework for creating microservices, web applications and more.
Ktor is an asynchronous framework for creating microservices, web applications and more.

ktor-sample Ktor is an asynchronous framework for creating microservices, web applications and more. Written in Kotlin from the ground up. Application

Share MPS code snippets. More than just screenshots.

skadi gist Share MPS code snippets. More than just screenshots. Repository Content ide-plugin: MPS Plugin that creates a gist from the IDE written in

Learn-kotlin - Learning more about Kotlin in various content

Kotlin study roadmap https://kotlinlang.org/docs/reference/ Getting Started Basi

One app for all women that covers everything from safety to health and more. 👩💪

sampoorna Sampoorna is a one-in-all solution concept revolving around the women who fight one on one with various problems. With it's features encapsu

An Android template you can use to build your project with gradle kotlin dsl

Android Gradle KTS An Android template you can use to build your project with gradle kotlin dsl Build.gradle.kts You can use your project's build.grad

Releases(1.1)
  • 1.1(Aug 30, 2022)

    Release Highlights

    Having LiveData integration for getting extras data.

    Features

    • Annotation @LiveExtra. To help processor to generate LiveData data type on Binding class. And also can combine with another annotation likes:
      • Annotation @Required. To define non null when receive the data from observe.
      • Annotation @Mutable. To define as MutableLiveData instead of LiveData.
    Source code(tar.gz)
    Source code(zip)
  • 1.0(Aug 26, 2022)

    Release Highlights

    This initial version, we try to make easier and simpler to get and put intent extras / arguments. To make it come true, we create some convention to generated some boilerplate function, so we don't need do and write the same things again and again

    Features

    • Annotation @Extras. To help processor to generate Binding and Routing class, and some extension function to populate extras to intent / bundle.
      • Annotation @Required. To define non null extra.
      • Annotation @Mutable. To define extra can modified (var).
    • Annotation @Route. To help processor to generate some extension function to help us to know which extras need to pass to route particular Activity / Fragment.
      • Property extras. To define for particular @Route need several extras
    • Having bindExtras extension function in Activity and Fragment.
    • Having basic Extra class such as:
      • BinderExtra
      • BooleanExtra
      • BundleExtra
      • ByteArrayExtra
      • ByteExtra
      • CharArrayExtra
      • CharExtra
      • CharSequenceArrayExtra
      • CharSequenceExtra
      • DoubleArrayExtra
      • DoubleExtra
      • FloatArrayExtra
      • FloatExtra
      • IntArrayExtra
      • IntExtra
      • LongArrayExtra
      • LongExtra
      • ParcelableArrayExtra
      • ParcelableExtra
      • SerializableExtra
      • ShortArrayExtra
      • ShortExtra
      • SizeExtra
      • SizeFExtra
      • StringArrayExtra
      • StringArrayListExtra
      • StringExtra
    • Having ParcelerExtra to integrate with johncarl81/parceler
    Source code(tar.gz)
    Source code(zip)
Owner
Ade Fruandta
Ade Fruandta
Use Android Data Binding wih Live Data to glue View Model and Android

Gruop-C Spliff Summary Use Android Data Binding wih Live Data to glue View Model and Android. Asynchronous communications implemented with KotlinX Cor

null 2 Nov 21, 2021
BindsAdapter is an Android library to help you create and maintain Adapter class easier via ksp( Kotlin Symbol Processing).

BindsAdapter BindsAdapter is an Android library to help you create and maintain Adapter class easier via ksp( Kotlin Symbol Processing). Installation

Jintin 5 Jul 30, 2022
SeatBookView is an Android Studio Library that helps to make it easier to create Bus, Train, Cinema Theater Seat UI and all functionalities are given.

SeatBookView SeatBookView is an Android Studio Library that helps to make it easier to create Bus ?? , Train ?? , Cinema Theater Seat UI and all funct

Md. Zahidul Islam 3 Oct 15, 2022
Spikot is a Kotlin library to make Spigot development easier

Spikot is a Kotlin library to make Spigot development easier Using Spikot Installation To use spikot add the following to your build.gradle.kts file.

Cody 1 Oct 30, 2021
This library is created to make files uploading and downloading on Aws easier

S3Manager - aws files uploading library This library is created to make files uploading and downloading on Aws easier Features Easy to use Single/mult

Rajesh Khuti 0 Apr 30, 2022
Basic-Android-Project - A Basic Android Project with proper structure and all necessary dependencies

Basic-Android-Project A Basic Android Project with proper structure and all nece

Ameer Hamza 2 Mar 18, 2022
sample project that shows you how you can use Ktor to creat a server for real Project.

Ktor-Sample This is a sample project that shows you how you can use Ktor to creat a server for real Project. What is done Save data to database (Get a

Mohamed Emad 4 Dec 23, 2022
A project that helps us generate the test project to test the Gradle plugin.

Ktlint Gradle Provides the function to generate a Gradle project for us to test your Gradle plugin Latest plugin version: [1.0.0] Table of content How

Jack Chen 5 Jul 20, 2022
Android library to help enter, and more importantly, leave, android "Immersive Mode".

Immersive Lock Android has various ways to full screen an application including locking the screen to prevent accidentally leaving the app. This is pa

Baby Apps 2 May 20, 2022