A collection of small utility functions to make it easier to deal with some otherwise nullable APIs on Android.

Overview

requireKTX

requireKTX is a collection of small utility functions to make it easier to deal with some otherwise nullable APIs on Android, using the same idea as requireContext, requireArguments, and other similar Android SDK methods.

Types that requireKTX provides extensions for:

Why?

Take the example of grabbing a Fragment argument bundle and reading a String ID from it that should always be there: you have two choices, and none of them are great:

// Providing no default value
// Results in a nullable return type, caller has to do null handling
val id: String = requireArguments().getString("user_id")!!

// Providing a (meaningless) default value
// Results in a platform return type, caller has to explicitly type as non-null
val id: String = requireArguments().getString("user_id", "")
if (id == "") { ... } // ... and check to avoid accidentally using the default value

requireKTX provides methods such as requireString so that you can demand that a value be there, or otherwise get an exception:

val id: String = requireArguments().requireString("user_id")

These methods in the library will throw meaningful exceptions based on the error that occurred - see the method docs for details.

getOrNull

To make the nullable case more obvious and explicit, requireKTX also includes getOrNull style methods for everything that it covers with require style methods. These match the conventions of the Kotlin Standard Library, and can make it clearer that null is returned if a value for a key couldn't be fetched.

val userId: String? = requireArguments().getStringOrNull("user_id")

Dependencies

requireKTX is available from MavenCentral.

repositories {
    mavenCentral()
}

It's available in several artifacts which you can import depending on which types you want to get extensions for - see the module descriptions below for more info:

dependencies {
    implementation "co.zsmb:requirektx-bundle:1.2.0"
    implementation "co.zsmb:requirektx-intent:1.2.0"
    implementation "co.zsmb:requirektx-navigation:1.2.0"
    implementation "co.zsmb:requirektx-work:1.2.0"
}

Available modules and extensions

Bundle

Given a Bundle, you can require the following types of values:

// Primitives (examples)
bundle.requireBoolean()
bundle.requireByte()
bundle.requireChar()
bundle.requireDouble()
bundle.requireFloat()

// Reference types
bundle.requireString()
bundle.requireBundle()
bundle.requireCharSequence()
bundle.requireParcelable()
bundle.requireSerializable()

// Arrays (examples)
bundle.requireBooleanArray()
bundle.requireByteArray()
bundle.requireCharArray()
bundle.requireDoubleArray()
bundle.requireFloatArray()

... and many more!

Intent

Given a Intent, you can require its extras Bundle (and then require values from it as seen above):

val extras: Bundle = intent.requireExtras()

Or you can require specific extras directly for various types of values:

// Primitives (examples)
intent.requireBooleanExtra()
intent.requireByteExtra()
intent.requireCharExtra()
intent.requireDoubleExtra()
intent.requireFloatExtra()

// Reference types
intent.requireStringExtra()
intent.requireBundleExtra()
intent.requireCharSequenceExtra()
intent.requireParcelableExtra()
intent.requireSerializableExtra()

// Arrays (examples)
intent.requireBooleanArrayExtra()
intent.requireByteArrayExtra()
intent.requireCharArrayExtra()
intent.requireDoubleArrayExtra()
intent.requireFloatArrayExtra()

... and many more!

NavBackStackEntry

The navigation module provides an extension to require the arguments of a NavBackStackEntry, same as you could do for a Fragment:

val args: Bundle = navBackStackEntry.requireArguments()

WorkManager Data

Given a WorkManager Data object (such as inputData inside a worker), you can require the following types of values:

class SomeWorker : Worker() {
    override fun doWork(): Result {
        // Values
        inputData.requireBoolean()
        inputData.requireByte()
        inputData.requireDouble()
        inputData.requireFloat()
        inputData.requireInt()
        inputData.requireLong()
        inputData.requireString()

        // Arrays
        inputData.requireBooleanArray()
        inputData.requireByteArray()
        inputData.requireDoubleArray()
        inputData.requireFloatArray()
        inputData.requireIntArray()
        inputData.requireLongArray()
        inputData.requireStringArray()

        // ...
    }
}

License

Copyright 2021 Márton Braun

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You might also like...
XClipper is a clipboard manager for Windows & Android which helps to track clipboard activities and makes it easier to interact with them.
XClipper is a clipboard manager for Windows & Android which helps to track clipboard activities and makes it easier to interact with them.

XClipper XClipper is a clipboard manager for Windows & Android which helps to track clipboard activities and makes it easier to interact with them ❤️

