Pass parameters safely and quickly between activities or fragments.

Overview

Bracer

Pass parameters safely and quickly between activities or fragments.

Read this in other languages: 中文, English, Change Log

Prepare

  1. Add the JitPack repository to your build file
allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}
  1. Add the dependency
dependencies {
	implementation 'com.github.ssseasonnn:Bracer:1.0.3'
}

First Blood

Dear, it's all 2020. Are you still writing such code?

val param1 = intent.getStringExtra("param1")
//param1 may be null, so we have to determine null
if (param1 != null) {
    //using param1
}

Or:

class ActivityB : AppCompatActivity() {
    private fun gotoActivityA() {
        val intent = Intent(this, ActivityA::class.java)
        intent.putExtra("key_1", "123")
        startActivity(intent)
    }
}

class ActivityA : AppCompatActivity() {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //oh shit, wtf!! 写错了key的名字,导致一直获取不到值
        val valueA = intent.getStringExtra("key_l")
        
    }
}

more than this:

//Oh my god! Does every Fragment need to be written like this?
class FragmentA : Fragment() {
    var a: String = ""
    var b: String = ""

    companion object {
        fun newFragment(a: String, b: String): FragmentA {
            val fragmentA = FragmentA()
            val bundle = Bundle()
            bundle.putString("key_a", a)
            bundle.putString("key_b", b)
            fragmentA.arguments = bundle
            return fragmentA
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            a = it.getString("key_a") ?: ""
            b = it.getString("key_b") ?: ""
        }
    }
}

I just want to simply pass a parameter, why should I write so much code? ? ? I am so tired...

Don't be afraid, now you have ** Bracer !! **

Double kill

Let's see how the new century should pass parameters correctly

Get parameters in Fragment:

class MutableParamsFragment : Fragment() {
    //basic type
    var intParams by mutableParams<Int>()
    var booleanParams by mutableParams<Boolean>()
    var stringParams by mutableParams<String>()

    //Custom type
    var customParams by mutableParams<CustomParams1>()

    //list
    var intListParams by mutableParams<ArrayList<Int>>()
    var stringListParams by mutableParams<ArrayList<String>>()
    
    //array
    var intArrayParams by mutableParams<IntArray>()
    var arrayCustomParams by mutableParams<Array<CustomParams1>>()

    //Any other type
    //...

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //Use directly, no need to manually read from Arguments
        println(intParams)
        println(booleanParams)
        println(stringParams)
        println(customParams)
        println(intListParams)
        println(stringListParams)
        println(intArrayParams)

    }
}

As you can see, getting parameters from Fragment is so simple and very safe! !!

And supports almost all types!

You will no longer encounter null pointer null, all parameters will have default values; You won't encounter wrong key writing. All parameters use their own names as keys by default.

Equivalent to: val byteParams = arguments.getByte("byteParams", 0) var stringParams = arguments.getString("stringParams") ?: ""

Let's see how to pass parameters:

val fragment = MutableParamsFragment().apply {
    intParams = 1  //Just assign
    booleanParams = true
    stringParams = "123"

    customParams = CustomParams1()
    intListParams = arrayListOf(1,2,3)

    intArrayParams = IntArray(2) { it }
}

//show this Fragment
val beginTransaction = supportFragmentManager.beginTransaction()
beginTransaction.add(R.id.frameLayout, fragment, "")
beginTransaction.commit()

Amazing!! Yes, it is so magical, passing parameters is as simple as that!

Double Kill

Let ’s take a look at Activity

class MutableParamsActivity : AppCompatActivity() {
    //basic type
    var intParams by mutableParams<Int>()
    var booleanParams by mutableParams<Boolean>()
    var stringParams by mutableParams<String>()

    //Custom type
    var customParams by mutableParams<CustomParams1>()

    //list
    var intListParams by mutableParams<ArrayList<Int>>()
    var stringListParams by mutableParams<ArrayList<String>>()
    
    //array
    var intArrayParams by mutableParams<IntArray>()
    var arrayCustomParams by mutableParams<Array<CustomParams1>>()

    //Any other type
    //...

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

        //Use it directly, no need to manually read from Intent anymore
        println(intParams)
        println(booleanParams)
        println(stringParams)
        println(customParams)
        println(intListParams)
        println(stringListParams)
        println(intArrayParams)

    }
}

Similar to Fragment, getting parameters from Activity is still so simple and still very safe! !! You will no longer encounter null pointer null, all parameters will have default values; You won't encounter wrong key writing. All parameters use their own names as keys by default.

Equivalent to: val byteParams = intent.getByteExtra("byteParams", 0) var stringParams = intent.getStringExtra("stringParams") ?: ""

Let's see how to pass parameters:

MutableParamsActivity().apply {
    intParams = 1  //Just assign
    booleanParams = true
    stringParams = "123"

    customParams = CustomParams1()
    intListParams = arrayListOf(1,2,3)

    intArrayParams = IntArray(2) { it }
}.start(context)

? ? ? Are you sure you wrote correctly? Why can we create an Activity? ? ?

Yes, it ’s so amazing, it is almost the same as Fragment usage, just a little bit of a show!

