
Android app or any application is made of two things Data And Functionality. So In Any application we need a way to store and manage data, Whether you are building a to-do list app, a note-taking app, or a contact app. In Android there are many ways to store data as mentioned below :
- Internal Storage
- External Storage
- SharedPreferances
- SQLite Database in Android
- Cloud Storage (via Network)
But when you want to store large set of data locally then SQLite Database is a preferable option
What is SQLite Database in Android ?
SQLite Database in Android is a lightweight Relational database which comes with Android OS. SQLite Database in Android is an Open Source database, SQLite supports standard relational database features like SQL. SQLite is an open-source relational database used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database. It is embedded in android by default. So there is no need to perform any database setup or administration task. If you want to store data locally in Android SQLite is way to go.
SQLite only has four primitive data types: INTEGER, REAL, TEXT, and BLOB. All other types must be converted into one of these fields before getting saved in the database
SQLite Setup in Android
To Setup SQLite Database we need to create a subclass of SQLiteOpenHelper. SQLiteOpenHelper class provides way to manage database creation and version management. It provides two methods onCreate(SQLiteDatabase db), onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion), which is useful for Database managment.
public class DBHelper extends SQLiteOpenHelper {
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Android SQLiteOpenHelper Class
The SQLiteOpenHelper class is used for database creation and version management. It helps you handle upgrades and creation of your database schema. For performing any database operations, You have to provide the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class and you also need to Implement it’s constructor. There are three constructors of SQLiteOpenHelper class:
- SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
- SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler)
- SQLiteOpenHelper(context: Context?, name: String?, version: Int, openParams: SQLiteDatabase.OpenParams)
Important Methods Of SQLiteOpenHelper class
For creating a table in SQLite Database we will use the onCreate() method of your SQLiteOpenHelper subclass. onCreate() method is called when the database is created for the first time, so we will use this method to execute SQL statements that will create a TABLE in SQLite Database.
Creating a Table
@Override
public void onCreate(SQLiteDatabase db) {
String createNotesData = "CREATE TABLE NotesData ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name TEXT, "
+ "Description TEXT)";
db.execSQL(createNotesData);
}
Here execSQL method is a method of SQLiteDatabase, which is used to executes the sql query.
SQLiteDatabase Methods
Insert Into SQLite Database Table
To insert data into SQLite Database, we will be using the insert() method of SQLiteDatabase. insert method requires three parameters which are as follows:
insert(String tableName, String nullColumnHack, ContentValues values)
- String table : Here we will pass table name where we want to insert the data
- String nullColumnHack: optional may be null, If you want to insert an empty row, in that case ContentValues have no content value, and you should use nullColumnHack
- ContentValues contentValues: ContentValues are smilar to an Associative array or HashMap Where we can put key value pair (COLUMN_NAME and It’s Value)
The following code snippet shows how to insert a new record in the SQLite database
fun addNotes(title: String, description: String) {
val db = this.writableDatabase
val values = ContentValues().apply {
put(COL_TITLE, title)
put(COL_DESCRIPTION, description)
}
db.insert(TABLE_NAME, null, values)
}
public void addNotes(String title, String description) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_TITLE, title);
values.put(COL_DESCRIPTION, description
);
db.insert("NotesData", null, values);
}
Here getWritableDatabase() method is used to open database connection in write mode. Another method you can use is getReadableDatabase() which is used to open the database connection in read mode.
Difference Between getWritableDatabase() and getReadableDatabase()
- getWritableDatabase(): getWritableDatabase method locks the Data file so other Processes may not access it.
- getReadableDatabase(): getReadableDatabase do not lock files Because there are no changes made to the database, So at a same time many processes can read the database.
Fetch Data From SQLite Database
To fetch data from the SQLite Database, we will be using query() method of SQLiteDatabase. query method requires following parameters :
Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
- String table: Here we will pass table name from where we want to get the data.
- String[] columns: For specific columns select from the table.
- String selection: A filter declaring which rows to return, formatted as an SQL WHERE clause. Passing null will return all rows for the given table.
- String [] selectionArgs: You may include ?s in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection. The values will be bound as Strings. If selection is null or does not contain ?s then selectionArgs may be null.
- groupBy: A Filter used for how to group rows. Same as SQL GROUP BY clause, Pass null if you don’t want row to be grouped.
- having: A filter declare which row groups to include in the cursor. Same as SQL HAVING clause, Passing null will cause all row groups to be included, and is required when row grouping is not being used.
- orderBy: How to order the rows, Same AS SQL ORDER BY clause. Passing null will use the default sort order, which may be unordered.
fun getNote(id: Int): NotesModel {
val db = this.readableDatabase
val cursor: Cursor = db.query(
TABLE_NAME,
arrayOf(COL_ID, COL_TITLE, COL_DESCRIPTION),
"$COL_ID=?",
arrayOf(id.toString()),
null,
null,
null
)
cursor.moveToFirst()
val notesModel = NotesModel(cursor.getString(1), cursor.getString(2))
cursor.close()
return notesModel
}
//Code to get a single note
public NotesModel getNote(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{COL_ID, COL_TITLE, COL_DESCRIPTION}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null);
cursor.moveToFirst();
NotesModel notesModel = new NotesModel(cursor.getString(1), cursor.getString(2));
cursor.close();
return notesModel;
}
Here, query() method returns cursor.
Cursor: cursor is the result set from a query operation is called cursor, we loop through the cursor items to process each line of a search result.
Updating Record in SQLite Database in Android
To update data into SQLite Database, we will be using the update() method of SQLiteDatabase. update method requires the following parameteres :
int update(String table, ContentValues values, String whereClause, String[] whereArgs)
- String table: Here we will pass table name from where we want to update the data.
- ContentValues: Similar as in insert() method.
- String whereClause: It’s condition (where you want to update into SQLite Database)
- String[] whereArgs: It allows you to substitute placeholders (?) in the WHERE clause of your SQL statement. These placeholders are then replaced with the actual values from the whereArgs array. This approach helps prevent SQL injection attacks and also makes your code cleaner and more flexible.
fun updateRecord(notesModel: NotesModel) {
val db = this.writableDatabase
val values = ContentValues().apply {
put(COL_TITLE, notesModel.title)
put(COL_DESCRIPTION, notesModel.description)
}
db.update(TABLE_NAME, values, "$COL_ID=?", arrayOf(notesModel.id.toString()))
db.close()
}
public void updateRecord(NotesModel notesModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_TITLE, notesModel.getTitle());
values.put(COL_DESCRIPTION, notesModel.getDescription());
db.update(TABLE_NAME, values, COL_ID + "=?", new String[]{String.valueOf(notesModel.getId())});
db.close();
}
Delete Record From SQLite Database in Android
To delete data from SQLite Database, we will be using the delete() method of SQLiteDatabase. delete method requires the following parameteres :
delete(String table, String whereClause, String[] whereArgs)
- String table: Pass table name where you want to delete the data.
- String whereClause: It’s condition. Passing null will delete all rows.
- String[] whereArgs: Same as update() method.
fun deleteRecord(id: Int) {
val db = this.writableDatabase
db.delete(TABLE_NAME, "$COL_ID=?", arrayOf(id.toString()))
}
public void deleteRecord(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL_ID + "=?", new String[]{String.valueOf(id)});
}
Step by Step Implementation
Here, we have created a small project of NotesApp as shown below :
This app consists of 3 helper classes and 3 activity. First we start with DBHelper.java class, this class will manage all the database operations. We define DBHelper.java class inside db package.
File: DBHelper class
package com.vairagicodes.databaseexample.db
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.vairagicodes.databaseexample.models.NotesModel
class DBHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
companion object {
const val DB_NAME = "NotesDB"
const val DB_VERSION = 1
const val TABLE_NAME = "NotesData"
const val COL_ID = "id"
const val COL_TITLE = "title"
const val COL_DESCRIPTION = "description"
}
override fun onCreate(db: SQLiteDatabase) {
val dbQuery = "CREATE TABLE $TABLE_NAME (" +
"$COL_ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"$COL_TITLE TEXT," +
"$COL_DESCRIPTION TEXT)"
db.execSQL(dbQuery)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// Handle database upgrade as needed
}
fun addNotes(title: String, description: String) {
val db = this.writableDatabase
val values = ContentValues().apply {
put(COL_TITLE, title)
put(COL_DESCRIPTION, description)
}
db.insert(TABLE_NAME, null, values)
}
fun fetchAllNotes(): List<NotesModel> {
val notesModelList = mutableListOf<NotesModel>()
val db = this.readableDatabase
val dbQuery = "SELECT * FROM $TABLE_NAME"
val cursor: Cursor = db.rawQuery(dbQuery, null)
if (cursor.count != 0) {
cursor.moveToFirst()
do {
val notesModel = NotesModel(cursor.getString(1), cursor.getString(2)).apply {
id = cursor.getInt(0)
}
notesModelList.add(notesModel)
} while (cursor.moveToNext())
}
cursor.close()
return notesModelList
}
fun updateRecord(notesModel: NotesModel) {
val db = this.writableDatabase
val values = ContentValues().apply {
put(COL_TITLE, notesModel.title)
put(COL_DESCRIPTION, notesModel.description)
}
db.update(TABLE_NAME, values, "$COL_ID=?", arrayOf(notesModel.id.toString()))
db.close()
}
fun deleteRecord(id: Int) {
val db = this.writableDatabase
db.delete(TABLE_NAME, "$COL_ID=?", arrayOf(id.toString()))
}
fun getNote(id: Int): NotesModel {
val db = this.readableDatabase
val cursor: Cursor = db.query(
TABLE_NAME,
arrayOf(COL_ID, COL_TITLE, COL_DESCRIPTION),
"$COL_ID=?",
arrayOf(id.toString()),
null,
null,
null
)
cursor.moveToFirst()
val notesModel = NotesModel(cursor.getString(1), cursor.getString(2))
cursor.close()
return notesModel
}
}
package com.vairagicodes.databaseexample.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.vairagicodes.databaseexample.model.NotesModel;
import java.util.ArrayList;
import java.util.List;
public class DBHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "NotesDB";
public static final int DB_VERSION = 1;
public static final String TABLE_NAME = "NotesData";
public static final String COL_ID = "id";
public static final String COL_TITLE = "title";
public static final String COL_DESCRIPTION = "description";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String dbQuery = "CREATE TABLE " + TABLE_NAME + "("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COL_TITLE + " TEXT,"
+ COL_DESCRIPTION + " TEXT)";
db.execSQL(dbQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addNotes(String title, String description) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_TITLE, title);
values.put(COL_DESCRIPTION, description
);
db.insert("NotesData", null, values);
}
public List<NotesModel> fetchAllNotes() {
List<NotesModel> notesModelList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String dbQuery = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(dbQuery, null);
if (cursor.getCount() != 0) {
cursor.moveToFirst();
do {
NotesModel notesModel = new NotesModel(cursor.getString(1), cursor.getString(2));
notesModel.setId(cursor.getInt(0));
notesModelList.add(notesModel);
}
while (cursor.moveToNext());
}
cursor.close();
return notesModelList;
}
public void updateRecord(NotesModel notesModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_TITLE, notesModel.getTitle());
values.put(COL_DESCRIPTION, notesModel.getDescription());
db.update(TABLE_NAME, values, COL_ID + "=?", new String[]{String.valueOf(notesModel.getId())});
db.close();
}
public void deleteRecord(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, COL_ID + "=?", new String[]{String.valueOf(id)});
}
//Code to get a single note
public NotesModel getNote(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{COL_ID, COL_TITLE, COL_DESCRIPTION}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null);
cursor.moveToFirst();
NotesModel notesModel = new NotesModel(cursor.getString(1), cursor.getString(2));
cursor.close();
return notesModel;
}
}
In activity_main.xml file, we have created Two Buttons and Two Edittext views, the one edittext is to get the title of the notes and another is to get the description and two buttons, one to save the notes and another is to read all the notes.
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/notes_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title" />
<EditText
android:id="@+id/notes_des"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Write something here" />
<Button
android:id="@+id/save_notes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:text="save"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read"
android:id="@+id/read_notes"
android:layout_marginTop="10dp"
/>
</LinearLayout>
File : MainActivity class file in Kotlin/Java
In, MainActivity we have called the insert() method and on read button click we have opened the other activity (AllNotesActivity) to fetch all the notes saved inside the SQLite database.
package com.vairagicodes.databaseexample
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.vairagicodes.databaseexample.db.DBHelper
import com.vairagicodes.databaseexample.models.NotesModel
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val dbHelper = DBHelper(this)
val notesTitle: EditText = findViewById(R.id.notes_title)
val notesDes: EditText = findViewById(R.id.notes_des)
val saveBtn: Button = findViewById(R.id.save_notes)
val readBtn: Button = findViewById(R.id.read_notes)
saveBtn.setOnClickListener {
val noteDes = notesDes.text.toString()
val noteTitle = notesTitle.text.toString()
val notesModel = NotesModel(noteTitle, noteDes)
dbHelper.addNotes(notesModel.title, notesModel.description)
notesTitle.text.clear()
notesDes.text.clear()
Toast.makeText(this, "Note Saved", Toast.LENGTH_SHORT).show()
}
readBtn.setOnClickListener {
startActivity(Intent(this, AllNotesActivity::class.java))
}
}
}
package com.vairagicodes.databaseexample;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.vairagicodes.databaseexample.db.DBHelper;
import com.vairagicodes.databaseexample.model.NotesModel;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DBHelper dbHelper = new DBHelper(MainActivity.this);
EditText notesTitle = findViewById(R.id.notes_title);
EditText notesDes = findViewById(R.id.notes_des);
Button saveBtn = findViewById(R.id.save_notes);
Button readBtn = findViewById(R.id.read_notes);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String noteDes = notesDes.getText().toString();
String noteTitle = notesTitle.getText().toString();
NotesModel notesModel = new NotesModel(noteTitle, noteDes);
dbHelper.addNotes(notesModel.getTitle(), notesModel.getDescription());
notesTitle.setText("");
notesDes.setText("");
Toast.makeText(MainActivity.this,"Note Saved",Toast.LENGTH_SHORT).show();
}
});
readBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,AllNotesActivity.class));
}
});
}
}
now in, AllNotesActivity we have fetch all the notes using fetchAllNotes() method of the DBHelper class and using listview, we have displayed all the notes that is fetched from the SQLite Database.
activity_all_notes.xml file
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/notes_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AllNotesActivity"
android:divider="@android:color/transparent"
android:dividerHeight="10.0sp"
android:background="@color/white"
android:padding="16dp"
android:clipToPadding="false"
/>
we have created a custome listview for the notes so for that we have created custom view (notes_view) and custom adapter class(NotesAdapter).
notes_view.xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="start"
android:padding="12dp"
>
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@drawable/post"
android:layout_gravity="center"
android:layout_marginStart="10dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginStart="20dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notes Title"
android:id="@+id/notes_view_title"
android:textSize="20sp"
android:textStyle="bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Description"
android:id="@+id/notes_view_des"
android:textSize="14sp"
/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
File: NotesAdapter class
package com.vairagicodes.databaseexample.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import com.vairagicodes.databaseexample.R
import com.vairagicodes.databaseexample.models.NotesModel
class NotesAdapter(context: Context, notesModels: ArrayList<NotesModel>) : ArrayAdapter<NotesModel>(context, 0, notesModels) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var v = convertView
if (v == null) {
v = LayoutInflater.from(context).inflate(R.layout.notes_view, parent, false)
}
val notesModel = getItem(position)
val notesTitle = v!!.findViewById<TextView>(R.id.notes_view_title)
val notesDescription = v.findViewById<TextView>(R.id.notes_view_des)
notesModel?.let {
notesTitle.text = it.title
notesDescription.text = it.description
}
return v
}
}
package com.vairagicodes.databaseexample.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.vairagicodes.databaseexample.R;
import com.vairagicodes.databaseexample.model.NotesModel;
import java.util.ArrayList;
public class NotesAdapter extends ArrayAdapter<NotesModel> {
public NotesAdapter(Context context, ArrayList<NotesModel> notesModels) {
super(context, 0, notesModels);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View v = convertView;
if (v == null) {
v = LayoutInflater.from(getContext()).inflate(R.layout.notes_view, parent, false);
}
NotesModel notesModel = getItem(position);
TextView notesTitle = v.findViewById(R.id.notes_view_title);
TextView notesDescription = v.findViewById(R.id.notes_view_des);
if (notesModel != null) {
notesTitle.setText(notesModel.getTitle());
notesDescription.setText(notesModel.getDescription());
}
return v;
}
}
File: AllNotesActivity class File Kotlin/Java
package com.vairagicodes.databaseexample
import NotesActivity
import android.content.Intent
import android.os.Bundle
import android.widget.AdapterView
import android.widget.ListView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.vairagicodes.databaseexample.adapter.NotesAdapter
import com.vairagicodes.databaseexample.db.DBHelper
import com.vairagicodes.databaseexample.models.NotesModel
class AllNotesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_all_notes)
}
override fun onResume() {
super.onResume()
val notesListView: ListView = findViewById(R.id.notes_list_view)
val dbHelper = DBHelper(this)
val notesModels: ArrayList<NotesModel> = ArrayList(dbHelper.fetchAllNotes())
val notesAdapter = NotesAdapter(this, notesModels)
notesListView.adapter = notesAdapter
notesListView.onItemClickListener = AdapterView.OnItemClickListener { _, view, i, _ ->
val intent = Intent(this@AllNotesActivity, NotesActivity::class.java)
val notesModel = notesAdapter.getItem(i)
notesModel?.let {
intent.putExtra("id", it.id)
startActivity(intent)
}
}
notesAdapter.notifyDataSetChanged()
dbHelper.close()
if (notesModels.isEmpty()) {
Toast.makeText(this, "No Notes Found", Toast.LENGTH_SHORT).show()
}
}
}
package com.vairagicodes.databaseexample;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.vairagicodes.databaseexample.adapter.NotesAdapter;
import com.vairagicodes.databaseexample.db.DBHelper;
import com.vairagicodes.databaseexample.model.NotesModel;
import java.util.ArrayList;
public class AllNotesActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_notes);
}
@Override
protected void onResume() {
super.onResume();
ListView notesListView = findViewById(R.id.notes_list_view);
DBHelper dbHelper = new DBHelper(AllNotesActivity.this);
ArrayList<NotesModel> notesModels;
notesModels = (ArrayList<NotesModel>) dbHelper.fetchAllNotes();
NotesAdapter notesAdapter = new NotesAdapter(this, notesModels);
notesListView.setAdapter(notesAdapter);
notesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(AllNotesActivity.this, NotesActivity.class);
NotesModel notesModel = notesAdapter.getItem(i);
assert notesModel != null;
intent.putExtra("id", notesModel.getId());
startActivity(intent);
}
});
notesAdapter.notifyDataSetChanged();
dbHelper.close();
if (notesModels.isEmpty()) {
Toast.makeText(AllNotesActivity.this, "No Notes Found", Toast.LENGTH_SHORT).show();
}
}
}
In activity_notes.xml file, we have created Two Buttons and Two Edittext views, the one edittext is to update the title of the notes and another is to update the description and two buttons, one to update the notes and another is to delete note.
File: activity_notes.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/notes_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title" />
<EditText
android:id="@+id/notes_des"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:hint="Write something here" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="start"
android:orientation="horizontal">
<Button
android:id="@+id/update_notes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Update" />
<Button
android:id="@+id/delete_notes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:text="Delete" />
</LinearLayout>
</LinearLayout>
File : NotesActivity class file in Kotlin/Java
In, NotesActivity we have called the updateRecord() method and on update button and we have called deleteRecord() method on delete button.
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.vairagicodes.databaseexample.R
import com.vairagicodes.databaseexample.db.DBHelper
import com.vairagicodes.databaseexample.models.NotesModel
class NotesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_notes)
val id = intent.getIntExtra("id", 1)
val dbHelper = DBHelper(this@NotesActivity)
val notesModel = dbHelper.getNote(id)
val notesTitle = findViewById<EditText>(R.id.notes_title)
val notesDes = findViewById<EditText>(R.id.notes_des)
val updateBtn = findViewById<Button>(R.id.update_notes)
val deleteBtn = findViewById<Button>(R.id.delete_notes)
notesTitle.setText(notesModel.title)
notesDes.setText(notesModel.description)
updateBtn.setOnClickListener {
val noteDes = notesDes.text.toString()
val noteTitle = notesTitle.text.toString()
val notesModel = NotesModel(noteTitle, noteDes)
notesModel.id = id
dbHelper.updateRecord(notesModel)
Toast.makeText(this@NotesActivity, "Notes Updated", Toast.LENGTH_SHORT).show()
finish()
}
deleteBtn.setOnClickListener {
dbHelper.deleteRecord(id)
Toast.makeText(this@NotesActivity, "Notes Deleted", Toast.LENGTH_SHORT).show()
finish()
}
}
}
package com.vairagicodes.databaseexample;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.vairagicodes.databaseexample.db.DBHelper;
import com.vairagicodes.databaseexample.model.NotesModel;
public class NotesActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
int id = getIntent().getIntExtra("id", 1);
DBHelper dbHelper = new DBHelper(NotesActivity.this);
NotesModel notesModel = dbHelper.getNote(id);
EditText notesTitle = findViewById(R.id.notes_title);
EditText notesDes = findViewById(R.id.notes_des);
Button updateBtn = findViewById(R.id.update_notes);
Button deleteBtn = findViewById(R.id.delete_notes);
notesTitle.setText(notesModel.getTitle());
notesDes.setText(notesModel.getDescription());
updateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String noteDes = notesDes.getText().toString();
String noteTitle = notesTitle.getText().toString();
NotesModel notesModel = new NotesModel(noteTitle, noteDes);
notesModel.setId(id);
dbHelper.updateRecord(notesModel);
Toast.makeText(NotesActivity.this, "Notes Updated", Toast.LENGTH_SHORT).show();
finish();
}
});
deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dbHelper.deleteRecord(id);
Toast.makeText(NotesActivity.this, "Notes Deleted", Toast.LENGTH_SHORT).show();
finish();
}
});
}
}
If you find this content Helpful feel free to Enroll in our Android Development Course with Kotlin contact us for more information