Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Migrate Android gradle from Groovy Scripts to KTS (Kotlin script)

This section will guide your step-by-step to convert or migrate your Android project's Gradle build script from Groovy script to Kotlin DSL

 When we create a project in Android (Arctic Fox 2020.3.1), We get the default Gradle Script setup for us which has 3 gradle file written in Groovy script

These 3 Gradle files are:
    1. The settings.gradle
    2. The root project’s build.gradle
    2. The app module’s build.gradle

Convert the settings.gradle file
1. Rename settings.gradle to settings.gradle.kts

You can do so by selecting the settings.gradle file, then go to Refactor
→ Rename File.

Then, just convert it to settings.gradle.kts. 

2. Fix the file syntax for “include”

You just need to change

include ':app'
to

include("app")

settings.gradle example file in groovy script:

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon
        maven {
            url 'https://jitpack.io'
        }
        maven {
            url 'https://maven.google.com'
        }
        maven {
            url 'https://maven.fpregistry.io/releases'
        }
        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots/"
        }
    }
}
rootProject.name = "Project name text"
include ':app'

'include ':news'
include ':events'
include ':home'
include ':profile'
include ':common'

example file becomes settings.gradle.kts in Kotlin script:

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        jcenter() // Warning: this repository is going to shut down soon
        maven(url = "https://jitpack.io")
        maven(url = "https://maven.google.com")
        maven(url = "https://maven.fpregistry.io/releases")    
        maven(url = "https://oss.sonatype.org/content/repositories/snapshots/")    
    }
}
rootProject.name = "Be better"
include("app")
include("news")
include("events")
include("home")
include("profile")
include("common")

How to use Kotlin Coroutines with volley

How to use API connection with Kotlin Coroutines + Volley
When start developing API with Volley in Kotlin, you want to use Kotlin Coroutine instead of AsyncTask. We see how to use API connection using Volley and Coroutine as an example.
First of all, How can I take advantage of coroutines so I can write my code in concise manner:
Here's an example to Coroutine calling API Android

Volley overview

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available on GitHub. Volley is an HTTP client developed by google for android development. You can use suspendCancellableCoroutine to make the Volley API request.

NetworkUtility.kt
package com.example.myapplication

import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import kotlinx.coroutines.suspendCancellableCoroutine
import org.json.JSONObject
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

class NetworkUtility {
 
    companion object {
        val mRequestQueue: RequestQueue by lazy {
            Volley.newRequestQueue(MainApp.get())
        }

        suspend fun APIrequest(url: String): JSONObject {

            return suspendCancellableCoroutine { continuation ->
                try {
                    // Sucess Listner
                    val success = Response.Listener<JSONObject> { response ->
                        if (continuation.isActive) {
                            continuation.resume(response)
                        }
                    }

                    // Error Listner
                    val error = Response.ErrorListener { error ->
                        if (continuation.isActive) {
                            continuation.resume(JSONObject())
                        }
                    }

                    val jsonObjectRequest =
                        JsonObjectRequest(Request.Method.GET, url, null, success, error)

                    mRequestQueue.add(jsonObjectRequest)

                } catch (e: Exception) {
                    e.printStackTrace()
                    if (continuation.isActive) {
                        if (continuation.isActive) {
                            continuation.resumeWithException(e)
                        }
                    }
                }
            }
        }
    }
 
}

MainViewModel.kt
package com.example.myapplication

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject

class MainViewModel : ViewModel() {

    var usersList: MutableLiveData<ArrayList<User>> = MutableLiveData(arrayListOf())

    var isLoadingData = true
    var showProgress = MutableLiveData<Boolean>()


    fun getData(urlStr: String) {
        showProgress.value = true

        viewModelScope.launch(Dispatchers.IO) {
            val rss = NetworkUtility.APIrequest(urlStr)

            withContext(Dispatchers.Main) {
                // call to UI thread
                isLoadingData = false
                showProgress.value = false
                usersList.value?.addAll(parseJsonString(rss.toString()))
            }
        }
    }

    fun parseJsonString(str: String): ArrayList<User> {
        val jsonOb = JSONObject(str)
        val list: ArrayList<User> = arrayListOf()
        val jsonArray = jsonOb.getJSONArray("data");

        for (j in 0..jsonArray.length() - 1) {
            val user = User(
                jsonArray.getJSONObject(j).getString("id"),
                jsonArray.getJSONObject(j).getString("email"),
                jsonArray.getJSONObject(j).getString("first_name"),
                jsonArray.getJSONObject(j).getString("last_name"),
                jsonArray.getJSONObject(j).getString("avatar")
            )
            list.add(user)
        }
        return list
    }

}


MainActivity.kt
package com.example.myapplication

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.myapplication.databinding.ActivityMainBinding
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.toolbar.*

class MainActivity : AppCompatActivity() {
    lateinit var viewModel: MainViewModel
    lateinit var userAdapter: UserRVAdapter

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

        val binding: ActivityMainBinding =
            DataBindingUtil.setContentView(this, R.layout.activity_main)

        setSupportActionBar(toolbar)
        getSupportActionBar()?.setDisplayHomeAsUpEnabled(true)

