Create Free Digital Festival Business Images & Video Maker App Create Free Digital Festival Business Images & Video Maker App

Android is an open-source operating system for mobile devices like smartphones, tablets, watches, and even television. Android programming can be done by Java Programming Language. Recently Android released a new language called Kotlin Programming language.

Kotlin is announced as the primary language of Android. This language is developed for both beginners and professionals. It is easier than the Java programming language. Kotlin is a general-purpose programming language and it is widely used for developing mobile applications.

Kotlin was developed by JetBrains team and the project was started to develop this language in 2010 and was first released in February 2016. This language runs on JVM(Java Virtual Machine) and it can be used anywhere like how Java programming language is today. Not only the android apps but it can be also used to develop server-side apps too. According to Kotlin’s official website, Many tech giants including Uber, Pinterest, Evernote are using Kotlin for android applications. For example, if you do a quick search on Google Trends, It proves that Kotlin is getting popular over the years.

Pros of Kotlin for Android app development

  • Kotlin reduces the writing of code compared to Java. This makes kotlin more usable and concise.
  • It reduces a lot of team efforts. In better terms, it increases team efficiency for having better coding structure and beautiful syntax.
  • Kotlin is easily maintainable and it can be used in a variety of IDE’s. Android Studio is the highly used IDE. This helps increase developer’s productivity.
  • Kotlin is a Less Buggy coding structure. It gives you error or detects bugs during compile time easily.

Cons of Kotlin for Android app development

  • There might be problems if we have pros in it. But definitely one of the major dis-advantage I would like to suggest is, Fewer Kotlin experts are hired.

Let’s discuss about Databases used in Kotlin

Using databases in any coding language plays a vital role in it. Kotlin database connection used to store data locally(Internal/External Storage) or at the server-side. There is no difference between an Android app database using java or kotlin. Every single piece is the same, just a syntax difference.We are now going to discuss some of the databases which are highly used and learn how to insert data in SQLite database in android using kotlin.

Shared Preferences using Kotlin

Shared Preference is one of the databases that is used to store data locally(Phone Storage). Even we can read data which we stored. When a user stores data in MySQL database then that eventually creates a table and number of columns and rows. But coming to preferences there are columns, but rows will always be single. It always rewrites the row which we want to store in it. In other words, it is used like a KEY VALUE pair.

For storing the values we can use Editor class in preference. This class has a method called put, Where we can set our Key and Value in it to store data.

First of all, for creating a preference we need to declare a preference name. For using it anywhere in the class we can just declare our preference name globally. Which we can do as below.

val PREFS_FILENAME = "MyPreference"

For initializing a preference we can just write down in onCreate method of a class. Pass down the preference name in the initializer. Preferences always have two parameters in that method. Preference name and the type of mode preference want to use.

val prefs = this.getSharedPreferences(PREFS_FILENAME, Context.MODE_PRIVATE)

“prefs” is an object which we can use anywhere in our code to store data or retrieve data from shared preference.

After all this initialization stuff, we can start our data to store in it using the “Editor” class which I’ve told before.

val editor = prefs!!.edit()
editor.putString(“DATA”,”value_of_data”)
editor.apply()

We are all set with how to store data in shared preference. Now, we want to get the stored data in the same activity or else you can get data in any of the activity(class) which you’ve created.

val getData = prefs.getString(“DATA”, “”)

The first parameter is used to define the key which you have stored to use. The second parameter is used for declaring any default value in it if incase the value which we are getting could be null. If the value is null then it would rather prefer to choose the default value which we have given in it. If not the value is successfully read.

If a user wants to just clear all the data which he stored then he can just initialize the Editor and call the clear method in it.

This is how we can use Shared Preference to store data and to get stored data from any of the activity in the application. It is so simple and one of the database’s easiest topics.

Android SQLite database in Kotlin

This is another database type that is used in Android development. This database is a very light database that is specifically used for mobile devices. Data is always stored in internal storage. This database is used to store data to a text file on a device. Android has this SQLite as a built-in implementation. This database doesn’t require you to establish any kind of connections like JDBC etc.

Let’s get into some coding. For accessing SQLite in an android project there is no need of adding any dependencies in Gradle. As I told you it is built-in android.

class DatabaseHandler(context: Context): SQLiteOpenHelper(context,DATABASE_NAME,null,DATABASE_VERSION)

