This website includes Education Information like a programming language, job interview question, general knowledge.mathematics

Education log

PageNavi Results No.

Ads

Thursday, March 19, 2020

how to insert data sqlite using kotlin android

how to insert  data  SQLite using kotlin  android 



Today learn how to insert data  SQLite using kotlin  android follow the  SQLite using kotlin android. for follow the site: google android developer

SQLite is an open-source relational database that is used to perform database operations on Android devices such as storing, manipulating or retrieving persistent data from the database.

By default SQLite database is embedded in android. So, there is no need to perform any database setup or administration task.
The SQLiteOpenHelper class provides the functionality to use the SQLite database.


1.MainActivity.kt:


import android.content.ContentValues
import android.content.Intent
import android.database.sqlite.SQLiteDatabase
import android.os.Bundle
import android.support.v7.app.ActionBarActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
class MainActivity:ActionBarActivity() {

  internal var controller = DBController(this)
  internal var add:Button
  internal var view:Button
  internal var update:Button
  internal var delete:Button
  internal var placeid:EditText
  internal var place:EditText
  internal var country:EditText
  internal var infotext:TextView

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

    placeid = findViewById(R.id.edplaceid) as EditText
    place = findViewById(R.id.edplace) as EditText
    country = findViewById(R.id.edcountry) as EditText
    add = findViewById(R.id.btnadd) as Button
    update = findViewById(R.id.btnupdate) as Button
    delete = findViewById(R.id.btndelete) as Button
    view = findViewById(R.id.btnview) as Button
    infotext = findViewById(R.id.txtresulttext) as TextView

    view.setOnClickListener(object:View.OnClickListener() {
      fun onClick(v:View) {
        val i = Intent(this@MainActivity, PlacesList::class.java)
        startActivity(i)
      }
    })

    add.setOnClickListener(object:View.OnClickListener() {
      fun onClick(v:View) {
        try
        {
          if (place.getText().toString().trim().equals("") || country.getText().toString().trim().equals(""))
          {
            infotext.setText("Please insert place name and country..")
          }
          else
          {
            controller = DBController(getApplicationContext())
            val db = controller.getWritableDatabase()
            val cv = ContentValues()
            cv.put("place", place.getText().toString())
            cv.put("country", country.getText().toString())
            db.insert("places", null, cv)

            db.close()

            infotext.setText("Place added Successfully")
          }
        }
        catch (ex:Exception) {
          infotext.setText(ex.message.toString())
        }
      }
    })


    update.setOnClickListener(object:View.OnClickListener() {
      fun onClick(v:View) {
        try
        {
          if ((place.getText().toString().trim().equals("") && country.getText().toString().trim().equals("")) || placeid.getText().toString().trim().equals(""))
          {
            infotext.setText("Please insert values to update..")
          }
          else
          {
            controller = DBController(getApplicationContext())
            val db = controller.getWritableDatabase()
            val cv = ContentValues()
            cv.put("place", place.getText().toString())
            cv.put("country", country.getText().toString())
            db.update("places", cv, "id=" + placeid.getText().toString(), null)
            Toast.makeText(this@MainActivity,
                           "Updated successfully", Toast.LENGTH_SHORT)
            .show()

            infotext.setText("Updated Successfully")
          }
        }
        catch (ex:Exception) {
          infotext.setText(ex.message.toString())
        }
      }
    })


    delete.setOnClickListener(object:View.OnClickListener() {
      fun onClick(v:View) {
        try
        {
          if (placeid.getText().toString().trim().equals(""))
          {
            infotext.setText("Please insert place ID to delete..")
          }
          else
          {
            controller = DBController(getApplicationContext())
            val db = controller.getWritableDatabase()
            db.delete("places", "id=" + placeid.getText().toString(), null)
            Toast.makeText(this@MainActivity,
                           "deleted successfully", Toast.LENGTH_SHORT)
            .show()

            infotext.setText("Deleted Successfully")
          }
        }
        catch (ex:Exception) {
          infotext.setText(ex.message.toString())
        }
      }
    })
  }

  fun onCreateOptionsMenu(menu:Menu):Boolean {
    // getMenuInflater().inflate(R.menu.menu_main, menu);
    return true
  }

  fun onOptionsItemSelected(item:MenuItem):Boolean {
    val id = item.getItemId()
    //if (id == R.id.action_settings) {
    return true
  }
  //return super.onOptionsItemSelected(item);
}