        viewModel = ViewModelProviders.of(this)[MainViewModel::class.java]
        binding.mainVM = viewModel
        binding.setLifecycleOwner(this)

        viewModel.getData("https://reqres.in/api/users?page=1&per_page=12")

        viewModel.showProgress.observe(this, Observer {
            if (it == true) {
                progressBar.visibility = View.VISIBLE
            } else {
                progressBar.visibility = View.GONE
            }
        })

        viewModel.usersList.observe(this, Observer {
            Log.e("ResSize", "" + it.size + "::" + it)
            userAdapter.addList(it)
        })

        // Creates a vertical Layout Manager
        rv_users.layoutManager = LinearLayoutManager(this)
        userAdapter = UserRVAdapter(this)
        rv_users.adapter = userAdapter
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable name="mainVM" type="com.example.myapplication.MainViewModel" />

    </data>
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    tools:context=".MainActivity">

    <include layout="@layout/toolbar" />

    <TextView
        app:layout_constraintTop_toBottomOf="@+id/toolbar"
        android:id="@+id/tv_select_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Users"
        android:layout_margin="7dp"
        android:textColor="@android:color/black"
        app:layout_constraintLeft_toLeftOf="parent"
        android:textSize="20sp"/>


    <androidx.recyclerview.widget.RecyclerView
        android:layout_marginTop="10dp"
        app:layout_constraintTop_toBottomOf="@id/tv_select_user"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:id="@+id/rv_users"
        android:layout_width="match_parent"
        android:layout_height="0dp"/>

    <ProgressBar
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:id="@+id/progressBar"
        android:visibility="gone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

UserRVAdapter.kt
package com.example.myapplication

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import kotlinx.android.synthetic.main.ly_item_user.view.*

class UserRVAdapter(val context: Context): RecyclerView.Adapter<UserRVAdapter.ViewHolder>() {

    var items : ArrayList<User> = arrayListOf()

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val posObj=items.get(position);

        holder.tv_name1?.text =posObj.first_name +" "+posObj.last_name
        holder.tv_email1?.text = posObj.email

        GlideApp.with(holder.iv_profile1.context)
            .load(posObj.avatar)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .apply(RequestOptions.circleCropTransform())
            .error(R.drawable.ic_launcher_background)
            .placeholder(R.drawable.ic_launcher_background)
            .into(holder.iv_profile1)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(context).inflate(R.layout.ly_item_user, parent, false))
    }

    fun addList(itemsNew : ArrayList<User>){
            this.items=itemsNew
            notifyDataSetChanged()
            Log.e("ResSize:ItemsIF", "" + items.size)
    }

    override fun getItemCount(): Int {
        return items.size
    }

    class ViewHolder (view: View) : RecyclerView.ViewHolder(view) {
        // Holds the TextView that will add each animal to
        val tv_name1 = view.tv_name
        val tv_email1 = view.tv_email
        val iv_profile1 = view.iv_profile
    }
}

ly_item_user.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/iv_profile"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_width="50dp"
        android:layout_margin="10dp"
        android:layout_height="50dp"/>

    <TextView
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@id/iv_profile"
        app:layout_constraintBottom_toTopOf="@+id/tv_email"
        android:id="@+id/tv_name"
        android:textSize="20sp"
        android:text="Pradip"
        android:layout_marginLeft="10dp"
        android:textColor="@android:color/black"
        app:layout_constraintVertical_chainStyle="packed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:layout_marginLeft="10dp"
        app:layout_constraintLeft_toRightOf="@id/iv_profile"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_name"
        android:id="@+id/tv_email"
        android:text="Tilala"
        android:textColor="@android:color/darker_gray"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <View
        app:layout_constraintTop_toBottomOf="@id/iv_profile"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_width="match_parent"
        android:background="#f3f3f3"
        android:layout_margin="10dp"
        android:layout_height="2dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Best reference : API connection with Volley + Coroutine

[databinding] {"msg":"Missing import expression although it is registered

[kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding error(s):

[databinding] {"msg":"Missing import expression although it is registered","file":"/home/espl/Documents/Desktop/d2/ocd/ocdlive_3.0.7_live_i_android_x_call (2)/app/src/main/res/layout/item_notif.xml","pos":[]}

at android.databinding.tool.processing.Scope.assertNoError(Scope.java:111)
at android.databinding.annotationprocessor.ProcessDataBinding.doProcess(ProcessDataBinding.java:124)
at android.databinding.annotationprocessor.ProcessDataBinding.process(ProcessDataBinding.java:88)
at org.jetbrains.kotlin.kapt3.base.incremental.IncrementalProcessor.process(incrementalProcessors.kt)
at org.jetbrains.kotlin.kapt3.base.ProcessorWrapper.process(annotationProcessing.kt:132)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$200(JavacProcessingEnvironment.java:91)
at com.sun.tools.javac.processing.JavacProcessingEnvironment$DiscoveredProcessors$ProcessorStateIterator.runContributingProcs(JavacProcessingEnvironment.java:627)
at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1033)
at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1198)
at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1068)
at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:80)
at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:36)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:223)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:187)
at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:98)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:96)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:106)
at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:82)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:384)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:70)
at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:107)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:375)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:123)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:131)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:54)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:84)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:42)
at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:103)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$1$2.invoke(CompileServiceImpl.kt:442)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$1$2.invoke(CompileServiceImpl.kt:102)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:1023)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:102)
at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:1065)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:1022)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:441)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Cleartext Http Traffic not Permitted Android 9