General purpose utilities and hash functions for Android and Java (aka java-common)

Essentials Essentials are a collection of general-purpose classes we found useful in many occasions. Beats standard Java API performance, e.g. LongHas

General purpose utilities and hash functions for Android and Java (aka java-common)

Essentials Essentials are a collection of general-purpose classes we found useful in many occasions. Beats standard Java API performance, e.g. LongHas

λRPC allows using code with high-order functions as a service
λRPC allows using code with high-order functions as a service

λRPC Simple native RPC with high order functions support. Inspired by @altavir and Communicator. λRPC allows using code with high-order functions as a

Catch `dd`, `ddd`, `dump`, `sleep` and `ray` functions in your code

catch-debug-code Template ToDo list Create a new IntelliJ Platform Plugin Template project. Get familiar with the template documentation. Verify the p

Utility for detecting and notifying when your Android app goes background / becomes foreground

Foredroid Utility for detecting and notifying when your Android app goes background / becomes foreground. API-level 14+. Usage: Initialise Foreground

A command line utility to help you investigate the sensitive data associated with Macie findings.
A command line utility to help you investigate the sensitive data associated with Macie findings.

Macie Finding Data Reveal This project contains a command line utility to help you investigate the sensitive data associated with Macie findings.

Utility library that utilizes KSP to generate Room type converter classes.

Roomie Roomie is an annotation processing library that utilizes KSP to geaRoomie is an annotation processing library that utilizes KSP to generate TypeConverter classes for Room. TypeConverter classes most often involve same boiler-plate code and Roomie makes it really easy to quickly create them with a single annotation.nerate TypeConverter classes for Room. TypeConverter classes most often invol

 CHAOS - Like a utility knife for discord
CHAOS - Like a utility knife for discord

CHAOS - Like a utility knife for discord. Currently under development. If you feel inclined, please support me by contributing to this project. Or alt

Releases(1.2.0)
Owner
Márton Braun
Android Developer Advocate @GetStream, GDE for Kotlin & Android, Android Tech Editor @raywenderlich, Lecturer @bmeaut.
Márton Braun
A compose friendly way to deal with in app updates on android

In-App update compose A way to make in app updates in compose How to include in your project The library is available via MavenCentral: allprojects {

Stefan Wärting 25 Dec 31, 2022
A beautiful set of predefined colors and a set of color methods to make your Android development life easier.

Colours is a port of the Colours Library for iOS made by my good friend Ben Gordon. You can find that project here. Installation Maven Central Colours

Matthew York 634 Dec 28, 2022
CloudStorageUtil - An Android library to make sync on Google Cloud Storage easier

gCloud Storage Utils An Android library to make sync on Google Cloud Storage eas

Evolve Asia 0 Jul 13, 2022
Useful helpers that make it easier to implement maven-plugin mojos with kotlin

A library that makes writing powerful maven plugins even easier by providing kotlin extensions and convenience functions for common use cases.

TOOListicon 1 Nov 4, 2022
A logger with a small, extensible API which provides utility on top of Android's normal Log class.

This is a logger with a small, extensible API which provides utility on top of Android's normal Log class. I copy this class into all the little apps

Jake Wharton 9.8k Dec 30, 2022
A small utility to record Android device screen to a GIF

RoboGif A small utility to record Android device screen to an optimized GIF so you can paste it to GitHub or a similar service. Requirements Python 2.

Jernej Virag 526 Dec 9, 2022
Small utility used to add Homewizard Energy Socket tiles to Android Quick Settings

TileWizard [Alpha! Unstable!] Settings Result Functionality: Add up to 5 Wi-Fi Energy Sockets to Android Quick Settings. What do you need: Android dev

Niels Masdorp 2 Oct 19, 2021
Small utility to create/restore encrypted backups

Quick Backup Choose some files and quickly create a complete encrypted and compressed file. Usage Clone the repository Run gradlew installShadowDist T

Leonardo Colman 5 Sep 18, 2021
Small command-line utility to safely merge multiple WhatsApp backups (msgstore.db) into one.

whatsapp-database-merger A small command-line utility that can be used to merge multiple WhatsApp databases (msgstore.db) into one. A few notes: input

Mattia Iavarone 31 Dec 27, 2022
Utility tool to make you a computer ninja.

Cmd Window Never spend 6 minutes doing something by hand when you can spend 6 hours failing to automate it - Zhuowej Zhang What is this about? This to

Marcin Radoszewski 3 Feb 1, 2022