Android Programming

Hands On No. 16 : Working with SQLite Database

Source Code of Employee.java
public class Employee {
public static final String TABLE_NAME = "employee";
public static final String COLUMN_ID = "eid";
public static final String COLUMN_ENAME = "ename";
private int eid;
private String ename;

// Create table SQL query
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_ENAME + " TEXT"
+ ")";

public Employee() {
}

public Employee(int eid, String ename) {
this.eid = eid;
this.ename = ename;

}

public int getEId() {
return eid;
}

public String getEname() {
return ename;
}

public void setEname(String ename) {
this.ename = ename;
}

public void setEId(int eid) {
this.eid = eid;
}

}
Source Code of DatabaseHelper.java
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 DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "employee_db";

public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {

// create employee table
db.execSQL(Employee.CREATE_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + Employee.TABLE_NAME);
// Create tables again
onCreate(db);
}
public long insertEmployee(String ename) {
// get writable database as we want to write data
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(Employee.COLUMN_ENAME, ename);

// insert row
long eid = db.insert(Employee.TABLE_NAME, null, values);

// close db connection
db.close();

// return newly inserted row id
return eid;
}
public List<Employee> getAllEmployee() {
List<Employee> employees = new ArrayList<>();

// Select All Query
String selectQuery = "SELECT * FROM " + Employee.TABLE_NAME + " ORDER BY " +
Employee.COLUMN_ID + " DESC";

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Employee emp = new Employee();
emp.setEId(cursor.getInt(cursor.getColumnIndex(Employee.COLUMN_ID)));

emp.setEname(cursor.getString(cursor.getColumnIndex(Employee.COLUMN_ENAME)));


employees.add(emp);
} while (cursor.moveToNext());
}

// close db connection
db.close();

// return notes list
return employees;
}
}

Source Code of MainActivity.java
import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {
private DatabaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
Button save = (Button) findViewById(R.id.save);
Button view = (Button) findViewById(R.id.viewall);
final EditText et1 = (EditText) findViewById(R.id.txtname);


save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
long id = db.insertEmployee(et1.getText().toString());
Toast.makeText(getApplicationContext(),"Record is added Successfully",Toast.LENGTH_LONG).show();
et1.setText("");

}
});
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, viewall.class);

startActivity(intent);


}
});
}
}
Source Code of viewall.java
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

public class viewall extends AppCompatActivity {
private DatabaseHelper db;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewall);
db = new DatabaseHelper(this);
final List<Employee> l = db.getAllEmployee();
int n = l.size();
String[] employeeName = new String[n];

for(int i=0;i<n;i++) {
employeeName[i] = ""+l.get(i).getEname().toString();

}

ArrayAdapter adapter = new ArrayAdapter<String>(viewall.this,
R.layout.list_view, employeeName);

ListView listView = (ListView) findViewById(R.id.lv);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

String value = "You have Clicked On " + adapter.getItem(position) +"";

Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}
});
}
}
Source Code of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>


<ScrollView xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent" android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="Enter Name"
android:textAppearance="@style/TextAppearance.AppCompat.Body2"
android:textColor="@android:color/holo_blue_light"
android:textSize="25sp" />

<EditText
android:id="@+id/txtname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="20"
android:hint="Enter Your Name"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_marginTop="10dp"
android:inputType="textPersonName"
/>


<Button
android:id="@+id/save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SAVE"
android:layout_marginTop="40dp"
android:textSize="25sp"
android:textColor="@android:color/white"
android:background="@color/cardview_dark_background"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"

/>
<Button
android:id="@+id/viewall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="VIEWALL"
android:layout_marginTop="20dp"
android:textSize="25sp"
android:textColor="@android:color/white"
android:background="@color/cardview_dark_background"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_marginBottom="20dp"
/>
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Developed By : w3techblog.com"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Body2"
android:layout_marginTop="20dp"
android:textSize="25sp"
android:layout_marginBottom="40dp"
android:textColor="@android:color/holo_blue_light" />
</LinearLayout>
</ScrollView>
Source Code of activity_viewall.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".viewall">

<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Source Code of list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="12dp"
android:textSize="18dp"
android:textStyle="bold" >
</TextView>