Triple Kill

In addition, Bracer also supports some other features.

For example a custom key:

var customKeyParams by mutableParams<Byte>("this is custom key")

Or support custom defaults:

var defaultParams by mutableParams<BigDecimal>(defaultValue = BigDecimal.ONE)

Radiant wins, GG

License

Copyright 2019 Season.Zlc

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...
AnyText - An Xposed module trying to hook TextView in any activities

AnyText What's this This application provides features to modify any TextView in

This application is purpose to help user create todo activities.
This application is purpose to help user create todo activities.

To Do This application is purpose to help user create todo activities. Download App Features List Tasks Sort Tasks Add, Update and Delete Task Clean a

Communicating between Wear OS and Android device using the OpWear module and a sample of displaying real-time camera on the watch and sending commands to the mobile by Wear OS.
Communicating between Wear OS and Android device using the OpWear module and a sample of displaying real-time camera on the watch and sending commands to the mobile by Wear OS.

OpWear-Cam Communicating between Wear OS and Android device using the OpWear module and a sample of displaying real-time camera on the watch and sendi

Sync DND state between Android phone and watch
Sync DND state between Android phone and watch

DNDSync This App was developed to enable Do Not Disturb (DND) synchronization between my Pixel phone and the Galaxy Watch 4 since this option was only

Sample app demonstrating interop between Jetpack Compose and the Android UI toolkit, including SurfaceView
Sample app demonstrating interop between Jetpack Compose and the Android UI toolkit, including SurfaceView

Wake Me Up Wake Me Up is a sample app showcased in the Google I/O 2021 Developer Keynote that demonstrates interoperability between Jetpack Compose an

Link previews between JetBrains Space and Slack

slack-unfurls This is the application for providing link previews between Slack and Space in both directions. It provides link previews for Slack mess

Endoscope lets you to stream live video between android devices over Wi-Fi! 📱📲
Endoscope lets you to stream live video between android devices over Wi-Fi! 📱📲

Endoscope - RTSP live video streamer for android devices via Wi-Fi. Project is no longer supported. Alternative solution is under development. Stay tu

Warscape core library. Includes common models for sharing between platforms.

warscope-core This repository uses for sharing common models between backend and frontend sides. Implementation $version available at top of README.md

An Android Library for in-app switching between environment variables

android-env-picker An Android Library for in-app switching between environment variables. Central use case is picking a desired endpoint for backend c

Comments
  • 混淆之后有错误

    混淆之后有错误

    java.lang.IllegalStateException: Incomplete hierarchy for class ArticleDetailActivity, unresolved classes [ch.ielse.view.imagewatcher.ImageWatcher.OnPictureLongPressListener, ch.ielse.view.imagewatcher.ImageWatcher.Loader, com.scwang.smart.refresh.layout.listener.OnRefreshListener, com.scwang.smart.refresh.layout.listener.OnLoadMoreListener]
        at kotlin.reflect.jvm.internal.impl.descriptors.runtime.components.RuntimeErrorReporter.reportIncompleteHierarchy(RuntimeErrorReporter.kt:26)
        at kotlin.reflect.jvm.internal.impl.serialization.deserialization.descriptors.DeserializedClassDescriptor$DeserializedClassTypeConstructor.computeSupertypes(DeserializedClassDescriptor.kt:188)
        at kotlin.reflect.jvm.internal.impl.types.AbstractTypeConstructor$supertypes$1.invoke(AbstractTypeConstructor.kt:80)
        at kotlin.reflect.jvm.internal.impl.types.AbstractTypeConstructor$supertypes$1.invoke(AbstractTypeConstructor.kt:26)
        at kotlin.reflect.jvm.internal.impl.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:352)
        at kotlin.reflect.jvm.internal.impl.storage.LockBasedStorageManager$LockBasedNotNullLazyValue.invoke(LockBasedStorageManager.java:408)
        at kotlin.reflect.jvm.internal.impl.types.AbstractTypeConstructor.getSupertypes(AbstractTypeConstructor.kt:27)
        at kotlin.reflect.jvm.internal.impl.serialization.deserialization.descriptors.DeserializedClassDescriptor$DeserializedClassMemberScope.getNonDeclaredVariableNames(DeserializedClassDescriptor.kt:296)
        at kotlin.reflect.jvm.internal.impl.serialization.deserialization.descriptors.DeserializedMemberScope$variableNamesLazy$2.invoke(DeserializedMemberScope.kt:77)
        at kotlin.reflect.jvm.internal.impl.serialization.deserialization.descriptors.DeserializedMemberScope$variableNamesLazy$2.invoke(DeserializedMemberScope.kt:40)
        at kotlin.reflect.jvm.internal.impl.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:352)
        at kotlin.reflect.jvm.internal.impl.storage.LockBasedStorageManager$LockBasedNotNullLazyValue.invoke(LockBasedStorageManager.java:408)
        at kotlin.reflect.jvm.internal.impl.storage.StorageKt.getValue(storage.kt:42)
        at kotlin.reflect.jvm.internal.impl.serialization.deserialization.descriptors.DeserializedMemberScope.getVariableNamesLazy(Unknown Source:7)
        at kotlin.reflect.jvm.internal.impl.serialization.deserialization.descriptors.DeserializedMemberScope.getVariableNames(DeserializedMemberScope.kt:85)
        at kotlin.reflect.jvm.internal.impl.serialization.deserialization.descriptors.DeserializedMemberScope.getContributedVariables(DeserializedMemberScope.kt:164)
        at kotlin.reflect.jvm.internal.impl.serialization.deserialization.descriptors.DeserializedClassDescriptor$DeserializedClassMemberScope.getContributedVariables(DeserializedClassDescriptor.kt:236)
        at kotlin.reflect.jvm.internal.KClassImpl.getProperties(KClassImpl.kt:204)
        at kotlin.reflect.jvm.internal.KDeclarationContainerImpl.findPropertyDescriptor(KDeclarationContainerImpl.kt:109)
        at kotlin.reflect.jvm.internal.KPropertyImpl$_descriptor$1.invoke(KPropertyImpl.kt:102)
        at kotlin.reflect.jvm.internal.KPropertyImpl$_descriptor$1.invoke(KPropertyImpl.kt:27)
        at kotlin.reflect.jvm.internal.ReflectProperties$LazySoftVal.invoke(ReflectProperties.java:92)
        at kotlin.reflect.jvm.internal.KPropertyImpl.getDescriptor(KPropertyImpl.kt:105)
        at kotlin.reflect.jvm.internal.KPropertyImpl.getDescriptor(KPropertyImpl.kt:27)
        at kotlin.reflect.jvm.internal.KCallableImpl$_returnType$1.invoke(KCallableImpl.kt:74)
        at kotlin.reflect.jvm.internal.KCallableImpl$_returnType$1.invoke(KCallableImpl.kt:21)
        at kotlin.reflect.jvm.internal.ReflectProperties$LazySoftVal.invoke(ReflectProperties.java:92)
        at kotlin.reflect.jvm.internal.KCallableImpl.getReturnType(KCallableImpl.kt:80)
        at zlc.season.bracer.e.b(Util.kt:447)
        at zlc.season.bracer.a.a(ActivityParams.kt:38)
    

    E/AndroidRuntime: at com.android.debug.ui.fragment.HomeFragment.onItemClick(HomeFragment.kt:132)

            ArticleDetailActivity().apply {
                mArticleId = article.id  :132
                recommendArticle = article
            }.start(this)
    
    opened by ff-frida 4