Android Studio Error Log: java.io.IOException: Cleartext HTTP traffic to my_IP/domain not permitted

2019-09-06 12:20:29.050 22531-22531/com.geekscompete.gate_isro_cs.ugc_net_preparation E/VolleyError:: ::com.android.volley.NoConnectionError: java.io.IOException: Cleartext HTTP traffic to http://geekscompete.com/ not permitted

Reason for this error:
According to Network security configuration - Opt out of cleartext traffic
Note: The guidance in this section applies only to apps that target Android 8.1 (API level 27) or lower. Starting with Android 9 (API level 28), cleartext support is disabled by default. Network security configuration also suggest to ensure that all connections to your domain are always done over HTTPS to protect sensitive traffic from hostile networks.

You have to create a new file in your xml folder, file named network_security_config.xml.
res/xml/network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">yourdomain.com</domain>
        <domain includeSubdomains="true">geekscompete.com</domain>
        <domain includeSubdomains="true">geekscompete.blogspot.com</domain>
    </domain-config>
</network-security-config>

This config will now allow clear traffic to your specified domains after you . Make sure that you have set android:networkSecurityConfig="@xml/network_security_config" in the application tag of your AndroidManifest.xml. The content of your config file should contain all URLs which requests clear traffic without encryption. As shown in below code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.yourappname">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name=".MainApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:allowBackup="false"
        android:supportsRtl="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:theme="@style/AppTheme">
    </application>
</manifest>


Related Articles: 


java.util.concurrent.TimeoutException android.os.BinderProxy.finalize() timed out after 10 seconds

Fatal Exception: java.util.concurrent.TimeoutException
android.os.BinderProxy.finalize() timed out after 10 seconds
android.os.BinderProxy.destroy (BinderProxy.java)
android.os.BinderProxy.finalize (BinderProxy.java:540)
java.lang.Daemons$FinalizerDaemon.doFinalize (Daemons.java:191)
java.lang.Daemons$FinalizerDaemon.run (Daemons.java:174)
java.lang.Thread.run (Thread.java:818)

E/WindowManager: android.view.WindowLeaked: Activity

10-13 16:00:29.760 27725-27725/com.example.DemoApp E/WindowManager: android.view.WindowLeaked: Activity com.example.DemoApp.V2.DealofTheDayActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{65f438d V.E...... R.....I. 0,0-1080,1920} that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:373)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:302)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:86)
        at android.app.Dialog.show(Dialog.java:322)
        at com.example.DemoApp.BaseActivity$4.onResourceReady(BaseActivity.java:754)
        at com.example.DemoApp.BaseActivity$4.onResourceReady(BaseActivity.java:723)
        at com.bumptech.glide.request.SingleRequest.onResourceReady(SingleRequest.java:568)
        at com.bumptech.glide.request.SingleRequest.onResourceReady(SingleRequest.java:530)
        at com.bumptech.glide.load.engine.EngineJob.handleResultOnMainThread(EngineJob.java:218)
        at com.bumptech.glide.load.engine.EngineJob$MainThreadCallback.handleMessage(EngineJob.java:324)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5604)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)

android.content.res.Resources$NotFoundException: File res/drawable/try_angle.xml from drawable resource ID

01-29 13:10:13.126 1634-1634/com.elitech.offers.coupons.deals W/System.err: android.content.res.Resources$NotFoundException: File res/drawable/try_angle.xml from drawable resource ID #0x7f0701c6
01-29 13:10:13.130 1634-1634/me.me2.com.myapp W/System.err:     at android.content.res.Resources.loadDrawable(Resources.java:2170)
01-29 13:10:13.130 1634-1634/me.me2.com.myapp W/System.err:     at android.content.res.Resources.getDrawable(Resources.java:710)
01-29 13:10:13.130 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v4.content.ContextCompat.getDrawable(ContextCompat.java:465)
01-29 13:10:13.130 1634-1634/me.me2.com.myapp W/System.err:     at me.me2.com.myapp.V2.HomeRecyclerViewAdapter.onBindViewHolder(HomeRecyclerViewAdapter.java:1055)
01-29 13:10:13.130 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3875)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3639)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1877)
01-29 13:10:13.131 1634-1634/me.me2.com.myapp W/System.err:     at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:407)
01-29 13:10:13.132 1634-1634/me.me2.com.myapp W/System.err:     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
01-29 13:10:13.134 1634-1634/me.me2.com.myapp W/System.err:     at android.view.Choreographer.doCallbacks(Choreographer.java:591)
01-29 13:10:13.134 1634-1634/me.me2.com.myapp W/System.err:     at android.view.Choreographer.doFrame(Choreographer.java:559)
01-29 13:10:13.134 1634-1634/me.me2.com.myapp W/System.err:     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
01-29 13:10:13.134 1634-1634/me.me2.com.myapp W/System.err:     at android.os.Handler.handleCallback(Handler.java:808)
01-29 13:10:13.134 1634-1634/me.me2.com.myapp W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:103)
01-29 13:10:13.134 1634-1634/me.me2.com.myapp W/System.err:     at android.os.Looper.loop(Looper.java:193)
01-29 13:10:13.134 1634-1634/me.me2.com.myapp W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5333)
01-29 13:10:13.135 1634-1634/me.me2.com.myapp W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
01-29 13:10:13.135 1634-1634/me.me2.com.myapp W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
01-29 13:10:13.135 1634-1634/me.me2.com.myapp W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
01-29 13:10:13.137 1634-1634/me.me2.com.myapp W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
01-29 13:10:13.137 1634-1634/me.me2.com.myapp W/System.err:     at dalvik.system.NativeStart.main(Native Method)
01-29 13:10:13.137 1634-1634/me.me2.com.myapp W/System.err: Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #2: invalid drawable tag vector
01-29 13:10:13.138 1634-1634/me.me2.com.myapp W/System.err:     at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:933)
01-29 13:10:13.138 1634-1634/me.me2.com.myapp W/System.err:     at android.graphics.drawable.Drawable.createFromXml(Drawable.java:877)
01-29 13:10:13.138 1634-1634/me.me2.com.myapp W/System.err:     at android.content.res.Resources.loadDrawable(Resources.java:2166)
01-29 13:10:13.138 1634-1634/me.me2.com.myapp W/System.err:  ... 30 more