2. DBController.kt:


import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import java.util.ArrayList
import java.util.HashMap

class DBController(context:Context):SQLiteOpenHelper(context, databasename, null, versioncode) {
  // return contact list
  val allPlace:ArrayList<HashMap<String, String>>
  get() {
    val wordList:ArrayList<HashMap<String, String>>
    wordList = ArrayList<HashMap<String, String>>()
    val selectQuery = "SELECT * FROM " + tablename
    val database = this.getWritableDatabase()
    val cursor = database.rawQuery(selectQuery, null)

    if (cursor.moveToFirst())
    {
      do
      {
        val map = HashMap<String, String>()
        map.put("id", cursor.getString(0))
        map.put("place", cursor.getString(1))
        map.put("country", cursor.getString(2))
        wordList.add(map)

      }
      while (cursor.moveToNext())
    }

    return wordList
  }

  fun onCreate(database:SQLiteDatabase) {
    val query:String
    query = "CREATE TABLE IF NOT EXISTS " + tablename + "(" + id + " integer primary key, " + place + " text, " + country + " text)"
    database.execSQL(query)
  }

  fun onUpgrade(database:SQLiteDatabase, version_old:Int,
                current_version:Int) {
    val query:String
    query = "DROP TABLE IF EXISTS " + tablename
    database.execSQL(query)
    onCreate(database)
  }

  companion object {
    private val tablename = "places" // tablename
    private val place = "place" // column name
    private val id = "ID" // auto generated ID column
    private val country = "country" // column name
    private val databasename = "placesinfo" // Dtabasename
    private val versioncode = 1 //versioncode of the database
  }
}



3. PlacesList.kt:

 

import android.os.Bundle

import android.support.v7.app.ActionBarActivity

import android.view.Menu

import android.view.MenuItem

import android.widget.ListView

import android.widget.SimpleAdapter

import android.widget.TextView

import java.util.HashMap

class PlacesList:ActionBarActivity() {

  internal var controller = DBController(this)

  internal var ls:ListView

  internal var infotext:TextView

  protected fun onCreate(savedInstanceState:Bundle) {

    super.onCreate(savedInstanceState)

    setContentView(R.layout.placeslist)

    ls = findViewById(R.id.placeslist) as ListView

    infotext = findViewById(R.id.txtresulttext) as TextView

    try

    {

      val data = controller.getAllPlace()

      if (data.size != 0)

      {

        // Srno, RMCode, Fileno, Loc, FileDesc, TAGNos

        val adapter = SimpleAdapter(

          this@PlacesList, data, R.layout.rows,

          arrayOf<String>("id", "place", "country"), intArrayOf(R.id.txtplaceid, R.id.txtplacename, R.id.txtcountry))

        ls.setAdapter(adapter)

        val length = (data.size).toString()

        infotext.setText(length + " places")

      }

      else

      {

        infotext.setText("No data in database")

      }

    }

    catch (ex:Exception) {

      infotext.setText(ex.message.toString())

    }

  }

  fun onCreateOptionsMenu(menu:Menu):Boolean {

    // getMenuInflater().inflate(R.menu.menu_main, menu);

    return true

  }

  fun onOptionsItemSelected(item:MenuItem):Boolean {

    val id = item.getItemId()

    //if (id == R.id.action_settings) {

    return true

  }

  // return super.onOptionsItemSelected(item);

}

 

 


 

