0% found this document useful (0 votes)
32 views

SQL Lite and Room CRUD Operation

The document describes how to perform CRUD operations using SQLite and Room databases in Android. It includes code samples for creating a database helper class, model classes, and performing insert, read, update and delete operations on a table using SQLite. It also includes code for creating a Room database with DAO classes and entity classes.

Uploaded by

Md Kamal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

SQL Lite and Room CRUD Operation

The document describes how to perform CRUD operations using SQLite and Room databases in Android. It includes code samples for creating a database helper class, model classes, and performing insert, read, update and delete operations on a table using SQLite. It also includes code for creating a Room database with DAO classes and entity classes.

Uploaded by

Md Kamal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

SQL lite CRUD Operation

DB Helper code
import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;

import java.util.List;

public class DBHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "mydatabase";

private static final int DATABASE_VERSION = 1;

private static final String TABLE_NAME = "mytable";

private static final String COLUMN_ID = "_id";

private static final String COLUMN_NAME = "name";

private static final String COLUMN_AGE = "age";


// SQL statement to create the table

private static final String TABLE_CREATE =

"CREATE TABLE " + TABLE_NAME + " (" +

COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +

COLUMN_NAME + " TEXT, " +

COLUMN_AGE + " INTEGER);";

public DBHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(TABLE_CREATE);

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

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

onCreate(db);

// CRUD Operations
// Create operation

public void insertData(String name, int age) {

SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();

values.put(COLUMN_NAME, name);

values.put(COLUMN_AGE, age);

db.insert(TABLE_NAME, null, values);

db.close();

// Read operation

public List<DataModel> getAllData() {

List<DataModel> dataList = new ArrayList<>();

SQLiteDatabase db = this.getReadableDatabase();

String[] projection = {COLUMN_ID, COLUMN_NAME, COLUMN_AGE};

Cursor cursor = db.query(TABLE_NAME, projection, null, null, null, null, null);

while (cursor.moveToNext()) {

long id = cursor.getLong(cursor.getColumnIndex(COLUMN_ID));

String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));

int age = cursor.getInt(cursor.getColumnIndex(COLUMN_AGE));


DataModel data = new DataModel(id, name, age);

dataList.add(data);

cursor.close();

return dataList;

public DataModel getDataById(long id) {

SQLiteDatabase db = this.getReadableDatabase();

String[] projection = {COLUMN_ID, COLUMN_NAME, COLUMN_AGE};

String selection = COLUMN_ID + " = ?";

String[] selectionArgs = {String.valueOf(id)};

Cursor cursor = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null,


null);

DataModel data = null;

if (cursor.moveToFirst()) {

String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));

int age = cursor.getInt(cursor.getColumnIndex(COLUMN_AGE));

data = new DataModel(id, name, age);

}
cursor.close();

return data;

// Update operation

public void updateData(long id, ContentValues updatedValues) {

SQLiteDatabase db = this.getWritableDatabase();

db.update(TABLE_NAME, updatedValues, COLUMN_ID + " = ?", new


String[]{String.valueOf(id)});

db.close();

// Delete operation

public void deleteData(long id) {

SQLiteDatabase db = this.getWritableDatabase();

db.delete(TABLE_NAME, COLUMN_ID + " = ?", new String[]{String.valueOf(id)});

db.close();

}
Model class for retrive recyclerview
public class DataModel {

private long id;

private String name;

private int age;

public DataModel(long id, String name, int age) {

this.id = id;

this.name = name;

this.age = age;

public long getId() {

return id;

public String getName() {

return name;

public int getAge() {

return age;

}
Main Activity Class Code
import android.content.ContentValues;

import android.database.Cursor;

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 java.util.List;

public class MainActivity extends AppCompatActivity {

private DBHelper dbHelper;

private EditText nameEditText, ageEditText, idEditText;

private Button addButton, readButton, updateButton, deleteButton;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
dbHelper = new DBHelper(this);

nameEditText = findViewById(R.id.nameEditText);

ageEditText = findViewById(R.id.ageEditText);

idEditText = findViewById(R.id.idEditText);

addButton = findViewById(R.id.addButton);

readButton = findViewById(R.id.readButton);

updateButton = findViewById(R.id.updateButton);

deleteButton = findViewById(R.id.deleteButton);

addButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

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

int age = Integer.parseInt(ageEditText.getText().toString());

dbHelper.insertData(name, age);

showToast("Data added.");

});

readButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {


List<DataModel> dataList = dbHelper.getAllData();

if (dataList.isEmpty()) {

showToast("No data found.");

return;

StringBuilder buffer = new StringBuilder();

for (DataModel data : dataList) {

buffer.append("ID: ").append(data.getId()).append("\n");

buffer.append("Name: ").append(data.getName()).append("\n");

buffer.append("Age: ").append(data.getAge()).append("\n\n");

showToast(buffer.toString());

});

updateButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

long id = Long.parseLong(idEditText.getText().toString());

ContentValues updatedValues = new ContentValues();

updatedValues.put(DBHelper.COLUMN_NAME, nameEditText.getText().toString());
updatedValues.put(DBHelper.COLUMN_AGE,
Integer.parseInt(ageEditText.getText().toString()));

dbHelper.updateData(id, updatedValues);

showToast("Data updated.");

});

deleteButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

long id = Long.parseLong(idEditText.getText().toString());

dbHelper.deleteData(id);

showToast("Data deleted.");

});

private void showToast(String message) {

Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

}
Room Database CRUDE operation code
App database class code or create database code

package com.example.a75dayshardchallenge.RoomDatabase;

import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

@Database(entities = {day.class, Image.class}, version = 1, exportSchema =


false)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase instance;

public abstract DayDao days75Dao();


public abstract ImgDao Img75Dao();

public static synchronized AppDatabase getInstance(Context context) {


if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "app_database")
.fallbackToDestructiveMigration()
.build();
}
return instance;
}
}
Create Table class for room database

