Skip to main content

SQLITE in Android

 What is SQLite?

It is a light-weight RDBMS package for android and iOS, it takes very little memory space and best performance as compared to normal database software.

SQLite provides separate memory space under Android Runtime, It supports all SQL queries.

This means we can create tables, insert rows, update rows, and delete rows using SQL Query.

It provides an SQLiteOpenHelper class to create and upgrade the database.


We will create a class with three mandatory components.

1)  Constructor():-

public DatabaseHelper(Context context) {

        super(context, DB_NAME, null, DB_VERSION);

    }

2) onCreate()

 It is used to create a database. when we install any app and SQLite is present then by default onCreate() will be called.

3) onUpgrade()

It is used to change or destroy the database objects. When we uninstall the app then upgrade() will be called.


Syntax to Insert Record into database table.


Android provides ContentValue class to store object data using key=>value pair, where the key contains the column name and the value contains column data.


public void insert(String columndata) { ContentValues contentValue = new ContentValues(); contentValue.put(columnname, columndata); .,...

database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);

}




Updating Record in Android SQLite database table

The following snippet shows how to update a single record.

public int update(long _id, String col1, String col2) { ContentValues contentValues = new ContentValues(); contentValues.put(DatabaseHelper.SUBJECT, col1); contentValues.put(DatabaseHelper.DESC, col2); int i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID + " = " + _id, null); return i; }


Delete Record from Table:-

We just need to pass the id of the record to be deleted as shown below.


public void delete(long _id) {
        database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null);
    }


CODE  for SQLite:-


DESIGN 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"
android:orientation="vertical"
tools:context=".SqliteActivity11">
<LinearLayout
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="RNO"
android:id="@+id/strno" >
</EditText>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="NAME"
android:id="@+id/stname" >
</EditText>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="BRANCH"
android:id="@+id/stbranch">

</EditText>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="FEES"
android:id="@+id/stfees">

</EditText>

</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnsqlite"
android:text="INSERT"
></Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnsselect"
android:text="SELECT"
></Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnupate"
android:text="UPDATE"
></Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btndelete"
android:text="DELETE"
></Button>

</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/lstshowdata">

</ListView>

</LinearLayout>
</LinearLayout>
SQLITEEXAMPLE.JAVA:-

package com.example.testapp;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class SqliteActivity11 extends AppCompatActivity {
Button btn,btnselect,btnupdate,btndelete;
DBMANAGER obj;
EditText txtrno,txtname,txtbranch,txtfees;
ListView lst;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlite11);
obj = new DBMANAGER(this);
obj.open();
btn = findViewById(R.id.btnsqlite);
txtrno = findViewById(R.id.strno);
txtname = findViewById(R.id.stname);
txtbranch = findViewById(R.id.stbranch);
txtfees = findViewById(R.id.stfees);
lst = findViewById(R.id.lstshowdata);
btnselect = findViewById(R.id.btnsselect);
btnupdate = findViewById(R.id.btnupate);
btndelete = findViewById(R.id.btndelete);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
obj.open();
obj.insert(txtname.getText().toString(),txtbranch.getText().toString(),Integer.parseInt(txtfees.getText().toString()));
Toast.makeText(getApplicationContext(),"Insert success" ,Toast.LENGTH_LONG).show();
obj.closeConn();
displaySelect();
}
});
btnupdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
obj.open();
obj.updateStudent(Integer.parseInt(txtrno.getText().toString()),txtname.getText().toString(),txtbranch.getText().toString(),Integer.parseInt(txtfees.getText().toString()));
obj.closeConn();
displaySelect();
}
});
btndelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
obj.open();
obj.deleteStudent(Integer.parseInt(txtrno.getText().toString()));
obj.closeConn();
displaySelect();
}
});
btnselect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
displaySelect();
}
});


}
void displaySelect()
{
obj.open();

Cursor c=obj.fetch();
c.moveToFirst();
String s[] = new String[c.getCount()];
Toast.makeText(getApplicationContext(),""+c.getCount() ,Toast.LENGTH_LONG).show();
for(int i=0;i<c.getCount();i++)
{
s[i] = c.getInt(0) + " "+c.getString(1) + " "+ c.getString(2)+ " "+ c.getInt(3);
c.moveToNext();
}
ArrayAdapter aa = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,s);
lst.setAdapter(aa);
obj.closeConn();
}
}
MyDb.JAVA

package com.example.testapp;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDb extends SQLiteOpenHelper {
public static final String TABLE_NAME = "Student";

// Table columns
public static final String RNO = "rno";
public static final String SNAME = "sname";
public static final String BRANCH = "branch";
public static final String FEES = "fees";
static final int DB_VERSION = 1;
// Database Information
static final String DB_NAME = "test.db";
private static final String CREATE_TABLE = "create table " + TABLE_NAME + "(" + RNO
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + SNAME + " TEXT NOT NULL, " + BRANCH + " TEXT ,"+ FEES + " INTEGER)";
public MyDb(Context ctx)
{
super(ctx,DB_NAME,null,DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("Drop table if exists "+TABLE_NAME);
}
}


DBMANAGER.JAVA


package com.example.testapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import android.database.SQLException;

public class DBMANAGER {
private MyDb dbHelper;

private Context context;

private SQLiteDatabase database;

public DBMANAGER(Context c) {
context = c;
}
public DBMANAGER open() throws SQLException {
dbHelper = new MyDb(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void insert(String name, String branch, int fees) {
ContentValues contentValue = new ContentValues();
contentValue.put(MyDb.SNAME, name);
contentValue.put(MyDb.BRANCH, branch);
contentValue.put(MyDb.FEES, fees);
database.insert(MyDb.TABLE_NAME, null, contentValue);

}
public Cursor fetch() {

Cursor cursor = database.rawQuery("Select * from "+ MyDb.TABLE_NAME,null);
return cursor;
}
public int updateStudent(int rno, String name, String branch, int fees) {


ContentValues contentValue = new ContentValues();
contentValue.put(MyDb.SNAME, name);
contentValue.put(MyDb.BRANCH, branch);
contentValue.put(MyDb.FEES, fees);

// updating row
return database.update(MyDb.TABLE_NAME, contentValue, MyDb.RNO + " = ?",
new String[] { String.valueOf(rno) });
}
public void deleteStudent(int rno) {

database.delete(MyDb.TABLE_NAME, MyDb.RNO + " = ?",
new String[] { String.valueOf(rno) });

}
public void closeConn()
{
database.close();
}
}













Comments

Popular posts from this blog

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

Conditional Statement in Python

It is used to solve condition-based problems using if and else block-level statement. it provides a separate block for  if statement, else statement, and elif statement . elif statement is similar to elseif statement of C, C++ and Java languages. Type of Conditional Statement:- 1) Simple if:- We can write a single if statement also in python, it will execute when the condition is true. for example, One real-world problem is here?? we want to display the salary of employees when the salary will be above 10000 otherwise not displayed. Syntax:- if(condition):    statements The solution to the above problem sal = int(input("Enter salary")) if sal>10000:     print("Salary is "+str(sal)) Q)  WAP to increase the salary of employees from 500 if entered salary will be less than 10000 otherwise the same salaries will be displayed. Solution:- x = int(input("enter salary")) if x<10000:     x=x+500 print(x)   Q) WAP to display th...