android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed:

Reason for Exception is that Gson treats “missing” values as “null”
Caused by: android.database.sqlite.SQLiteConstraintException:
NOT NULL
constraint failed: (code 1299 SQLITE_CONSTRAINT_NOTNULL)
You might come across this error when you are using Room database on Android. This happens because the generated schema for your tables mark some of the table’s columns as NOT NULL.

For example, if you Entity class looks like this:

Model Class Book:
package com.geekscompete.gate_isro_cs.ugc_net_preparation.database.models

import androidx.room.Entity
import androidx.room.PrimaryKey
import com.geekscompete.gate_isro_cs.ugc_net_preparation.database.BaseOb

@Entity(tableName = "book")
class Book(
        @PrimaryKey(autoGenerate = true)
        var objectId: Int = 0,

        id: String ="",
        data: String = "",
        title: String ="",
        description: String ="",
        last_updated: String ="",
        logo_url: String ="",
        orderno: Int = 0,
        tags: String="",
        type: Int = -1,
        btm_color: String="#F0513C",

       var price: Int,
        var redirect_url: String,
        var tag: String
): BaseOb(id,data,title,description,last_updated,logo_url,orderno,tags,type,btm_color)

Data I am getting from API is as below:
{
id: 1,
title: "NTA UGC NET/SET/JRF - Paper 1",
description: "This book, in its third edition, is designed and developed for students who aspire to build a career in academics and research field",
image_url: "https://images-na.ssl-images-amazon.com/images/I/71%2BZPvi7ZlL.jpg",
store_logo_url: "https://images-na.ssl-images-amazon.com/images/G/01/rainier/available_at_amazon_1200x600_Nvz5h2M.png",
price: 411,
redirect_url: "https://www.amazon.in/NTA-UGC-NET-SET-JRF/dp/9353433746/ref=as_li_ss_il?crid=2EYYT7DF8WXMX&keywords=ugc+net+paper+1+2019&qid=1564293960&s=gateway&sprefix=ugc+net+,aps,281&sr=8-1-spons&psc=1&linkCode=li2&linkId=8424f35e3b5163df827e84af24007fb9&language=en_IN",
tag: "UGC NET PAPER 1"
}

There was no data field in the API response and I am parsing using Gson.
The generated columns like title, description, data and logo_url will be marked as NOT NULL. And thus, when you try to add a record with one of these values as null, you will get an SQLiteConstraintException.
val title: String
In Kotlin, this means that title can never be null.

To fix this, you just need to change the Entity class a bit, and allow the fields to be Nullable.
@Entity(tableName = "books")
data class Book(
    @PrimaryKey
    val id: Int,
    val title: String?,
    val description: String?,
    val info: String?,
    val type: Int,
    val url: String?
)

08-31 18:19:06.031 8364-8450/com.geekscompete.gate_isro_cs.ugc_net_preparation E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
    Process: com.geekscompete.gate_isro_cs.ugc_net_preparation, PID: 8364
    android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: book.data (code 1299)
        at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
        at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:780)
        at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
        at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
        at androidx.sqlite.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:51)
        at androidx.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.java:97)
        at com.geekscompete.gate_isro_cs.ugc_net_preparation.database.models.BookNewDao_Impl.insertAll(BookNewDao_Impl.java:267)
        at com.geekscompete.gate_isro_cs.ugc_net_preparation.quiz_attempts.QuizListFragment_new$getBooks$1$1.run(QuizListFragment_new.kt:410)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)

References best:
https://techdroid.kbeanie.com/2018/11/24/room-database-kotlin-nullable-column/
https://www.bignerdranch.com/blog/when-nullability-lies-a-cautionary-tale/

