An Introduction About Kotlin For Android Development

An Introduction About Kotlin For Android Development

Kotlin is a new programming language from JetBrains for multiple platforms. This programming language is a statically-typed which is runs on the Java Virtual Machine and also can be compiled to JavaScript source code or uses the LLVM compiler infrastructure. It’s developed by a team of JetBrains programmers in 2011 when JetBrains unveiled their project named “Kotlin”. Kotlin is an Open-Source Language for mobile development.While the syntax is not compatible with Java, Kotlin is designed to inter-operate with Java code syntax and is reliant on Java code from the existing Java Class constructor jar and Libraries which have used by Java, such as the collections framework. Kotlin is similar to Apple’s Swift.

Syntax:

/* Java Code */
static int num1, num2; //explicit declaration
num1 = 20;
num2 = 30;
/* Kotlin Code*/
val a: Int
val b: Int
a=5
b=10

Configuring Android Studio with Kotlin

The Kotlin plugin will bundle with Android Studio starting from version 3.0. If you use an earlier version, you’ll need to install the Kotlin plugin and it binds with the android studio. Go to File | Settings | Plugins | Install JetBrains plugin… and then search for and install Kotlin. If you are looking at the “Welcome to Android Studio” screen, choose Configure | Plugins | Install JetBrains plugin… You’ll need to restart the IDE after this completes.

MainActivity.kt:Code Syntax, Null Safety 

MainActivity is a Kotlin file with some basic syntax of the language and also adding all the code that we need for the MainActivity.kt in order to open our fragment in android studio.

Syntax:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, “Replace with your own action”, Snackbar.LENGTH_LONG)
                        .setAction(“Action”, null).show();
            }
        });
    }
}

NewsFragment.kt: Extension Functions, Android Extensions with its functions.

NewsFragment.kt provides different Kotlin concepts that will help us to create our NewsFragment fragment. At the end of this story, you will learn:
Extension Functions (Utility class?)
Default Values in Parameters
Android Extensions (bind view)
Delegated Properties
private var newsList: RecyclerView? = null
Syntax:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
    val view = inflater.inflate(R.layout.news_fragment, container, false)
    newsList = view.findViewById(R.id.news_list) as RecyclerView?
    newsList?.setHasFixedSize(true) // use this setting to improve performance
    newsList?.layoutManager = LinearLayoutManager(context)
    return view
}

RecyclerView Delegate Adapters & Data Classes with Kotlin Implementation.

RecyclerView Delegate Adapters & Data Classes  depend on following adapter and class :
Init Constructor
Object Expressions
Single Expressions
Data Classes
Ranges
List & Lambdas (introduction)
Syntax:
class LoadingDelegateAdapter : ViewTypeDelegateAdapter {
    override fun onCreateViewHolder(parent: ViewGroup) = TurnsViewHolder(parent)
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType) {
    }
    class TurnsViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
            parent.inflate(R.layout.news_item_loading)) {
    }
}

Use of Kotlin, RxJava & RxAndroid in android studio code

This is an incredible combo and we are going to take advantages of both by providing a new layer to our App and decoupling our Main UI thread with our background tasks, in this case, to request Reddit news from the server. We are going to leave everything to prepare to connect with a real server script.

Syntax:

fun getNews(): Observable<List<RedditNewsItem>> {
    return Observable.create {
        subscriber ->
        val news = mutableListOf<RedditNewsItem>()
        // api call…
        subscriber.onNext(news)
        subscriber.onCompleted()
    }
}

API Integration with Kotlin for Android app

API is used for send request to the server using parameter and access related data from the server in JSON format.A better way to analyze the content is using a JSON parser like JSON Editor Online (https://www.jsoneditoronline.org/) which is an excellent online tool provided by kotlin.

Syntax:

val callResponse = api.getNews(“”, limit)
val response = callResponse.execute()
if (response.isSuccessful) {
    val news = response.body().data.children.map {
        val item = it.data
        RedditNewsItem(item.author, item.title, item.num_comments,
                item.created, item.thumbnail, item.url)
    }
    subscriber.onNext(news)
    subscriber.onCompleted()
} else {
    subscriber.onError(Throwable(response.message()))
}

Infinite Scroll: Higher-Order functions & Lambdas for android using kotlin

In kotlin, By  Infinite Scroll script the user to see not only the first 10 news but the next news that also belongs to this Top related news. That’s why we introduce here the Infinite Scroll.

Syntax:

fun logExecution(func: () -> Unit) {
    Log.d(“tag”, “before executing func”)
    func()
    Log.d(“tag”, “after executing func”)
}

Orientation Change (Parcelable & Data Classes) for android

Its manager, how to handle run time changes orientation of layout at the same point as landscape or portrait.

Syntax:

data class RedditNews(val after: String,
                      val before: String,
                      val news: List<RedditNewsItem>) : Parcelable {
    // 1
    companion object {
        // 2
        @JvmField @Suppress(“unused”)
        val CREATOR = createParcel { RedditNews(it) } // 3
    }
    // 4
    protected constructor(parcelIn: Parcel) : this(
            parcelIn.readString(),
            parcelIn.readString(),
            mutableListOf<RedditNewsItem>().apply {
                parcelIn.readTypedList(this, RedditNewsItem.CREATOR)
            }
    )
    override fun writeToParcel(dest: Parcel, flags: Int) {
        dest.writeString(after)
        dest.writeString(before)
        dest.writeTypedList(news)
    }
    override fun describeContents() = 0
}

Unit Test with Kotlin for all give task(Mockito, RxJava & Spek) 

We need to configure the project and create our unit tests for the  AppManager Using (Mockito, RxJava & Spek) .

Syntax:

fun testSuccess_basic() {
    // prepare
    val redditNewsResponse = RedditNewsResponse(RedditDataResponse(listOf(), null, null))
    val response = Response.success(redditNewsResponse)
    `when`(callMock.execute()).thenReturn(response)
    // call
    val newsManager = NewsManager(apiMock)
    newsManager.getNews(“”).subscribe(testSub)
    // assert
    testSub.assertNoErrors()
    testSub.assertValueCount(1)
    testSub.assertCompleted()
}

 Kotlin and its Dependency Injection installation and bind

If you’ve already configured the Kotlin plugin in your project, all you need to do is configure kept.
If you already used Dagger, you probably know apt. kept is just the version for Kotlin, which creates the necessary self-generated classes for Dagger.
To configure it, you need to add in build.gradle in that project which created in the android studio.

Syntax:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
}

Continuous Integration with Kotlin (BuddyBuild) for Android app

Buddy build ties together and automates building, deploying and gathering feedback for developed mobile apps.

Generate Signed App to publication On play store:

 
It similar to export build signed the app with a key tool to publish on google play store.

Leave a Comment