You are on page 1of 43

1. Write a Kotlin program in Android to demonstrate the use of Shared Preferences.

Code:-

activity_main.xml

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a

pk/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"

tools:context="example.kttpoint.com.kotlinsharedpreference.MainActivity">

<TableLayout

android:layout_width="368dp"

android:layout_height="495dp"

android:layout_marginBottom="8dp"

android:layout_marginEnd="8dp"

android:layout_marginStart="8dp"

android:layout_marginTop="8dp"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent">

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_column="0"

android:layout_marginLeft="10sp"
android:layout_marginStart="10sp"

android:text="Enter Id"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

<EditText

android:id="@+id/editId"

android:layout_width="201dp"

android:layout_height="wrap_content"

android:layout_column="1"

android:layout_marginLeft="50sp"

android:layout_marginStart="50sp"

android:hint="id"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

</TableRow>

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_column="0"

android:layout_marginLeft="10sp"

android:layout_marginStart="10sp"

android:text="Enter Name"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Mediu

m" />

<EditText

android:id="@+id/editName"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_column="1"

android:layout_marginLeft="50sp"

android:layout_marginStart="50sp"

android:hint="name"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Mediu

m" />

</TableRow>

<TableRow android:layout_marginTop="60dp">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_column="0"

android:layout_marginLeft="10sp"

android:layout_marginStart="10sp"

android:text="Your Id"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Mediu

m" />

<TextView

android:id="@+id/textViewShowId"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_column="1"

android:layout_marginLeft="50sp"

android:layout_marginStart="50sp"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

</TableRow>
<TableRow android:layout_marginTop="20dp">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_column="0"

android:layout_marginLeft="10sp"

android:layout_marginStart="10sp"

android:text="Your Name"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

<TextView

android:id="@+id/textViewShowName"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_column="1"

android:layout_marginLeft="50sp"

android:layout_marginStart="50sp"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Mediu

m" />

</TableRow>

</TableLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_marginBottom="16dp"

android:layout_marginEnd="8dp"

android:layout_marginStart="8dp"

android:orientation="horizontal"

android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.0"

app:layout_constraintStart_toStartOf="parent">

<Button

android:id="@+id/save"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Save" />

<Button

android:id="@+id/view"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="View" />

<Button

android:id="@+id/clear"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Clear" />

</LinearLayout>

</android.support.constraint.ConstraintLayout>

MainActivity.kt

package example.kttpoint.com.kotlinsharedpreference

import android.content.Context

import android.content.SharedPreferences

import android.support.v7.app.AppCompatActivity

import android.os.Bundle
import android.view.View

import android.widget.Button

import android.widget.EditText

import android.widget.TextView