android room unique constraint (Kotlin)

Kotlin code:


Single column unique (e.g. id_key only).

@Entity(tableName = "user",indices = [(Index(value = ["id_key"], unique = true))])
data class User (

  @PrimaryKey(autoGenerate = true)
    var id: Int = 0
 
  @ColumnInfo(name = "id_key")
    var id_key: String = ""

    @ColumnInfo(name = "first_name")
    var first_name: String = ""

@ColumnInfo(name = "last_name")
    var last_name: String = ""
}


How to add unique constraint in room database to multiple column

Combine two columns to be unique (e.g. first_name and last_name).

@Entity(tableName = "user",indices = arrayOf(Index(value = ["first_name", "last_name"], unique = true)))
data class User (
.....
}


Multiple unique constaints.

@Entity(tableName = "user", indices = [Index(value = ["id_key"]),Index(value = ["first_name", "last_name"],unique = true)])
....
}

versioncode deprecated android

versionCode

public int versionCode
pinfo.versioncode was deprecated in API level 28 (Added in API level 1).
Use getLongVersionCode() instead, which includes both this and the additional versionCodeMajor attribute. The version number of this package, as specified by the <manifest> tag's versionCode attribute.
'versionCode' is deprecated as of API 28: Android 9.0 (Pie)

getLongVersionCode is an API 28 method, though, so consider using PackageInfoCompat. It has one static method : getLongVersionCode(PackageInfo info)

PackageInfoCompat.getLongVersionCode (PackageInfo info)

public static long getLongVersionCode (PackageInfo info)
Return R.attr.versionCode and R.attr.versionCodeMajor combined together as a single long value. The versionCodeMajor is placed in the upper 32 bits on Android P or newer, otherwise these bits are all set to 0.

Recommended solution:
If your have included below appcompat dependency this in your app level build.gradle :
implementation 'androidx.appcompat:appcompat:1.0.2'

then just use this function code:
public static long appVersionCode() {
try {
    PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
    long longVersionCode= PackageInfoCompat.getLongVersionCode(pInfo);
    return  (int) longVersionCode;
    } catch (PackageManager.NameNotFoundException e) {
          e.printStackTrace();
  }
   return 0;
}

Alternative solution in case you have not used appcompat library then just use as below :
final PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
int versionCode;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    versionCode = (int) pInfo.getLongVersionCode(); // avoid huge version numbers and you will be ok
} else {
    //noinspection deprecation
    versionCode = pInfo.versionCode;
}

Android Databinding : Compare strings in xml

