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>
No comments:
Post a Comment