Android Koltin Build error incompatible version of Kotlin metadata is 1.5.1, expected version is 1.1.15


If your getting error while building in android studio while building apk  

Android Koltin Build error incompatible version of Kotlin metadata is 1.5.1, expected version is 1.1.15.

Error


Error :
   Class 'kotlin.Unit' was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.



Build.gradle(app-level)


Solution

file : build.gradle
 

Replace
implementation "androidx.core:core-ktx:+"


With
implementation "androidx.core:core-ktx:1.5.0"


Read More »

Java Get HostUrl Or Domain From a Given Link


Below method returns host-url or domain from a given link 

private String getDomainName(String url) {

	String domain = "";
	try {
		URL uri = new URL(url);
		domain = uri.getHost();
	} catch (MalformedURLException e) {
		e.printStackTrace();
	}

	return domain;
}


getDomainName("https://www.tutorialsbuzz.com/2018/09/android-hello-world-example.html");

Read More »

Android Placing Drawable Inside Shape (Circle , Rectangle )

 In the previous post / article we have seen how to Convert SVG to Vector drawable in android studio .

In the post we will how to place the Vector drawable inside the any shape ( Oval , Rectangle) Using Layer-List drawable .

Lets place the below Home Icon (Vector Drawable) , Inside the circle , rectangle .

Example 1 

For placing above vector drawable inside the any shape we will create a drawable with root tag layer-list  and add two items to it .
  • Item 1  : add shape drawable and define its stroke (width,color), padding,solid(its background color).
  • Item 2  : add above mentioned vector drawable.

TAG's Inside Item 
  • The shape tag of item defines the shape of drawable .
  • The stroke tag of item define the border of the drawable .
  • The padding tag of item define the inner padding of drawable .

<?xml version="1.0" encoding="utf-8"?>
<layer-list 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">

            <stroke
                android:width="2dp"
                android:color="#3db5ea" />
                
            <padding
                android:bottom="8dp"
                android:left="8dp"
                android:right="8dp"
                android:top="8dp" />
        </shape>
        
    </item>
    
    <item android:drawable="@drawable/ic_home_filled" />
    
</layer-list>

The Shape TAG contains attribute andriod:shape which defines the shape of item ( Oval , Rectangle ) .

Result: 

Example 2


Similarly like above example we will  place the below arrow icon (Vector Drawable) , Inside the circle , rectangle and also on the line




we will place the arrow-icon (vector-drawable) inside layer-list with shape item
<?xml version="1.0" encoding="utf-8"?>
<layer-list 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
    
        <shape android:shape="oval">

            <solid android:color="#fff" />

            <stroke
                android:width="2dp"
                android:color="#3db5ea" />
                
            <padding
                android:bottom="@dimen/ic_padding"
                android:left="@dimen/ic_padding"
                android:right="@dimen/ic_padding"
                android:top="@dimen/ic_padding" />
                
        </shape>
    </item>
    
    <item android:drawable="@drawable/ic_right" />
    
</layer-list>

Using Shape TAG of Item we can place the vector drawable inside ( oval , rectangle , line ) 

Result :


Read More »

Convert SVG to Vector Drawable In Android Studio

What is SVG ?

SVG stands for Scalable Vector Graphics.
SVG defines vector-based graphics in XML format.


What is VectorDrawable ?

A VectorDrawable is a vector graphic defined in an XML file as a set of points, lines, and curves along with its associated color information.

Advantage of VectorDrawable over PNG 
  1. It can be scaled without loss of display quality which means the same file is resized for different screen densities without loss of image quality .
  2. Same file can be used in normal and dark (Just have to apply color tint to vector drawable).
  3. Helps in reducing APK Size . 

To Convert SVG To Vector follow below steps in android studio 

1. Right click on resource folder of your project , then click on new and then click on Vector Asset .
2. A popup window will open select Local SVG option and then browse path then select SVG Icon and then click ok  .
 





 

Read More »

Android Rounded Corner Button

In this post we will see how to add rounded corner to Button using drawable

1. Colors


Define color attritube in color.xml  which will be used in drawable below.

file : colors.xml
<resources>
  
  <color name="button_bgcolor">#EEEEEE</color>
  <color name="button_bgcolor_press">#2e89b1</color>
  <color name="button_bgcolor_enable">#3db5ea</color>

</resources>


1. Drawable


Create Drawable add selector and assign color to item for different state ( enable, pressed )

file : rounded_corner.xml
<?xml version="1.0" encoding="UTF-8"?>
<selector 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false">
        <shape>
            <corners android:radius="22dp" />
            <solid android:color="@color/button_bgcolor" />
        </shape>
    </item>

    <!-- State Pressed-->
    <item android:state_pressed="true">
        <shape>
            <corners android:radius="22dp" />
            <solid android:color="@color/button_bgcolor_press" />
        </shape>
    </item>

    <!-- State Enabled -->
    <item android:state_enabled="true">
        <shape>
            <corners android:radius="22dp" />
            <solid android:color="@color/button_bgcolor_enable" />
        </shape>
    </item>

</selector>


3. XML Layout


Create XML Layout , add TextView and set the background of Button with above defined drawable .