class MainActivity : AppCompatActivity() {

private val sharedPrefFile = "kotlinsharedpreference"

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

val inputId = findViewById<EditText>(R.id.editId)

val inputName = findViewById<EditText>(R.id.editName)

val outputId = findViewById<TextView>(R.id.textViewShowId)

val outputName = findViewById<TextView>(R.id.textViewShowName)

val btnSave = findViewById<Button>(R.id.save)

val btnView = findViewById<Button>(R.id.view)

val btnClear = findViewById<Button>(R.id.clear)

val sharedPreferences: SharedPreferences = this.getSharedPreferences(sharedPrefFile,Co

ntext.MODE_PRIVATE)

btnSave.setOnClickListener(View.OnClickListener {

val id:Int = Integer.parseInt(inputId.text.toString())

val name:String = inputName.text.toString()

val editor:SharedPreferences.Editor = sharedPreferences.edit()

editor.putInt("id_key",id)

editor.putString("name_key",name)
editor.apply()

editor.commit()

})

btnView.setOnClickListener {

val sharedIdValue = sharedPreferences.getInt("id_key",0)

val sharedNameValue = sharedPreferences.getString("name_key","defaultname")

if(sharedIdValue.equals(0) && sharedNameValue.equals("defaultname")){

outputName.setText("default name: ${sharedNameValue}").toString()

outputId.setText("default id: ${sharedIdValue.toString()}")

}else{

outputName.setText(sharedNameValue).toString()

outputId.setText(sharedIdValue.toString())

btnClear.setOnClickListener(View.OnClickListener {

val editor = sharedPreferences.edit()

editor.clear()

editor.apply()

outputName.setText("").toString()

outputId.setText("".toString())

})

Screenshot:-
3.Write a Kotlin program in Android to demonstrate the use of External Storage

Code:-

activity_main.xml

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

<RelativeLayout 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"

tools:context="example.kttpoint.com.kotlinexternalstoragereadwrite.MainActivity"

>

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"

android:layout_alignParentTop="true"

android:layout_alignStart="@+id/textView2"

android:layout_marginTop="68dp"

android:text="File Name"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.027"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintVertical_bias="0.065" />

<TextView

android:id="@+id/textView2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBottom="@+id/editTextData"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_marginBottom="36dp"

android:layout_marginLeft="50dp"

android:layout_marginStart="50dp"

android:text="File Data"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.027"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/textView"

app:layout_constraintVertical_bias="0.167" />
<EditText

android:id="@+id/editTextFile"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/editTextData"

android:layout_alignStart="@+id/editTextData"

android:layout_alignTop="@+id/textView"

android:ems="10"

android:inputType="none" />

<EditText

android:id="@+id/editTextData"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentEnd="true"

android:layout_alignParentRight="true"

android:layout_below="@+id/editTextFile"

android:layout_marginEnd="37dp"

android:layout_marginRight="37dp"

android:layout_marginTop="30dp"

android:ems="10"

android:inputType="none"

android:lines="5" />

<Button

android:id="@+id/button_save"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentBottom="true"

android:layout_marginBottom="68dp"
android:layout_toLeftOf="@+id/editTextData"

android:layout_toStartOf="@+id/editTextData"

android:text="Save" />

<Button

android:id="@+id/button_view"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBottom="@+id/button_save"

android:layout_alignEnd="@+id/editTextData"

android:layout_alignRight="@+id/editTextData"

android:layout_marginEnd="43dp"

android:layout_marginRight="43dp"

android:text="View" />

</RelativeLayout>

MainActivity.kt

package example.kttpoint.com.kotlinexternalstoragereadwrite

import android.support.v7.app.AppCompatActivity

import android.os.Bundle

import android.view.View

import android.widget.Button

import android.widget.EditText

import android.widget.Toast

import android.os.Environment

import java.io.*

class MainActivity : AppCompatActivity() {

private val filepath = "MyFileStorage"

internal var myExternalFile: File?=null


private val isExternalStorageReadOnly: Boolean get() {

val extStorageState = Environment.getExternalStorageState()

return if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {

true

} else {

false

private val isExternalStorageAvailable: Boolean get() {

val extStorageState = Environment.getExternalStorageState()

return if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {

true

} else{

false

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

val fileName = findViewById(R.id.editTextFile) as EditText

val fileData = findViewById(R.id.editTextData) as EditText

val saveButton = findViewById<Button>(R.id.button_save) as Button

val viewButton = findViewById(R.id.button_view) as Button

saveButton.setOnClickListener(View.OnClickListener {

myExternalFile = File(getExternalFilesDir(filepath), fileName.text.toString())

try {

val fileOutPutStream = FileOutputStream(myExternalFile)

fileOutPutStream.write(fileData.text.toString().toByteArray())
fileOutPutStream.close()

} catch (e: IOException) {

e.printStackTrace()

Toast.makeText(applicationContext,"data save",Toast.LENGTH_SHORT).show()

})

viewButton.setOnClickListener(View.OnClickListener {

myExternalFile = File(getExternalFilesDir(filepath), fileName.text.toString())

val filename = fileName.text.toString()

myExternalFile = File(getExternalFilesDir(filepath),filename)

if(filename.toString()!=null && filename.toString().trim()!=""){

var fileInputStream =FileInputStream(myExternalFile)

var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream)

val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)

val stringBuilder: StringBuilder = StringBuilder()

var text: String? = null

while ({ text = bufferedReader.readLine(); text }() != null) {

stringBuilder.append(text)

fileInputStream.close()

//Displaying data on EditText

Toast.makeText(applicationContext,stringBuilder.toString(),Toast.LENGTH_S

HORT).show()

})

if (!isExternalStorageAvailable || isExternalStorageReadOnly) {

saveButton.isEnabled = false

}
}

AndroidManifest.xml

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

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

package="example.kttpoint.com.kotlinexternalstoragereadwrite">

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

<usespermission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<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>

Screenshot
4.Write a Kotlin program in Android to provide user(s) with 3 options of creating a Simple
Notification,

Custom Notification and Clear Notification. Implement appropriate functionality and perform the

required task

Code :-

activity_main.xml

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a

pk/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"

tools:context="example.kttpoint.com.androidnotification.MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="ANDROID NOTIFICATION"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintLeft_toLeftOf="parent"

app:layout_constraintRight_toRightOf="parent"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintVertical_bias="0.091"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/button"

android:layout_marginBottom="112dp"

android:layout_marginEnd="8dp"

android:layout_marginStart="8dp"

android:text="Notify"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>

activity_notification_view.xml

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a

pk/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"

tools:context="example.kttpoint.com.androidnotification.NotificationView">
<TextView

android:id="@+id/textView2"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:text="your detail of notification..."

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginBottom="8dp"

android:layout_marginEnd="8dp"

android:layout_marginStart="8dp"

android:layout_marginTop="8dp"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.096"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/textView2"

app:layout_constraintVertical_bias="0.206"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>

</android.support.constraint.ConstraintLayout>

MainActivity.kt

package example.kttpoint.com.androidnotification;

import android.app.NotificationManager;

import android.app.PendingIntent;
import android.content.Context;

import android.content.Intent;

import android.support.v4.app.NotificationCompat;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button button;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

addNotification();

});

private void addNotification() {

NotificationCompat.Builder builder =

new NotificationCompat.Builder(this)

.setSmallIcon(R.drawable.messageicon) //set icon for notification

.setContentTitle("Notifications Example") //set title of notification

.setContentText("This is a notification message")//this is notification m

essage

.setAutoCancel(true) // makes auto cancel of notification


.setPriority(NotificationCompat.PRIORITY_DEFAULT); //set priority of n

otification

Intent notificationIntent = new Intent(this, NotificationView.class);

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

//notification message will get at NotificationView

notificationIntent.putExtra("message", "This is a notification message");

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationInte

nt,

PendingIntent.FLAG_UPDATE_CURRENT);

builder.setContentIntent(pendingIntent);

// Add as notification

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIF

ICATION_SERVICE);

manager.notify(0, builder.build());

NotificationView.kt

package example.kttpoint.com.androidnotification;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.TextView;

import android.widget.Toast;

public class NotificationView extends AppCompatActivity {

TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_notification_view);

textView = findViewById(R.id.textView);

//getting the notification message

String message=getIntent().getStringExtra("message");

textView.setText(message);

strings.xml

<resources>

<string name="app_name">AndroidNotification</string>

<string name="notification_activity">NotificationView</string>

</resources>

AndroidManifest.xml

Add the following code in AndroidManifest.xml file.

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

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

package="example.kttpoint.com.androidnotification">

<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>

<activity android:name=".NotificationView"

android:label="@string/notification_activity"

android:parentActivityName=".MainActivity">

<meta-data

android:name="android.support.PARENT_ACTIVITY"

android:value=".MainActivity"/>

</activity>

</application>

</manifest>

Screenshot :-

6.Write a Kotlin program in Android to implement the Telephony API to send SMS

Code:-

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

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

android:orientation="vertical" android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView

android:id="@+id/fstTxt"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="100dp"

android:layout_marginTop="150dp"

android:text="Mobile No" />

<EditText

android:id="@+id/mblTxt"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="100dp"

android:ems="10"/>

<TextView

android:id="@+id/secTxt"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Message"

android:layout_marginLeft="100dp" />

<EditText

android:id="@+id/msgTxt"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="100dp"

android:ems="10" />

<Button

android:id="@+id/btnSend"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="100dp"

android:text="Send SMS" />

</LinearLayout>

MainActivity.kt

package com.tutlane.sendsmsexample;

import android.content.Intent;

import android.net.Uri;

import android.provider.Telephony;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.telephony.SmsManager;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private EditText txtMobile;

private EditText txtMessage;

private Button btnSms;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

txtMobile = (EditText)findViewById(R.id.mblTxt);

txtMessage = (EditText)findViewById(R.id.msgTxt);

btnSms = (Button)findViewById(R.id.btnSend);

btnSms.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {


try{

SmsManager smgr = SmsManager.getDefault();

smgr.sendTextMessage(txtMobile.getText().toString(),nul

l,txtMessage.getText().toString(),null,null);

Toast.makeText(MainActivity.this, "SMS Sent Successfull

y", Toast.LENGTH_SHORT).show();

catch (Exception e){

Toast.makeText(MainActivity.this, "SMS Failed to Send,

Please try again", Toast.LENGTH_SHORT).show();

});

AndroidManifest.xml

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

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

package="com.tutlane.sendsmsexample">

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

<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>

Screenshot

7. Create a database “FriendsDB” to store information about your friends. Implement CRUD
functionality

for the given database.

Code :-

1) Code Database Operations in your app

Below is xml code of our Layout file

<?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"
tools:context=".MainActivity"

android:orientation="vertical"

>

<EditText

android:id="@+id/student_id"

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:ems="10"

android:inputType="number"

android:hint="Student ID"

/>

<EditText

android:id="@+id/student_name"

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:ems="10"

android:inputType="textPersonName"

android:hint="Student Name"

/>

<Button

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:text="Load All Students"

android:onClick="loadStudents"

/>

<TextView

android:id="@+id/result"

android:layout_width="match_parent"
android:layout_height="0dp"

android:layout_weight="1"

android:hint="Result"

android:textSize="30dp"

/>

<Button

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:onClick="addStudent"

android:text="ADD" />

<Button

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:onClick="updateStudent"

android:text="UPDATE"

/>

<Button

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:onClick="deleteStudent"

android:text="DELETE By Id"

/>

</LinearLayout>

MyDBHandler class is our database handler class which

extends SQLiteOpenHelper class to manage database operations. First

time on constructor (MyDBHandler) call we will create our database. In

onCreate() method we will create student table.

MyDBHandler(Context context)
{

super(context, DATABASE_NAME, null, DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase db) {

String CREATE_STUDENT_TABLE = "CREATE TABLE " +

TABLE_STUDENTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY,"

+ COLUMN_NAME

+ " TEXT " + ")";

db.execSQL(CREATE_STUDENT_TABLE);

loadHandler() method will read all records from student

table. addHandler() method will insert a new record in student

table. updateHandler() method will update an existing record in student

table. deleteHandler() method will delete selected record from student

table.

String loadHandler() {

String result = "";

String query = "Select*FROM " + TABLE_STUDENTS;

SQLiteDatabase db = this.getWritableDatabase();

Cursor cursor = db.rawQuery(query, null);

while (cursor.moveToNext()) {

int result_0 = cursor.getInt(0);

String result_1 = cursor.getString(1);

result += String.valueOf(result_0) + " " + result_1 +

System.getProperty("line.separator");

cursor.close();

db.close();

if(result.equals(""))

result="No Record Found";


return result;

long addHandler(Student student) {

long id;

ContentValues values = new ContentValues();

values.put(COLUMN_ID, student.getID());

values.put(COLUMN_NAME, student.getStudentName());

SQLiteDatabase db = this.getWritableDatabase();

id = db.insert(TABLE_STUDENTS, null, values);

db.close();

return id;

boolean updateHandler(int ID, String name) {

SQLiteDatabase db = this.getWritableDatabase();

ContentValues args = new ContentValues();

args.put(COLUMN_ID, ID);

args.put(COLUMN_NAME, name);

return db.update(TABLE_STUDENTS, args, COLUMN_ID + "=" + ID, null) > 0;

boolean deleteHandler(int ID) {

boolean result = false;

String query = "Select*FROM " + TABLE_STUDENTS + " WHERE " + COLUMN_ID + " = '" +

String.valueOf(ID) + "'";

SQLiteDatabase db = this.getWritableDatabase();

Cursor cursor = db.rawQuery(query, null);

Student student = new Student();

if (cursor.moveToFirst()) {

student.setID(Integer.parseInt(cursor.getString(0)));

db.delete(TABLE_STUDENTS, COLUMN_ID + "=?",

new String[] {

String.valueOf(student.getID())
});

cursor.close();

result = true;

db.close();

return result;

In Mainactivity on respective buttons clicks loadStudents(), addStudent(),

updateStudent() and deleteStudent() methods will be called which will

then internally invokes corresponding MyDBHandler method

for crud operation.

public void loadStudents(View view) {

resultText.setText(dbHandler.loadHandler());

studentId.setText("");

studentName.setText("");

public void addStudent (View view) {

if(!studentId.getText().toString().isEmpty() && !studentName.getText().toString().isEmpty()) {

int id = Integer.parseInt(studentId.getText().toString());

String name = studentName.getText().toString();

Student student = new Student(id, name);

long insertId=dbHandler.addHandler(student);

if(insertId==-1){

resultText.setText("Record already exists");

else{

studentId.setText("");

studentName.setText("");

resultText.setText("Record added");

}
else{

resultText.setText("Please fill correct id and name");

public void updateStudent(View view) {

if( !studentId.getText().toString().isEmpty() && !studentName.getText().toString().isEmpty()) {

boolean result = dbHandler.updateHandler(Integer.parseInt(

studentId.getText().toString()), studentName.getText().toString());

if (result) {

studentId.setText("");

studentName.setText("");

resultText.setText("Record Updated");

} else {

resultText.setText("No Record Found");

else{

resultText.setText("Please fill correct id and name");

public void deleteStudent(View view) {

if(!studentId.getText().toString().isEmpty()) {

boolean result = dbHandler.deleteHandler(Integer.parseInt(

studentId.getText().toString()));

if (result) {

studentId.setText("");

studentName.setText("");

resultText.setText("Record Deleted");

} else {

resultText.setText("No Record Found");

}
} else{

resultText.setText("Please fill correct id");

Whole Code

activity_main xml file

<?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"

tools:context=".MainActivity"

android:orientation="vertical"

>

<EditText

android:id="@+id/student_id"

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:ems="10"

android:inputType="number"

android:hint="Student ID"

/>

<EditText

android:id="@+id/student_name"

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:ems="10"

android:inputType="textPersonName"
android:hint="Student Name"

/>

<Button

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:text="Load All Students"

android:onClick="loadStudents"

/>

<TextView

android:id="@+id/result"

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:hint="Result"

android:textSize="30dp"

/>

<Button

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:onClick="addStudent"

android:text="ADD" />

<Button

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:onClick="updateStudent"

android:text="UPDATE"

/>

<Button
android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:onClick="deleteStudent"

android:text="DELETE By Id"

/>

</LinearLayout>

MainActivity.kt

package com.programtown.example;

import android.os.Bundle;

import android.text.method.ScrollingMovementMethod;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

TextView resultText;

EditText studentId;

EditText studentName;

MyDBHandler dbHandler;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

resultText = (TextView) findViewById(R.id.result);

studentId = (EditText) findViewById(R.id.student_id);

studentName = (EditText) findViewById(R.id.student_name);

resultText.setMovementMethod(new ScrollingMovementMethod());

dbHandler= new MyDBHandler(this);

public void loadStudents(View view) {


resultText.setText(dbHandler.loadHandler());

studentId.setText("");

studentName.setText("");

public void addStudent (View view) {

if(!studentId.getText().toString().isEmpty() && !studentName.getText().toString().isEmpty()) {

int id = Integer.parseInt(studentId.getText().toString());

String name = studentName.getText().toString();

Student student = new Student(id, name);

long insertId=dbHandler.addHandler(student);

if(insertId==-1){

resultText.setText("Record already exists");

else{

studentId.setText("");

studentName.setText("");

resultText.setText("Record added");

else{

resultText.setText("Please fill correct id and name");

public void updateStudent(View view) {

if( !studentId.getText().toString().isEmpty() && !studentName.getText().toString().isEmpty()) {

boolean result = dbHandler.updateHandler(Integer.parseInt(

studentId.getText().toString()), studentName.getText().toString());

if (result) {

studentId.setText("");

studentName.setText("");

resultText.setText("Record Updated");
} else {

resultText.setText("No Record Found");

else{

resultText.setText("Please fill correct id and name");

public void deleteStudent(View view) {

if(!studentId.getText().toString().isEmpty()) {

boolean result = dbHandler.deleteHandler(Integer.parseInt(

studentId.getText().toString()));

if (result) {

studentId.setText("");

studentName.setText("");

resultText.setText("Record Deleted");

} else {

resultText.setText("No Record Found");

} else{

resultText.setText("Please fill correct id");

@Override

protected void onDestroy() {

super.onDestroy();

dbHandler.close();

MyDBHandler.kt

package com.programtown.example;
import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class MyDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "studentDB.db";

private static final String TABLE_STUDENTS = "students";

private static final String COLUMN_ID = "StudentID";

private static final String COLUMN_NAME = "StudentName";

MyDBHandler(Context context)

super(context, DATABASE_NAME, null, DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase db) {

String CREATE_STUDENT_TABLE = "CREATE TABLE " +

TABLE_STUDENTS + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME

+ " TEXT " + ")";

db.execSQL(CREATE_STUDENT_TABLE);

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion,

int newVersion) {

db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENTS);

onCreate(db);

String loadHandler() {

String result = "";

String query = "Select*FROM " + TABLE_STUDENTS;


SQLiteDatabase db = this.getWritableDatabase();

Cursor cursor = db.rawQuery(query, null);

while (cursor.moveToNext()) {

int result_0 = cursor.getInt(0);

String result_1 = cursor.getString(1);

result += String.valueOf(result_0) + " " + result_1 +

System.getProperty("line.separator");

cursor.close();

db.close();

if(result.equals(""))

result="No Record Found";

return result;

long addHandler(Student student) {

long id;

ContentValues values = new ContentValues();

values.put(COLUMN_ID, student.getID());

values.put(COLUMN_NAME, student.getStudentName());

SQLiteDatabase db = this.getWritableDatabase();

id = db.insert(TABLE_STUDENTS, null, values);

db.close();

return id;

boolean updateHandler(int ID, String name) {

SQLiteDatabase db = this.getWritableDatabase();

ContentValues args = new ContentValues();

args.put(COLUMN_ID, ID);

args.put(COLUMN_NAME, name);

return db.update(TABLE_STUDENTS, args, COLUMN_ID + "=" + ID, null) > 0;

}
boolean deleteHandler(int ID) {

boolean result = false;

String query = "Select*FROM " + TABLE_STUDENTS + " WHERE " + COLUMN_ID + " = '" +

String.valueOf(ID) + "'";

SQLiteDatabase db = this.getWritableDatabase();

Cursor cursor = db.rawQuery(query, null);

Student student = new Student();

if (cursor.moveToFirst()) {

student.setID(Integer.parseInt(cursor.getString(0)));

db.delete(TABLE_STUDENTS, COLUMN_ID + "=?",

new String[] {

String.valueOf(student.getID())

});

cursor.close();

result = true;

db.close();

return result;

Student.kt

package com.programtown.example;

public class Student {

private int id;

private String studentName;

Student() {

Student(int id, String studentName) {

this.id = id;

this.studentName = studentName;

}
void setID(int id) {

this.id = id;

int getID() {

return this.id;

void setStudentName(String studentname) {

this.studentName = studentname;

String getStudentName() {

return this.studentName;

OUTPUT

You might also like