Showing posts with label kotlin getting started. Show all posts
Showing posts with label kotlin getting started. Show all posts

Last Updated: December 27, 2017

Things every android developer should know - part 4

Description: In this post, I will show you some interesting tools from Android Studio that developers use.

Also check out Part 1,Part 2  and  Part 3.


So let's get started.


1. Layout Inspector: Layout Inspector is an interesting tool to help track view and their respective properties. It contains-

    •    View Tree - contains the hierarchy of the Android widgets displaying the full nesting of views.
    •    Properties Table - contains the properties attached to the respective view. e.g.: layouts/methods/padding and many more.
 a) How to enable it?
        Goto Tools -> Android -> Layout Inspector fig.1 
     
fig.1 Layout Inspector
 Note: Make sure you have an Android process running for your app and you have an active window present to take the screenshot.

 b) How to understand it?(fig.2)

    Left
       - 'View Tree' showing the full hierarchy of the screen.
   Center
     - Screenshot of the active window       
   Right
      - 'Properties Table' for each view.
  View Click
    - Properties of the widgets get updated on the right pane i.e. 'Properties Table.' and get highlighted on the screenshot screen.


fig.2 Layout Inspector

fig.3 Layout Inspector with Properties

RecyclerView:

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/percentList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</RelativeLayout>
RecyclerView Item:

<android.support.percent.PercentRelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/fifty_huntv"
        android:background="#ff7acfff"
        android:text="20% - 50%"
        android:textColor="@android:color/white"
        style="@style/STYLE_PERCENT_TV"
        app:layout_heightPercent="20%"
        app:layout_widthPercent="50%" />
    <TextView
        android:layout_toRightOf="@id/fifty_huntv"
        android:background="#ffff5566"
        android:text="80%-50%"
        style="@style/STYLE_PERCENT_TV"
        app:layout_heightPercent="80%"
        app:layout_widthPercent="50%" />


</android.support.percent.PercentRelativeLayout>


Its an amazing tool to analyse the screen UI for the developers with all the information available on single click. Simply great.



2. How to change the DPI of the Phone using ADB?

Many times in our development phase we want to check the look of Android UI on low/high-end devices. Changing the DPI could come in handy in such cases.

So let get started.

Step 1: Find out your phone's dpi using the below command of adb shell. Search for 'mBaseDisplayInfo='. And then search for density within it. Save it for the future to revert our DPI
adb shell dumpsys display

Step 2: Search for 'mBaseDisplayInfo' and 'density' as shown in fig.4


fig.4 Display Density
Step 3: Finally enter below adb command to change the dpi. (fig.5) with 200dpi,420dpi and 600dpi respectively

adb shell wm density 150



 


Note: If the changes do not reflect you can also try:
adb shell wm density 150 && adb reboot

That it, the screen will be reloaded and icon sizes will change to withstand the density specified in the command.


For more updates follow us on -  
Twitter

Last Updated: August 18, 2017

Switch from Java to Kotlin


Description: In this post I'm gonna show some of the basic syntax and semantics difference while we use "KOTLIN" in your android application w.r.t JAVA(Java v/s KOTLIN).


So let's get started.



1. Variable Declaration
Java:
String name="coderconsole";

Kotlin:
val  name:String="coderconsole"

2. Casting

Java:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);

Kotlin:
val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager

3. Function Declaration

Java:

void methodDeclaration(){
    methodDeclaration("First Method ");
}

void methodDeclaration(String firstParam) {
    methodDeclaration(firstParam, "Second Method ");
}

void methodDeclaration(String firstParam, String secondParams) {
    System.out.println(firstParam + secondParams);
}


Kotlin:


fun methodDeclaration(){
    methodDeclaration("First Method ")
}

fun methodDeclaration(name : String){
    methodDeclaration(name, "Second Method ")
}

fun methodDeclaration(first : String, second: String){
    println(first + second)
}


4. Static Functions and Variable

Java:

class DeviceUtils{
    static final String name = "coderconsole";

    public static String getAndroidId(Context context){
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }
}



Kotlin:


class DeviceUtils {

    companion object {
        val name: String = "coderconsole"
        @JvmStatic fun getAndroidId(context: Context): String = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
   }

}



5. Ternary


Java:
String ternary(String name) {
    return name.equalsIgnoreCase("coderconsole") ? " Ternary success" : " Ternary failed";
}

Kotlin:
fun ternary(name: String): String {
    return if (name.equals("coderconsole"))"Ternary success" else "Ternary failed"
}

6. Operators(this operators are only useful in kotlin)

a) Null Type(?)- variable can be made null only using null type operator

   val array: String = null /** Null cannot be the value of not null type**/ 
   val array: String? = null  /** Bingo! Will work now **/

b) Safe Type:(?.) - Helpful when we donot know when the variable be null.So instead of throwing NPE it return the value as null.

//The below code will return "customerId" if present else return null even if the "customerObject" is null.
fun safeTypeDemo(customerObject: JSONObject?): String?{
         return customerObject?.optString("customerId")     
}

c) Elvis Operator(?:) - Helpful when we want to return some not-null values, if the first result is null.
Java:
int elvisDemo(JSONObject result){
      if (result != null)
        return result.optInt("marks");
     else  return -1;
   }

Kotlin: 
fun elvisDemo(marksObject: JSONObject?): Int {
         return marksObject?.optInt("marks")?:-1      
}
                                 (or)
fun elvisDemo(marksObject: JSONObject?): Int = marksObject?.optInt("marks")?:-1


d) !! operator - throws Null Pointer when asked explicitly
//The below code will throw NullPointerException if customerObject is null.
fun npeTypeDemoDemo(customerObject: JSONObject?): String{
         return customerObject!!.optString("customerId")     
}


7. Loops
a) for loop:
Java
void forLoopDemo(List mList) {
        for (String item : mList)Log.d("Loop", item);
    }

Kotlin
fun forLoopDemo(mList: List) {
       for (item in mList) Log.d("Loop", item)
    }

b) while/do-while: - there is no syntactical difference from Java.

8. Switch Case
Java
void switchCaseDemo(int type) {
    switch (type){
        case 0:
            Log.d("switch", "value - " + type);
            break;
        case 1:
            Log.d("switch", "value - " + type);
            break;
        default:
            Log.d("switch", "value default");
            break;

    }
}

Kotlin
fun switchCaseDemo(type: Int) {
    when (type) {
        0 -> Log.d("switch", "value - " + type)
        1 -> Log.d("switch", "value - " + type)
        else -> Log.d("switch", "value default")
    }
}


9. Extends/Implements

//This sample contains abstract class and an interface to printData.
public abstract class AbstractA {
    public void printAbstractData(String data){
        System.out.println(data);
    }
}
public interface InterfaceA {
    public void printData(String data);
}


public class ExtendsImpDemo extends AbstractA implements InterfaceA {
    @Override    public void printData(String data) {
        printAbstractData(data);
    }
}


Kotlin

abstract class AbstractA{
    public fun printAbstractData(data: String){
        println(data)
    }
}

interface InterfaceA{
    fun printData(data: String)
}

class ExtendsImpDemo : AbstractA(), InterfaceA {
    override fun printData(data: String) {
        printAbstractData(data)
    }
}


10. Iterating JSONArray

Java:
void arrayTest(JSONArray jsonArray) {
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.optJSONObject(i);
        Log.d("ArrayTest", jsonObject.optString("name"));
    }
}

Kotlin:
fun arrayTest(jsonArray: JSONArray){
    jsonArray.items<JSONObject>().forEachIndexed { i, jsonObject ->
        Log.d("ArrayTest", jsonObject.optString("name"))
    }
}

Kotlin is an awesome language and very fun to write code in it.
For further reference you can try https://try.kotlinlang.org

For more updates follow us on -  Twitter