Compare two strings after putting the constant string in side two Back quote ( ` ).

<RadioButton
            android:id="@+id/male"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:checked="@{user.gender.equalsIgnoreCase(`male`)}"
            android:text="@string/male"/>

Use string resources

        <RadioButton
            android:id="@+id/male"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:checked="@{user.gender.equalsIgnoreCase(@string/male)}"
            android:text="@string/male"/>


Use string constants:

<data>
    <import type="yourfullpackagepath.StringConstants"/>
</data>

        <RadioButton
            android:id="@+id/female"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:checked="@{user.gender.equalsIgnoreCase(StringConstants.FEMALE)}"
            android:text="@string/female"/>

android.os.networkonmainthreadexception android

android.os.NetworkOnMainThreadException

NetworkOnMainThreadException
The exception that is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.

StrictMode
StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them. StrictMode is most commonly used to catch accidental disk or network access on the application's main thread, where UI operations are received and animations take place. Keeping disk and network operations off the main thread makes for much smoother, more responsive applications. By keeping your application's main thread responsive, you also prevent ANR dialogs from being shown to users.

StrictMode.ThreadPolicy.Builder
You should almost always run network operations on a thread or as an asynchronous task.

But it is possible to remove this restriction and you override the default behavior, if you are willing to accept the consequences.

Add:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
In your class,
and
ADD this permission in android manifest.xml file: 
<uses-permission android:name="android.permission.INTERNET"/>

Consequences:
Your app will (in areas of spotty internet connection) become unresponsive and lock up, the user perceives slowness and has to do a force kill, and you risk the activity manager killing your app and telling the user that the app has stopped.
Android has some good tips on good programming practices to design for responsiveness:

AsyncTask:
This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:
class RetrieveFeedTask extends AsyncTask<String, Void, RSSFeed> {

    private Exception exception;

    protected RSSFeed doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader xmlreader = parser.getXMLReader();
            RssHandler theRSSHandler = new RssHandler();
            xmlreader.setContentHandler(theRSSHandler);
            InputSource is = new InputSource(url.openStream());
            xmlreader.parse(is);

            return theRSSHandler.getFeed();
        } catch (Exception e) {
            this.exception = e;

            return null;
        } finally {
            is.close();
        }
    }

    protected void onPostExecute(RSSFeed feed) {
        // TODO: check this.exception
        // TODO: do something with the feed
    }
}

How to execute the task:
In MainActivity.java file you can add this line within your oncreate() method
new RetrieveFeedTask().execute(urlToRssFeed);

Don't forget to add this to AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
Android volley post json request example

Fatal Exception: java.lang.AssertionError No NameTypeIndex match for SHORT_STANDARD

Fatal Exception: java.lang.AssertionError
No NameTypeIndex match for SHORT_STANDARD
android.icu.impl.TimeZoneNamesImpl$ZNames.getNameTypeIndex (TimeZoneNamesImpl.java:724)
android.icu.impl.TimeZoneNamesImpl$ZNames.getName (TimeZoneNamesImpl.java:790)
android.icu.impl.TimeZoneNamesImpl.getTimeZoneDisplayName (TimeZoneNamesImpl.java:183)
android.icu.text.TimeZoneNames.getDisplayName (TimeZoneNames.java:261)
java.util.TimeZone.getDisplayName (TimeZone.java:405)
java.util.Date.toString (Date.java:1066)
java.util.Properties.store0 (Properties.java:828)
java.util.Properties.store (Properties.java:817)
com.google.firebase.iid.zzy.zza (Unknown Source:88)
com.google.firebase.iid.zzy.zzc (Unknown Source:9)
com.google.firebase.iid.zzaw.com.google.firebase.iid.zzy.zzb (Unknown Source:2005)
com.google.firebase.iid.FirebaseInstanceId.zzi (Unknown Source:60)
com.google.firebase.iid.FirebaseInstanceId.zza (Unknown Source:147)
com.google.firebase.iid.zzn.run (Unknown Source:10)
java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1162)
java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:636)
java.lang.Thread.run (Thread.java:764)

java.lang.illegalstateexception: unable to create layer for linearlayout

Found most of this crashes on Android 6.0 around 75% of the total crashes and 25% from Android 5.0. According to google Crashlytics  report, these devices areOnePlus One, OnePlus X, Xperia Z, Xperia Z1, Xperia Z2, Xperia Z3, Samsung Galaxy Note, Galaxy S4 and Galaxy S5 devices, covering 80% of total crashes. Not able to recreate this crash on my HTC, Mi devices. How to reproduce this issue or find where exact the issue in app? Below is the detailed log from Crashlytics.
Fatal Exception: java.lang.IllegalStateException: Unable to create layer for LinearLayout, size 1080x4160 exceeds max size 4096
       at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
       at android.os.MessageQueue.next(MessageQueue.java:323)
       at android.os.Looper.loop(Looper.java:136)
       at android.app.ActivityThread.main(ActivityThread.java:6186)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

Rectify and solve issue:

I have Nested scroll view which contains vertical recycler view and other elements in the main screen.

What is the exact issue :
Cause is that RecyclerView inside scrollview or nestedscrollview try to load all items at once. As RecyclerView loads all items, also those items whcih are not visible. If you put log inside onBindViewHolder of RecylerView you find that all items loads at once in the start instead of based on the visibility of the item. This causes the parent LinearLayout (inside the ScrollView) to throw exception. I had also issue related to same with Recyclerview inside NestedScrollView.

Issue cause related  to above discussion:
If UI load more than 1-1.5 screens of content at a time.
Means you are loading unncessasary content which are not visible to user at a time on mobile screen. (While vertical RecyclerView inside NestedScrollView loads all its items at once in starting, instead of based on Recyclerview Visibility)

In the below answer @ivan V found issue related to the same and also given suggestions.
https://stackoverflow.com/questions/26664922/crash-material-design-android-5-0/27906489#answer-32966150

If you have crashlytics log for this issue then you can rectify the android Device and Android OS for which this type of Crashnalytics log detected.

Ho to detect issue:
1. Find all such activities whcih contains layout with LinearLayout.
2. Run you application and search your log and open each of your activity. Try to find during which activity log similar to below is detected.
W/OpenGLRenderer(18137): Layer exceeds max. dimensions supported by the GPU (1080x4628, max=4096x4096)
E/AndroidRuntime(18137): java.lang.IllegalStateException: Unable to create layer for  RelativeLayout
OR
Unable to create layer for v
OR
Fatal Exception: java.lang.IllegalStateException: Unable to create layer for LinearLayout, size 1080x4160 exceeds max size 4096
Reference: https://stackoverflow.com/questions/26626344/scene-transition-with-hero-elements-throws-layer-exceeds-max-dimensions-support#answer-27995911
Reference 2: https://stackoverflow.com/questions/26664922/crash-material-design-android-5-0/27906489#answer-27906489

Reference 3: Scene transition with hero elements throws Layer exceeds max. dimensions supported by the GPU

Solution :
Paginate your content and load no more than 1-1.5 screens of content at a time.

This will significantly decrease the screen size that is being pre-rendered during shared elements transition (it's being pre-rendered every time so the system knows where to place your transition object after transition)

Best Reference for solution:  https://stackoverflow.com/questions/26664922/crash-material-design-android-5-0/27906489#answer-32966150

I had the same issue & How I solved it:

My Layout was like below mentioned:
I have refactored my code such that there is only one main recycler view and all other layout are child of it. Using the RecycleView with multiple types of child views

Here I have replaced the logic part and UI part of Nested Scroll View items to different type of Recycler View holders inside Main RecyclerView.

You can see in bottom table I have replaced the Nested Scroll View and Linear-layout with a New Main RecyclerView.


BeforeAfter Refactoring from Scroll View to Recycler View
Nested Scroll View Main layout-> RecyclerView
LinearLayout
Horizontal Recycler View Child item layout-> Horizontal Recycler View
Two text View with two Horizontal Recycler Views Child item layout-> Two text View with two Horizontal Recycler Views
ImageView Child item layout-> ImageView
Horizontal Recuycler View Child item layout-> Horizontal Recycler View
Vertical Recuycler View (with 12 items of sametype) Child item layout-> With 12 items with same type as a childs of Main RecyclerView


Feel free to comment and post your solutions and doubts. 

IllegalArgumentException reportSizeConfigurations: ActivityRecord not found for: Token

Fatal Exception: java.lang.IllegalArgumentException
reportSizeConfigurations: ActivityRecord not found for: Token{4a52be7 null}
android.os.Parcel.createException + 1954 (Parcel.java:1954)
android.os.Parcel.readException + 1918 (Parcel.java:1918)
android.os.Parcel.readException + 1868 (Parcel.java:1868)
android.app.IActivityManager$Stub$Proxy.reportSizeConfigurations + 8679 (IActivityManager.java:8679)
android.app.ActivityThread.reportSizeConfigurations + 3217 (ActivityThread.java:3217)
android.app.ActivityThread.handleLaunchActivity + 3176 (ActivityThread.java:3176)
android.app.ActivityThread.handleRelaunchActivityInner + 4920 (ActivityThread.java:4920)
android.app.ActivityThread.handleRelaunchActivity + 4829 (ActivityThread.java:4829)
android.app.servertransaction.ActivityRelaunchItem.execute + 69 (ActivityRelaunchItem.java:69)
android.app.servertransaction.TransactionExecutor.executeCallbacks + 108 (TransactionExecutor.java:108)
android.app.servertransaction.TransactionExecutor.execute + 68 (TransactionExecutor.java:68)
android.app.ClientTransactionHandler.executeTransaction + 55 (ClientTransactionHandler.java:55)
android.app.ActivityThread.handleRelaunchActivityLocally + 4879 (ActivityThread.java:4879)
android.app.ActivityThread.access$3400 + 207 (ActivityThread.java:207)
android.app.ActivityThread$H.handleMessage + 1916 (ActivityThread.java:1916)
android.os.Handler.dispatchMessage + 106 (Handler.java:106)
android.os.Looper.loop + 193 (Looper.java:193)
android.app.ActivityThread.main + 6863 (ActivityThread.java:6863)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run + 537 (RuntimeInit.java:537)
com.android.internal.os.ZygoteInit.main + 858 (ZygoteInit.java:858)

Android Rounded Corners Button with Background Color

Content:
1) How to create a rounded corners Button in Android
2) How to set Button pressed state background color in Android when clicked

1.Create a xml file in your drawable folder like rounded_corner_background.xml and paste the following markup:

rounded_corner_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<!--button pressed state background color-->
    <item android:state_pressed="true" >
        <shape android:shape="rectangle"  >
            <corners android:radius="10dip" />
            <stroke android:width="2dip" android:color="#5e7974" />
            <gradient android:angle="-90" android:startColor="#CC9933" android:endColor="#CC9933"  />
        </shape>
    </item>

<!--button focused state background color-->
    <item android:state_focused="true">
        <shape android:shape="rectangle"  >
            <corners android:radius="10dip" />
            <stroke android:width="2dip" android:color="#5e7974" />
            <gradient android:angle="-90" android:startColor="#CCCC33" android:endColor="#CCCC33"  />
        </shape>
    </item>

 <!--button default background color-->
    <item >
        <shape android:shape="rectangle"  >
            <corners android:radius="10dip" />
            <stroke android:width="2dip" android:color="#5e7974" />
            <gradient android:angle="-90" android:startColor="#CCCCCC" android:endColor="#CCCCCC" />
        </shape>
    </item>
</selector>

Button Default Background Color

button focused state background color

button pressed state background color


2. Now use this drawable for the background of your Button.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:padding="30dp"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_corner_background"
        android:text="Rounded Corners Button !"
        android:padding="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>

close/hide the soft keyboard android kotlin


created a static utility method which can do the job VERY solidly, provided you call it from an Activity.
public static void hideKeyboard(Activity activity) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); //Find the currently focused view, so we can grab the correct window token from it. View view = activity.getCurrentFocus(); //If no view currently has focus, create a new one, just so we can grab a window token from it if (view == null) { view = new View(activity); } imm.hideSoftInputFromWindow(view.getWindowToken(), 0); }
You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your focused view.
// Check if no view has focus: View view = this.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); }
This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).
Note: If you want to do this in Kotlin, use:context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
Kotlin Syntax
// Check if no view has focus: val view = this.currentFocus view?.let { v -> val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager imm?.let { it.hideSoftInputFromWindow(v.windowToken, 0) } }

Kotlin Elvis Operator (?:) Example

The Elvis Operator (?:) is represented by a question mark followed by a colon: ?: .It is ?: is a binary operator. If the first operand is not null, it is returned. Otherwise the value of the second operand (which may be null) is returned and it can be used with this syntax:
first operand ?: second operand

Lets take example:
If the expression to the left of ?:  (here : b?.length) is not null, the elvis operator returns it (here: result of expression b.length), otherwise it returns the expression to the right (here: -1). Note that the right-hand side expression is evaluated only if the left-hand side is null.
var b: String? = "Some Nullable String Value"
val l = b?.length ?: -1
When we have a nullable reference r, we can say "if r is not null, use it, otherwise use some non-null value x"
Above Elvis operator expression written with ?:: can be expressed along with the complete if-expression as below:
val l: Int = if (b != null) b.length else -1

Things to Note
Note that, since throw and return are expressions in Kotlin, they can also be used on the right hand side of the elvis operator. This can be very handy, for example, for checking function arguments:

​fun foo(node: Node): String? {
    val parent = node.getParent() ?: return null
    val name = node.getName() ?: throw IllegalArgumentException("name expected")
    // ...
}

Val and Var in Kotlin

Read-only local variables are defined using the keyword val. They can be assigned a value only once. val use to declare final variable.

val in Kotlin
val is same as the final keyword in java. As you should probably know that we cannot reassign value to a final variable but can change its properties. Similarly, val is like Final variable and its known as immutable in kotlin and can be initialized only single time.
Characteristics of val variables in Kotlin:
1. Initialization of val in Kotlin
1.1 Immediate assignment
val a: Int = 1
val b = 2   // `Int` type is inferred
1.2 deferred assignment
val c: Int  // Type required when no initializer is provided
c = 3       // deferred assignment
1.3 Must be initialized
Refer more about https://kotlinlang.org/docs/reference/basic-syntax.html#defining-variables
1.4 value can not be changed or reassign
1.5 val is same as the final modifier in java. can not assign to a final variable again but can change its properties.
Uses: val is used for getter (read-only, value won't change).
Extra:
val variables are not necessarily immutable. They are final -- only the reference is immutable -- but if the object stored in the val is mutable, the object is mutable regardless of whether it is assigned via val or var.

Var in Kotlin:
var in kotlin used to declare a variable which is like general variable and its known as a mutable variable in kotlin and
If you use the var keyword to declare Variables that can be reassigned (assigned multiple times)

Characteristics of var variables in Kotlin:
1. variables defined with var are mutable(Read and Write)
2. We can initialize later by using lateinit modifier [lateinit also use for global variable we can not use it for local variable]  value can be changed or reassign but not in global scope

var is as a general variable

Uses:
1. use var where value is changing frequently
2. var is used for setter (value will change).

Difference
val is immutable and var is mutable in Kotlin.

Example:

package com.example.espl.val_vs_var_in_kotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

class MainActivity : AppCompatActivity() {

    val a: Int = 1  // immediate assignment
    val b = 2   // `Int` type is inferred

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

        val c: Int  // Type required when no initializer is provided
//        Log.e("IntVal",""+c)  //  Warning: Variable 'c' must be initialised
        c = 3  // deferred assignment
        Log.e("val c",":: "+c)

        val person=Person("Ram", 50, Address("kaka ni pol","New street", "Ahmedabad"))

        Log.e("Value of city of person","- City:: "+person.address.city)
//        person.address.city="Rajkot"; // Val cannot be reassigned
        person.address.street="Dalal street"; // Var street can be reassigned
        person.address.name="Maharshi"; // Val name can be reassigned

        Log.e("log of val person","after change of address name,street :: "+person.toString()) //

        val person1=Person("Raj", 50, Address("Raj street name","Raj street", "Rajkot"))
//        person=person1           // Warning: Val person cannot be reassigned
//        person=Person("Lakhan", 52, Address("kaka ni pol","New street", "Ahmedabad")) // Warning: Val person cannot be reassigned

        person.address=person1.address // we can reassign the address of a val person as its variable
        // This proves that val cannot be reassigned but its properties defined using the val can be changed.

//val is used for getter (read-only, value won't change).
//        person.age=person1.age // Warning: Val age cannot be reassigned
//        person.age=51 // Warning: Val age cannot be reassigned

//var is used for setter (value will change).
        person.name="Tarun"
        Log.e("log of val person","after change of var address :: "+person.toString()) //
    }

    data class Person(var name: String, val age: Int,var address: Address)

    data class Address(var name : String, var street : String, val city : String)

//    OutPut
    //04-24 12:30:36.338 5104-5104/com.example.espl.val_vs_var_in_kotlin E/val c: :: 3
//04-24 12:27:08.054 1661-1661/com.example.espl.val_vs_var_in_kotlin E/Value of city of person: - City:: Ahmedabad
//04-24 12:27:08.054 1661-1661/com.example.espl.val_vs_var_in_kotlin E/log of val person: after change of address name,street :: Person(name=Ram, age=50, address=Address(name=Maharshi, street=Dalal street, city=Ahmedabad))
//04-24 12:27:08.054 1661-1661/com.example.espl.val_vs_var_in_kotlin E/log of val person: after change of var address :: Person(name=Tarun, age=50, address=Address(name=Raj street name, street=Raj street, city=Rajkot))
}

Popular Posts