We need to extend our class to “SQLiteOpenHelper” class in order to access all the functionalities of SQLite. This OpenHelper class has a constructor where four parameters are confirmed. DATABASE_NAME and DATABASE_VERSION are declared globally inside the companion object in order to access dynamically to our class. We have to declare database name and version and even table name and all the table column names inside the companion object. The use of declaring all these values inside the companion object, We can access them anywhere in our class and if incase we need to change any of the names then we can just update them inside the companion object. It is quite easy when we implement it in this way.

companion object {  
private val DATABASE_VERSION = 1  
private val DATABASE_NAME = "demoDatabase"  
private val TABLE_DEMO = "demoTable"  
private val KEY_ID = "id"  
private val KEY_NAME = "name"  
private val KEY_EMAIL = "email"  
private val KEY_GENDER = "gender"  
private val KEY_PHONE = "phone"  
private val KEY_DOB = "dob"  
}  

When you just extend your own class to “SQLiteOpenHelper” it always asks you to create a constructor and implement its methods. Constructor is which we have already initialized before and it’s time to implement methods. All we just need to do is bring down your cursor to the class and just click “ctrl+enter”. It’ll ask you to implement methods and this is the way it can be done.

Finally, you’ll be able to see those methods in your class.

onCreate method

override fun onCreate(db: SQLiteDatabase?){ }

onUpgrade method

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int){  }

Inside the onCreate method we can just create our table using SQL query

val CREATE_DEMO_TABLE = ("CREATE TABLE " + TABLE_DEMO + "("  +  KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"  + KEY_EMAIL + " TEXT," + KEY_GENDER + " TEXT,"  + KEY_PHONE + " TEXT,"  + KEY_DOB + " TEXT," + ")")  db?.execSQL(CREATE_DEMO_TABLE)

Inside the onUpdate method we can just upgrade our table using SQL query

db!!.execSQL("DROP TABLE IF EXISTS " + TABLE_DEMO) onCreate(db)

Note:- Upgrade and update has a lot of differences. Upgrade is used to update the whole table and update is used to update the column values.

SQLite has four important operations to store data and to retrieve data

1) Insert

2) Read

3) Update

4) Delete

For Insert we can call,

db.insert()

For Read we can call,

Cursor class

For Update we can call,

db.update()

For Delete we can call,

db.delete() or we can also write raw queries too

Note:- Delete has two operations, either single row delete or whole table delete.

JSON(Javascript Object Notation)

This is widely used in android applications. JSON is a server based database where users can store and retrieve data from the server.

JSON have two types of structure

1) JSON Object

2) JSON Array

Objects are findable with {} curly braces and Array are identified with [] square brackets. Rest of them in JSON can be identified as String,int,float, etc.

First things first, we need to add dependencies in order to access any of the JSON third party libraries. JSON has a lot of third party libraries, One amongst them is “Volley” which I’m going to show you here.

Add this dependency in your “build.gradle” file

compile 'com.android.volley:volley:1.0.0'

By adding these you can access all the functionalities and imports in your project.

For example if I’m having an URL where I can get JSON data from it, Then we should initialize volley to call it.

val url = ”https://bugzilla.mozilla.org/rest/bug?assigned_to=lhenry@mozilla.com”
var request = StringRequest(Request.Method.GET,url,ResponseListener{},ErrorListener{});

From above code you can see that Volley has a class called StringRequest which is used to call any of the URLs in order to get a JSON response. It has four important and must be called parameters.

1) Method Type: It can be any of the methods depending on the URL call

2) URL to call: Whatever URL you wanted to call then you can pass that piece of url into this parameter.

3) Response Listener: After calling the URL you’ll get some response that is inside it. You need to fetch that response from this listener in order to output on mobile devices.

4) Error Listener: After calling the URL, If there is an issue with URL JSON or with the mobile internet issue or any other. You need to fetch that error response from this listener in order to output on mobile devices.

Finally, when you’re done with all these things then you just need to call your request. For that Volley has a class called RequestQueue.

var queue = Volley.newRequestQueue(this)
queue.add(request)

Note:- You can call a number of requests inside a queue. As you know, a queue can handle it. Queue is also known as FIFO(First In First Out).

Amar Infotech provides Kotlin app development services, Hire dedicated Kotlin application developers Now!