Android Kotlin CURD Operation using Volley

in #android8 years ago

Google announced at I/O 2017 that it will officially support Kotlin as a first language for Android Development.Kotlin tools will be included with Android Studio 3.0. Kotlin is easy to get started with and can be gradually introduced into existing projects, which means that your existing skills and technology investments are preserved. Kotlin was named after an island (Kotlin Island, located nearby the city of Saint-Petersburg).

What is Kotlin ?


Kotlin is powerful language primarily developed by JetBrains Team. It runs on JVM (Java Virtual Machine) and is statically typed programming language (statically-typed languages require you to declare the data types of your variables before you use them) and also can be compiled to JavaScript source code or uses the Low level Virtual Machine compiler infrastructure. It is perfect for Android Development because of Compatibility with Java , Performance (uses byteCode Structure), Interoperability (import java libraries). Kotlin extention is .kt.




Advantages of using Kotlin :

  • Kotlin requires less code to write.
  • Less Crushes occur on Kotlin.
  • Kotlin is Type-safety Language.
  • Kotlin saves time.

Demo Video

 

Lets Get started with Kotlin


Before starting download the preview version of Android Studio 3.0.

Step 1. Create Project


Type your Project Name -> Check Include Kotlin Support -> Click Next


Step 2. Select the Version Minimum SDK


Step 3. Click on Empty Activity


 

Add this to your Gradle File


Dont compile Kotlin if it is already there in Gradle File

 compile 'com.android.volley:volley:1.0.0' 
 compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

Add this to your Manifest File

<uses-permission android:name="android.permission.INTERNET"/>
 

Step 4. Creating Database Structure

Step 5. Writing Connection File

As you have to establish a connection for you database you have to make connection.php file . Run this file on the server you can use XAMPP or WAMP for the local server if you are getting blank screen it means that your connection is established.
<?php

$server_name = "localhost"; //servername
$user_name = "root1"; //username
$password = "root1"; //password
$db= 'freebieslearning'; //database name
$conn = mysqli_connect($server_name, $user_name, $password,$db);

if(!$conn){
die("Error Connection");
}

?>

Step 6. Writing Employee file


Use this URL to check your Inserted Data

<?PHP

include("Connection.php");

if(isset($_POST['name']) && isset($_POST['position'])&& isset($_POST['salary'])&& isset($_POST['experience']))
{
$name = $_POST["name"];

  $position = $_POST["position"];

  $salary = $_POST["salary"];

  $experience = $_POST["experience"];

  $query="INSERT INTO employee(name,position,salary,experience)VALUES('$name','$position','$salary','$experience')";

  $data=mysqli_query($conn,$query);

if($data)
  {
        echo "Data Inserted";
  }
else
  {
        echo "Error While Inserting";
  }

    exit;

}

?>

Step 7. Creating XML Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    android:orientation="vertical"
    tools:context="com.example.sumit.volley_crud_operations.MainActivity">
&lt;ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/kotlin" /&gt;

&lt;LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:orientation="vertical"&gt;

    &lt;TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/colorPrimaryDark"
        android:gravity="center"
        android:padding="5dp"
        android:text="@string/employee_Details"
        android:textColor="@android:color/background_light"
        android:textSize="18sp" /&gt;

    &lt;EditText
        android:id="@+id/editTextName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/enter_name" /&gt;

    &lt;EditText
        android:id="@+id/editTextPosition"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/position"
        android:inputType="textPersonName" /&gt;

    &lt;EditText
        android:id="@+id/editTextSalary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/salary"
        android:inputType="textPersonName" /&gt;


    &lt;EditText
        android:id="@+id/editTextExperience"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/years"
        android:inputType="textPersonName" /&gt;

    &lt;Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:singleLine="true"
        android:text="@string/send_button"
        android:textColor="@android:color/background_light" /&gt;

&lt;/LinearLayout&gt;

</LinearLayout>

Step 8 . Writing Kotlin File

package com.example.sumit.volley_crud_operations

import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.android.volley.DefaultRetryPolicy
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley

class MainActivity : AppCompatActivity() {

// Variable declaration

private var editTextName: EditText? = null
private var editTextPosition: EditText? = null
private var editTextSalary: EditText? = null
private var editTextExperience: EditText? = null
private var button: Button? = null
private var pd: ProgressDialog? = null

//URL

private val URL = "http://vga.ramstertech.com/freebieslearning/employee.php"

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

    pd = ProgressDialog(this@MainActivity)

//Accessing Palette from XML in Kotlin

    editTextName = findViewById(R.id.editTextName) as EditText

    editTextPosition = findViewById(R.id.editTextPosition) as EditText

    editTextSalary = findViewById(R.id.editTextSalary) as EditText

    editTextExperience = findViewById(R.id.editTextExperience) as EditText

    button = findViewById(R.id.button) as Button

    // onClickListener

    button?.setOnClickListener(View.OnClickListener {

        loginRequest()
    })
}

// Method for Inserting data using Volley

private fun loginRequest() {

    pd!!.setMessage("Inserting Data . . ")

    pd!!.show()

    val queue = Volley.newRequestQueue(this@MainActivity)

    val response: String? = null

    val finalResponse = response

    val postRequest = object : StringRequest(Request.Method.POST, URL,Response.Listener&lt;String&gt;
    {
        
// Getting Response from Server
        
        response -&gt;

        pd!!.hide()
        
//Toast Method
        
        toast(response)
        
//Remove Method 
        
        remove()

    },
      Response.ErrorListener {
           // error
           pd!!.hide()
           Log.d("ErrorResponse", finalResponse)
      }
    ) {
        override fun getParams(): Map&lt;String, String&gt; {
            //Creating HashMap
            val params = HashMap&lt;String, String&gt;()

            params.put("name", editTextName?.text.toString())
            params.put("position", editTextPosition?.text.toString())
            params.put("salary", editTextSalary?.text.toString())
            params.put("experience", editTextExperience?.text.toString())

            return params
        }
    }

    postRequest.retryPolicy = DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)

    queue.add(postRequest)


}

//Method for Toast

fun Activity.toast(setToast: CharSequence) {
    Toast.makeText(this, setToast, Toast.LENGTH_SHORT).show()
}

//Method for clear Text After Sending Data to the server

private fun remove(){
    editTextName?.text?.clear()
    editTextPosition?.text?.clear()
    editTextExperience?.text?.clear()
    editTextSalary?.text?.clear()

}

}

 

Run you project Now. Always use LogCat to debug your Applications.

Sort:  

Boost Your Post. Send 0.100 STEEM or SBD and your post url on memo and we will resteem your post on 5000+ followers. check our account to see the follower count.

Coin Marketplace

STEEM 0.05
TRX 0.32
JST 0.082
BTC 62816.13
ETH 1674.13
USDT 1.00
SBD 0.41