Code Monkey home page Code Monkey logo

dobdroidmiscutils's Introduction

DobDroidMiscUtils

A small and useful set of Android utility classes written in kotlin to reduce boilerplate

Import

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}
dependencies {
    implementation 'com.github.andob:DobDroidMiscUtils:v1.0.7'
}

Table of Contents

  1. ToolbarX
  2. BottomNavigationViewX
  3. ViewPagerX
  4. EditTextX
  5. ScreenSize
  6. PermissionsHandler
  7. Keyboard
  8. FileManager
  9. RetrofitX
  10. CacheDelegate
  11. Async
  12. Library dependencies

ToolbarX

Toolbar eXtension methods. To setup a toolbar with back button:

toolbar.setupBackIcon()

Toolbar with menu on the right:

toolbar.setMenu(R.menu.menu_main)
toolbar[R.id.add] = {
    Log.e("a", "add logic")
}
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      tools:context=".MainActivity">
    <item
        android:id="@+id/add"
        android:title="Add"
        app:showAsAction="always" />
</menu>

If you are using menu or back button, override:

override fun onCreateOptionsMenu(menu: Menu?): Boolean
{
    toolbar.onCreateOptionsMenu(menuInflater, menu)
    return super.onCreateOptionsMenu(menu)
}

If you are using menu, override:

override fun onOptionsItemSelected(item: MenuItem?) : Boolean
{
    toolbar.onOptionsItemSelected(item)
    return super.onOptionsItemSelected(item)
}

Toolbar with hamburger menu icon: Please import this library.

implementation 'com.balysv.materialmenu:material-menu:2.0.0'
toolbar.setupHamburgerMenu()
toolbar.setOnHamburgerMenuClickedListener {
    Log.e("a", "toggle drawer")
}

BottomNavigationViewX

BottomNavigationView eXtension method

bottomNavigationView.setupWithViewPager(viewPager)
bottomNavigationView.setupWithViewPager(viewPager, initialTab = 0)

ViewPagerX

ViewPager eXtension method

viewPager.setOnPageChangedListener { page ->
    Log.e("a", "You're on page $page")
}

EditTextX

EditText eXtension methods

editText.setOnTextChangedListener { newText ->
    Log.e("a", newText)
}
editText.setOnEditorActionListener { actionId ->
    if (actionId==EditorInfo.IME_ACTION_DONE)
        Log.e("a", "enter pressed")
}

ScreenSize

Used to get the width, height and density of the screen. In Application Class onCreate method:

ScreenSize.init(withContext = this)

Then, you can simply use the properties from ScreenSize:

if (ScreenSize.width<ScreenSize.height)
    if (ScreenSize.density>=2.0) {...code...}

PermissionsHandler

Used to ask for dangerous permisssions. In the Activity class:

class MainActivity : AppCompatActivity()
{
    val permissionsHandler = PermissionsHandler()
    
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        permissionsHandler.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
}

To ask for permissions, simply use:

permissionsHandler.askFor(arrayOf(Manifest.permission.CAMERA))
    .onGranted { Log.e("a", "YAY") }
    .onDenied { Log.e("a", "NAY") }
    .withContext(context = this)

Keyboard

Used to open or close the keyboard

Keyboard.open(on = context)
Keyboard.close(on = context)

FileManager

Extend FileManager class to create classes that manages app file's paths. For instance, getSampleFilePath will return /storage/emulated/0/Dob/sample.pdf

object AppFileManager : FileManager()
{
    override fun folderBasePath() : String = Environment.getExternalStorageDirectory().absolutePath
    override fun folderName() : String = "Dob"

    fun getSampleFilePath() : String = getFilePath("sample.pdf")
}

Retrofit extensions

Download and upload files:

interface IApiClient
{
    @Streaming
    @GET("/samples/pdf.pdf")
    fun downloadPdf() : Call<ResponseBody>

    @Multipart
    @POST("/samples/pdf.pdf")
    fun uploadPdf(@Part file : MultipartBody.Part) : Call<Unit?>
}

To download a file:

ApiClient.Instance.downloadPdf().enqueue(object : Callback<ResponseBody>
{
    override fun onFailure(call: Call<ResponseBody>, t: Throwable)
    {
        Log.e("a", "fail")
    }

    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>)
    {
        Thread {
            try
            {
                downloadFile(response.body()!!, outputPath = AppFileManager.getSampleFilePath())
                Log.e("a", "success")
            }
            catch (ex : Exception)
            {
                Log.e("a", "fail")
            }
        }.start()
    }
})

To upload a file:

ApiClient.Instance.uploadPdf(fileUpload(context = this, path = AppFileManager.getSampleFilePath()))
    .enqueue(object : Callback<Unit?>
    {
        override fun onFailure(call: Call<Unit?>, t: Throwable)
        {
            Log.e("a", "fail")
        }

        override fun onResponse(call: Call<Unit?>, response: Response<Unit?>)
        {
            Log.e("a", "success")
        }
    })

Cache delegate

Use by cache() delegate to cache in memory values returned by other delegates. For instance, with kotpref library:

object Preferences : KotprefModel()
{
    var username by cached(stringPref())
    var level by cached(intPref())
    var firstRun by booleanPref(default = true)
}

Username will be returned from memory cache. If not found in cache, it will be fetched by stringPref delegate, from SharedPreferences.

Async

In Application onCreate,

Run.handler=Handler(mainLooper)

To run on UI thread:

Run.onUIThread {
    println("on ui thread")
}

To run delayed on UI thread:

Run.delayed(1000) {
    println("delayed")
}

To run async on a new thread:

Run.async {
    println("on new thread")
}

To run async and return a result, handling success and error cases (promises style). onAny will alwats be called before onSuccess or onError. Callback methods are run on UI thread

Run.async(task = {
    println("on new thread with result")
    Thread.sleep(1000)
    return@async 1
},
onAny = { println("hide loading dialog") },
onError = { it.printStackTrace() },
onSuccess = { println("result: $it") })

To run async without a result, handing success:

Run.async(task = {
    println("on new thread without result")
    Thread.sleep(1000)
},
onSuccess = { println("done!") })

To run lambdas in paralel. onDone is called after all tasks are done. onError is called after a task throws exception. If a task has an error, remaining tasks will not be executed anymore. Specify maximumNumberOfThreads = value argument to set the maximum amount of paralel running threads at a given time. Default value is 4

Run.paralel(tasks = mutableListOf(
{
    println("task 1")
},
{
    println("task 2")
},
{
    println("task 3")
}), onDone = {
    println("Done!")
}, onError = {
    println("Exception: $it")
})

To set a global error handler for paralel and async methods:

Run.globalErrorHandler={ ex ->
    ex.printStackTrace()
}

Library dependencies

This library depends on the following libraries:

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.balysv.materialmenu:material-menu:2.0.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.0'

You can exclude any of those:

implementation ('com.github.andob:DobDroidMiscUtils:v1.0.7') {
    exclude group: 'com.android.support'
    exclude group: 'com.balysv.materialmenu'
    exclude group: 'com.squareup.okhttp3'
}

License

Copyright 2019 Andrei Dobrescu

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.`

dobdroidmiscutils's People

Contributors

andob001 avatar andob avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.