file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="40dp"
    tools:context=".MainActivity">
    
    <androidx.appcompat.widget.AppCompatButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_corner"
        android:gravity="center"
        android:padding="10dp"
        android:text="Hello World!"
        android:textColor="@color/white"
        android:textSize="22sp" />

</LinearLayout>

Read More »

Android Rounded Corner TextView

In this post we will see how to add rounded corner to TextView using drawable 

1. Colors


 Define color attritube in color.xml  which will be used in drawable below.


file : colors.xml
<resources>
  
  <color name="button_bgcolor">#EEEEEE</color>
  <color name="button_bgcolor_press">#2e89b1</color>
  <color name="button_bgcolor_enable">#3db5ea</color>

</resources>


2. Drawable


 Create Drawable add selector and assign color to item for different state ( enable, pressed )

file : rounded_corner.xml
<?xml version="1.0" encoding="UTF-8"?>
<selector 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false">
        <shape>
            <corners android:radius="22dp" />
            <solid android:color="@color/button_bgcolor" />
        </shape>
    </item>

    <!-- State Pressed-->
    <item android:state_pressed="true">
        <shape>
            <corners android:radius="22dp" />
            <solid android:color="@color/button_bgcolor_press" />
        </shape>
    </item>

    <!-- State Enabled -->
    <item android:state_enabled="true">
        <shape>
            <corners android:radius="22dp" />
            <solid android:color="@color/button_bgcolor_enable" />
        </shape>
    </item>

</selector>


3. XML Layout


Create XML Layout , add TextView and set the background of TextView with above defined drawable .

file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="40dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/rounded_corner"
        android:clickable="true"
        android:focusable="true"
        android:gravity="center"
        android:padding="10dp"
        android:text="Hello World!"
        android:textColor="@color/white"
        android:textSize="22sp" />

</LinearLayout>



Read More »

Android Request To Turn On GPS Pragmatically

In the previous tutorial we have seen  how to get location using FusedLocationProviderClient , for apps to request location the device needs to enable the appropriate system settings, such as GPS or Wi-Fi scanning . to turn on gps programmatically using android gms location request and setting clients by presenting the Location Settings dialog for the user to update their settings with a single tap.


1. Gradle


file : build.gradle
dependencies {

    implementation "com.google.android.gms:play-services-location:18.0.0"
}


2. XML Layout


file : activity_main.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3. Set up a location request .

val locationRequest = LocationRequest.create().apply {
            interval = 10000
            fastestInterval = 5000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }

Create the location request and set the parameters as shown in this code sample:
  • Update interval : This method sets the rate in milliseconds at which your app prefers to receive location updates.
  • Fastest update interval : This method sets the fastest rate in milliseconds at which your app can handle location updates .
  • Priority : This method sets the priority of the request . It takes the following values 
1. PRIORITY_HIGH_ACCURACY 
2. PRIORITY_LOW_POWER 
3. PRIORITY_NO_POWER 

Prompt the user to change location settings


1.  Create a LocationSettingsRequest.Builder .

2.  Create SettingsClient instance .

3.  checkLocationSettings method of SettingsClient Checks if the relevant system settings are enabled on the device to  carry out the desired location requests.Call checkLocationSettings on settingsclient instance by passing locationSettingsRequest builder as parameter , it returns Task<LocationSettingsResponse> .
   
4.  Call addOnFailureListener and addOnFailureListener on Task .
  • Inside addOnSuccessListener All location settings are satisfied. The client can initialize locationrequests here.
  • Inside addOnFailureListener Location settings are not satisfied, but this can be fixed by showing the user a dialog. Show the dialog by calling startResolutionForResult() and check the result in onActivityResult().

3. Activity


MainActivity full code .

file : MainActivity.kt
package com.tutorialsbuzz.devicelocationsettings

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


    override fun onResume() {
        super.onResume()
        requestDeviceLocationSettings();
    }

    // request device

    fun requestDeviceLocationSettings() {
        val locationRequest = LocationRequest.create().apply {
            interval = 10000
            fastestInterval = 5000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }

        val builder = LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest)

        val client: SettingsClient = LocationServices.getSettingsClient(this)
        val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build())

        task.addOnSuccessListener { locationSettingsResponse ->
            // All location settings are satisfied. The client can initialize
            // location requests here.
            // ...
            val state = locationSettingsResponse.locationSettingsStates

           val label =
	           "GPS >> (Present: ${state.isGpsPresent}  | Usable: ${state.isGpsUsable} ) \n\n" +
	           "Network >> ( Present: ${state.isNetworkLocationPresent} | Usable: ${state.isNetworkLocationUsable} ) \n\n" +
	           "Location >> ( Present: ${state.isLocationPresent} | Usable: ${state.isLocationUsable} )"

            showToast(label)

            textView.text = label

        }

        task.addOnFailureListener { exception ->
            if (exception is ResolvableApiException) {
                // Location settings are not satisfied, but this can be fixed
                // by showing the user a dialog.
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    exception.startResolutionForResult(
                        this@MainActivity,
                        100
                    )
                } catch (sendEx: IntentSender.SendIntentException) {
                    // Ignore the error.
                    textView.text = sendEx.message.toString()
                }
            }
        }

    }

    fun showToast(msg: String) {
        Toast.makeText(this@MainActivity, msg, Toast.LENGTH_LONG).show()
    }
}




Read More »