Owner
Season
会写点代码
Season
Native-loader - Safely load native libraries in Java

Native Loader ??️ Safe native loading in Java based off of the native-loader use

Mixtape 1 Oct 19, 2022
Android app for removing tracking parameters from shared URLs

Léon - The URL Cleaner is an Android application which removes tracking and other obsolete parameters from a URL before sharing. Its usage is simple,

Sven Jacobs 89 Dec 30, 2022
Environmental-Monitoring-Android-App - This Android App is used to monitor environmental parameters data from remote sensors

Environmental-Monitoring-Android-App - This Android App is used to monitor environmental parameters data from remote sensors. Parameters includes but not limited to temperature, humidity, air quality, level of Ionizing radiation, ...

Francisco Pascal Elias TAMBASAFIDY 0 Jan 4, 2022
Android application compatible with ZX2C4's Pass command line application

Password Store Download Documentation We're in the process of rewriting our documentation from scratch, and the work-in-progress state can be seen her

Android Password Store 2.2k Jan 8, 2023
Asteroid Radar is an app that allow you to view the asteroids detected by NASA that pass near Earth

Asteroid-radar Asteroid Radar is an app that allow you to view the asteroids detected by NASA that pass near Earth. you can view all the detected aste

Ana Stanescu 5 Aug 6, 2022
Get a libGDX-powered Android live wallpaper up and running quickly with this project template

This project is a libGDX Android live wallpaper template. It's the demo application created by the libGDX code generator, remade as a live wallpaper.

Kurtis LoVerde 1 Jun 30, 2022
DessertPusher - A dessert app displaying the functionalities of activity lifecycle and fragments

Activity Lifecycle - DessertPusher This is the toy app for lesson 4 of the Andro

Brian Kubai 0 Jan 18, 2022
A lightweight, feature-rich wrapper for the Telegram Bot API, providing a handy Kotlin DSL to quickly build your bot.

Kotlin Telegram Bot Kotlin based wrapper over Telegram API. Current version of the Telegram Api: 6.0 Principles Annotations Magic. The basic interacti

Jey 61 Dec 27, 2022
Android Package Inspector - dynamic analysis with api hooks, start unexported activities and more. (Xposed Module)

Inspeckage - Android Package Inspector Inspeckage is a tool developed to offer dynamic analysis of Android applications. By applying hooks to function

acpm 2.5k Jan 8, 2023
App consist of 4 main fragments accessable from bottom navigation

Bug demo Demo App consist of 4 main fragments accessable from bottom navigation, each fragment is a tablayout hosting 2 more child fragment, child fra

Babish 0 Nov 21, 2021