You are on page 1of 31

NAME: DHRUVNARAYAN RAWAL

ENROLMENT NUMBER: IU2082820063


SUBJECT: ANDROID
SEMESTER: VI
BRANCH: IMCA
Pr1> Write a Kotlin program in Android to demonstrate the use of Shared Preferences.
<?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">

<TextView
android:id="@+id/nameLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name:" />

<EditText
android:id="@+id/nameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<TextView
android:id="@+id/emailLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Email:" />

<EditText
android:id="@+id/emailEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/saveButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save" />

<TextView
android:id="@+id/displayTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />

</LinearLayout>

package com.example.program1

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView

class MainActivity : AppCompatActivity() {

// Define the SharedPreferences object


private lateinit var sharedPreferences: SharedPreferences
// Define the keys for the data we want to store in SharedPreferences
private val KEY_NAME = "name"
private val KEY_EMAIL = "email"

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

// Get the SharedPreferences object


sharedPreferences = getSharedPreferences("mySharedPreferences",
MODE_PRIVATE)

// Set up the UI elements


val nameEditText = findViewById<EditText>(R.id.nameEditText)
val emailEditText = findViewById<EditText>(R.id.emailEditText)
val saveButton = findViewById<Button>(R.id.saveButton)
val displayTextView = findViewById<TextView>(R.id.displayTextView)

// Load the saved data, if any, into the UI elements


nameEditText.setText(sharedPreferences.getString(KEY_NAME, ""))
emailEditText.setText(sharedPreferences.getString(KEY_EMAIL, ""))
displayTextView.text = "Name:
${sharedPreferences.getString(KEY_NAME, "")}\nEmail:
${sharedPreferences.getString(KEY_EMAIL, "")}"

// Set up the save button click listener


saveButton.setOnClickListener {
// Save the data to SharedPreferences
val editor = sharedPreferences.edit()
editor.putString(KEY_NAME, nameEditText.text.toString())
editor.putString(KEY_EMAIL, emailEditText.text.toString())
editor.apply()

// Update the display


displayTextView.text = "Name: ${nameEditText.text}\nEmail:
${emailEditText.text}"
}
}
}

OUTPUT
Pr2> Write a Kotlin program in Android to demonstrate the use of Internal Storage.

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

<EditText
android:id="@+id/inputEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter data to save" />

<Button
android:id="@+id/saveButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save" />

<Button
android:id="@+id/loadButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Load" />

<TextView
android:id="@+id/displayTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />

</LinearLayout>

KT FILE
package com.example.program2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.InputStreamReader

class MainActivity : AppCompatActivity() {

// Define the filename for the data we want to store in internal


storage
private val FILENAME = "mydata.txt"

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Set up the UI elements


val inputEditText = findViewById<EditText>(R.id.inputEditText)
val saveButton = findViewById<Button>(R.id.saveButton)
val loadButton = findViewById<Button>(R.id.loadButton)
val displayTextView = findViewById<TextView>(R.id.displayTextView)

// Set up the save button click listener


saveButton.setOnClickListener {
// Save the data to internal storage
val fileOutputStream = openFileOutput(FILENAME, MODE_PRIVATE)

fileOutputStream.write(inputEditText.text.toString().toByteArray())
fileOutputStream.close()

// Clear the input field


inputEditText.setText("")
}

// Set up the load button click listener


loadButton.setOnClickListener {
// Load the data from internal storage
var data = ""
val file = File(filesDir, FILENAME)
if (file.exists()) {
val fileInputStream = openFileInput(FILENAME)
val inputStreamReader = InputStreamReader(fileInputStream)
val bufferedReader = BufferedReader(inputStreamReader)

data = bufferedReader.readLine()

bufferedReader.close()
inputStreamReader.close()
fileInputStream.close()
}

// Update the display


displayTextView.text = data
}
}
}

OUTPUT
Pr3> Write a Kotlin program in Android to demonstrate the use of External Storage.

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

<EditText
android:id="@+id/inputEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter data to save" />

<Button
android:id="@+id/saveButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save" />

<Button
android:id="@+id/loadButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="View" />

<TextView
android:id="@+id/displayTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />

</LinearLayout>

KT FILE
package com.example.program3

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.InputStreamReader

class MainActivity : AppCompatActivity() {

// Define the filename for the data we want to store in external


storage
private val FILENAME = "mydata.txt"

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Set up the UI elements
val inputEditText = findViewById<EditText>(R.id.inputEditText)
val saveButton = findViewById<Button>(R.id.saveButton)
val loadButton = findViewById<Button>(R.id.loadButton)
val displayTextView = findViewById<TextView>(R.id.displayTextView)

// Set up the save button click listener


saveButton.setOnClickListener {
// Save the data to external storage
val file =
File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), FILENAME)
val fileOutputStream = FileOutputStream(file)

fileOutputStream.write(inputEditText.text.toString().toByteArray())
fileOutputStream.close()

// Clear the input field


inputEditText.setText("")
}

// Set up the load button click listener


loadButton.setOnClickListener {
// Load the data from external storage
var data = ""
val file =
File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), FILENAME)
if (file.exists()) {
val fileInputStream = file.inputStream()
val inputStreamReader = InputStreamReader(fileInputStream)
val bufferedReader = BufferedReader(inputStreamReader)

data = bufferedReader.readLine()

bufferedReader.close()
inputStreamReader.close()
fileInputStream.close()
}

// Update the display


displayTextView.text = data
}
}
}
OUTPUT
Pr4> 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.

XML File
<?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:padding="16dp">

<Button
android:id="@+id/createSimpleBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create Simple Notification" />

<Button
android:id="@+id/createCustomBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create Custom Notification" />

<Button
android:id="@+id/clearNotificationBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Clear Notification" />

</LinearLayout>

Kt File
package com.example.program4
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import androidx.core.app.NotificationCompat

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val createSimpleBtn = findViewById<Button>(R.id.createSimpleBtn)


val createCustomBtn = findViewById<Button>(R.id.createCustomBtn)
val clearNotificationBtn =
findViewById<Button>(R.id.clearNotificationBtn)

// createSimpleBtn click listener


createSimpleBtn.setOnClickListener {
createSimpleNotification()
}

// createCustomBtn click listener


createCustomBtn.setOnClickListener {
createCustomNotification()
}

// clearNotificationBtn click listener


clearNotificationBtn.setOnClickListener {
clearNotification()
}
}

@SuppressLint("NotificationPermission")
private fun createSimpleNotification() {
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as
NotificationManager

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {


val channel = NotificationChannel("default", "Default",
NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}

val notificationBuilder = NotificationCompat.Builder(this,


"default")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Simple Notification Title")
.setContentText("This is a simple notification message.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)

notificationManager.notify(1, notificationBuilder.build())
}

private fun createCustomNotification() {


val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {


val channel = NotificationChannel("default", "Default",
NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}

val notificationIntent = Intent(this, MainActivity::class.java)


val pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0)

val notificationBuilder = NotificationCompat.Builder(this,


"default")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Custom Notification Title")
.setContentText("This is a custom notification message.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
notificationManager.notify(2, notificationBuilder.build())
}

private fun clearNotification() {


val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancelAll()
}
}

OUTPUT
Pr6>. 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>

OUTPUT
Pr7>Create a database “FriendsDB” to store information about your friends. Implement CRUD
functionality for the given database.

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