package com.example.a75dayshardchallenge.RoomDatabase;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

import org.checkerframework.checker.nullness.qual.NonNull;

@Entity
public class day {

@NonNull
@ColumnInfo

String id;
@ColumnInfo
boolean field1;
@ColumnInfo
boolean field2;
@ColumnInfo
boolean field3;
@ColumnInfo
boolean field4;
@ColumnInfo
boolean field5;
@ColumnInfo
boolean field6;

@ColumnInfo
int daycount;

@PrimaryKey(autoGenerate = true)
@ColumnInfo
int idcard;

public String getId() {


return id;
}

public void setId(String id) {


this.id = id;
}

public boolean isField1() {


return field1;
}

public void setField1(boolean field1) {


this.field1 = field1;
}

public boolean isField2() {


return field2;
}
public void setField2(boolean field2) {
this.field2 = field2;
}

public boolean isField3() {


return field3;
}

public void setField3(boolean field3) {


this.field3 = field3;
}

public boolean isField4() {


return field4;
}

public void setField4(boolean field4) {


this.field4 = field4;
}

public boolean isField5() {


return field5;
}

public void setField5(boolean field5) {


this.field5 = field5;
}

public boolean isField6() {


return field6;
}

public void setField6(boolean field6) {


this.field6 = field6;
}

public int getDaycount() {


return daycount;
}

public void setDaycount(int daycount) {


this.daycount = daycount;
}

public int getIdcard() {


return idcard;
}

public void setIdcard(int idcard) {


this.idcard = idcard;
}
}
Create DAO class for Query
package com.example.a75dayshardchallenge.RoomDatabase;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;

import java.util.List;
@Dao
public interface DayDao {

@Query("SELECT * FROM day")


List<day> getAllDays();

@Query("SELECT * FROM day WHERE id= :id")


day getDayById(String id);

@Insert
void insertDay(day da);

@Update
void updateDay(day da);

@Query("DELETE FROM day")


void deleteDay();
}

Another class for table


package com.example.a75dayshardchallenge.RoomDatabase;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity
public class Image {
@PrimaryKey(autoGenerate = true)
@ColumnInfo
int id;

@ColumnInfo(name = "image")
private byte[] imageData;

public Image(byte[] imageData) {

this.imageData = imageData;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public byte[] getImageData() {


return imageData;
}

public void setImageData(byte[] imageData) {


this.imageData = imageData;
}
}

Another DAO Class

package com.example.a75dayshardchallenge.RoomDatabase;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;

import java.util.List;
@Dao
public interface ImgDao {

@Insert
long insertImage(Image imageEntity);

@Query("SELECT * FROM Image")


List<Image> getAllImages();

@Query("SELECT * FROM Image WHERE id= :id")


Image getDayByIdd(int id);
@Query("DELETE FROM Image")
void delete();

}
Activity or fragment class Database initialize
AppDatabase database;
DayDao dayDao;
database = AppDatabase.getInstance(this);

database = Room.databaseBuilder(getApplicationContext()
, AppDatabase.class, "app_database").allowMainThreadQueries()
.build();

dayDao = database.days75Dao();

You might also like