4. activity_main.xml:

 

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    android:weightSum="7"

    android:background="#ffb6ffb0">

 

    <TextView

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:layout_weight="0.5"

        android:layout_margin="5dp"

        android:gravity="center_horizontal"

        android:text="PLACES TO VISIT : "

        android:textSize="25sp"

        android:textStyle="italic|normal" />

 

    <EditText

        android:id="@+id/edplaceid"

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:layout_weight="1"

        android:layout_margin="5dp"

        android:hint="PLACE ID" />

 

    <EditText

        android:id="@+id/edplace"

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:layout_weight="1"

        android:layout_margin="5dp"

        android:hint="PLACE NAME" />

 

    <EditText

        android:id="@+id/edcountry"

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:layout_weight="1"

        android:layout_margin="5dp"

        android:hint="COUNTRY" />

 

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:layout_weight="0.8"

        android:orientation="horizontal"

        android:weightSum="3">

 

        <Button

            android:id="@+id/btnadd"

            android:layout_width="0dp"

            android:layout_marginLeft="5dp"

            android:layout_marginRight="5dp"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:background="#ffff2f5d"

            android:textColor="#fff"

            android:textSize="20sp"

            android:text="ADD" />

 

        <Button

            android:id="@+id/btnupdate"

            android:layout_width="0dp"

            android:layout_marginLeft="5dp"

            android:layout_marginRight="5dp"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:background="#ffff2f5d"

            android:textColor="#fff"

            android:textSize="20sp"

            android:text="UPDATE" />

 

        <Button

            android:id="@+id/btndelete"

            android:layout_width="0dp"

            android:layout_marginLeft="5dp"

            android:layout_marginRight="5dp"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:background="#ffff2f5d"

            android:textColor="#fff"

            android:textSize="20sp"

            android:text="DELETE" />

    </LinearLayout>

 

    <Button

        android:id="@+id/btnview"

        android:layout_width="match_parent"

        android:layout_marginLeft="5dp"

        android:layout_marginRight="5dp"

        android:layout_marginTop="5dp"

        android:layout_height="0dp"

        android:layout_weight="0.8"

        android:background="#ff2b84ff"

        android:textColor="#fff"

        android:textSize="20sp"

        android:text="VIEW PLACES" />

 

    <TextView

        android:id="@+id/txtresulttext"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginLeft="5dp"

        android:layout_marginTop="15dp"

        android:gravity="left"

        android:text=""

        android:layout_weight="1"

        android:textStyle="italic|bold"

        android:textSize="20sp" />

</LinearLayout>

 



 

 5. placeslist.xml:



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="10">

    <ListView
        android:id="@+id/placeslist"
        android:layout_width="match_parent"
        android:layout_weight="9"
        android:layout_height="0dp"
        android:layout_alignParentLeft="true"></ListView>

    <TextView
        android:id="@+id/txtresulttext"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:gravity="left"
        android:text=""
        android:layout_weight="1"
        android:textStyle="italic|bold"
        android:textSize="13sp" />
</LinearLayout>



 6. rows.xml :

 

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:orientation="vertical" >

 

    <LinearLayout

        android:id="@+id/lvh"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal"

        android:scrollbars="horizontal"

        android:weightSum="4" >

 

        <TextView

            android:id="@+id/txtplaceid"

            android:layout_width="0dp"

            android:layout_height="wrap_content"

            android:layout_weight="0.6"

            android:gravity="center"

            android:text="1"

            android:background="#ffb6ffb0"

            android:textColor="#000"

            android:textSize="20sp" />

 

        <TextView

            android:id="@+id/txtplacename"

            android:layout_width="0dp"

            android:layout_height="wrap_content"

            android:layout_weight="1.7"

            android:gravity="center"

            android:text="Barcelona"

            android:background="#ffc5ffe3"

            android:textColor="#000"

            android:textSize="20sp" />

 

        <TextView

            android:id="@+id/txtcountry"

            android:layout_width="0dp"

            android:layout_height="wrap_content"

            android:layout_weight="1.7"

            android:gravity="center"

            android:text="Spain"

            android:background="#ffd3f5ff"

            android:textColor="#000"

            android:textSize="20sp" />

 

 

    </LinearLayout>

 

</LinearLayout>

 




 

 7. AndroidManifest.xml :


<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.prakash.shree.studentinformation">

 

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

 

</manifest>

 

 

 

No comments:

Post a Comment