Android SQLite Database CRUD Operation

Android SQLite Database CRUD Operation

Hello, All. This is my first blog and I would like to dedicate this blog to the future programmers .I would like to start with the Simple SQLite CRUD Operation in Android.To Understand the SQLite operation very clearly we need to first understand the database queries carefully.So, I am creating one databse for student record.i am creating a table named studentrecord.

DatabaseHelper.java

package com.elogic.sqliteexample.database;

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

import com.elogic.sqliteexample.data.Student;

import java.util.ArrayList;

public class DatabaseHelper extends SQLiteOpenHelper {

public static String DATABASENAME = "studentdatabase";
public static String Person1 = "data_student";
private ArrayList<Student> cartList = new ArrayList<Student>();
Context c;

public DatabaseHelper(Context context) {
super(context, DATABASENAME, null, 33);
c = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE if not exists studentrecord(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "idno "
+ " TEXT ,"
+ "name"
+ " TEXT,"
+ "mark"
+ " TEXT,"
+ "date"
+ " TEXT,"
+ "remark" + " TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS studentrecord");

onCreate(db);
}

public void addmonth1(Student productitem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("idno", productitem.idno);
contentValues.put("name", productitem.name);
contentValues.put("mark", productitem.mark);
contentValues.put("date", productitem.date);
contentValues.put("remark", productitem.remark);
db.insert("studentrecord", null, contentValues);
db.close();

}

// update

public void updatemonth1(Student productList) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", productList.name);

contentValues.put("mark", productList.mark);
contentValues.put("date", productList.date);

contentValues.put("remark", productList.remark);
db.update("studentrecord", contentValues, "idno="
+ productList.idno, null);

db.close();
}
public void removerecord(String studentid) {
try {
// SQLiteDatabase db = this.getWritableDatabase();
// db.execSQL("delete from producttable where productidno="
// + productid);
// db.close();

String[] args = { studentid };
getWritableDatabase().delete("studentrecord", "idno=?", args);

} catch (Exception e) {
e.printStackTrace();
}
}

public ArrayList<Student> getmonth1() {

cartList.clear();

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from studentrecord", null);
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
do {
Student item = new Student();

item.idno = cursor.getString(cursor
.getColumnIndex("idno"));

item.name = cursor.getString(cursor
.getColumnIndex("name"));

item.mark = cursor.getString(cursor
.getColumnIndex("mark"));

item.date = cursor.getString(cursor
.getColumnIndex("date"));

item.remark = cursor.getString(cursor
.getColumnIndex("remark"));

cartList.add(item);

} while (cursor.moveToNext());
}
}
cursor.close();
db.close();
return cartList;
}

}


Here,

first I am designing the first page of my android app called

activity_main.xml.

Here I am adding two buttons.one for inserting new record and

other one for viewing records.

 

Activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >

 <ScrollView 
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 >
 <LinearLayout 
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical">

 <Button
 android:id="@+id/btn_add"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:text="Add Records"
 android:textStyle="bold" />

 
 <Button
 android:id="@+id/btn_month"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:text="View Record"
 android:textStyle="bold" />


 </LinearLayout>
 </ScrollView>

</LinearLayout>
 

 

Now, I am creating one model class for storing and retrieving data using model.so, I am implementing model

class named student with string files related to SQLite table columns.

 

Student.java

package com.elogic.sqliteexample.data;

public class Student {


 public String idno="", name="", mark="",date="", remark="";

 public String getname() {
 return name;
 }

 public void setname(String name) {
 this.name = name;
 }

 public String getmark() {
 return mark;
 }

 public void setmark(String mark) {
 this.mark = mark;
 }

 
 public String getdate() {
 return date;
 }

 public void setdate(String date) {
 this.date = date;
 }


 
 public String getremark() {
 return remark;
 }

 public void setremark(String remark){
 this.remark = remark;
 }
 


 public String getIdno() {
 return idno;
 }

 public void setIdno(String idno) {
 this.idno = idno;
 }

}

 

Now, I am creating java file for this layout calledMainActivity.java. Here, I am putting code for

button on click from where I amredirecting user to another activity.

Mainactivity.java

package com.elogic.sqliteexample.data;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import com.elogic.sqliteexample.R;
import com.elogic.sqliteexample.database.DatabaseHelper;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class AddRecord extends Activity implements OnClickListener {
 

 private Button btn_addrecord;
 private EditText txtpname, txtpprice, txtpid,txtpdate,txtpremark;
 String valid_policy = null, valid_name = null, valid_type=null;
 private DatePickerDialog fromDatePickerDialog;

 int str;
 
 private SimpleDateFormat dateFormatter;
 DatabaseHelper db;
 Student pm;
 Intent i;


 @Override
 protected void onCreate(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onCreate(savedInstanceState);
 setContentView(R.layout.addrecord);
 dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
 
 findViewsById();
 
 setDateTimeField();
 i = getIntent();
 
 
 txtpname = (EditText) findViewById(R.id.txtpname);
 txtpprice = (EditText) findViewById(R.id.txtpprice);

 txtpdate = (EditText) findViewById(R.id.txtpdate);

 txtpremark = (EditText) findViewById(R.id.txtpremark);

 btn_addrecord = (Button) findViewById(R.id.btn_addrecord);

 txtpid = (EditText) findViewById(R.id.txtpid);
 txtpdate.setOnClickListener(this);
 btn_addrecord.setOnClickListener(this);

 // Country Item Selected Listener

 txtpid.addTextChangedListener(new TextWatcher() {

 @Override
 public void onTextChanged(CharSequence s, int start, int before,
 int count) {
 // TODO Auto-generated method stub

 }

 @Override
 public void beforeTextChanged(CharSequence s, int start, int count,
 int after) {
 // TODO Auto-generated method stub

 }

 @Override
 public void afterTextChanged(Editable s) {
 // TODO Auto-generated method stub
 // min lenth 10 and max lenth 12 (2 extra for - as per phone
 // matcher format)
 Is_Valid_policy(9, 9, txtpid);
 }
 });
 
 

 
 txtpname.addTextChangedListener(new TextWatcher() {

 @Override
 public void onTextChanged(CharSequence s, int start, int before,
 int count) {
 // TODO Auto-generated method stub

 }

 @Override
 public void beforeTextChanged(CharSequence s, int start, int count,
 int after) {
 // TODO Auto-generated method stub

 }
 @Override
 public void afterTextChanged(Editable s) {
 // TODO Auto-generated method stub
 Is_Valid_name(txtpname);
 }
 
 });


 }
 private void findViewsById() {
 txtpdate = (EditText) findViewById(R.id.txtpdate); 
 txtpdate.setInputType(InputType.TYPE_NULL);
 
 
 
 }

 private void setDateTimeField() {
 txtpdate.setOnClickListener(this);
 
 
 Calendar newCalendar = Calendar.getInstance();
 fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {

 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
 Calendar newDate = Calendar.getInstance();
 newDate.set(year, monthOfYear, dayOfMonth);
 txtpdate.setText(dateFormatter.format(newDate.getTime()));
 
 str = newDate.getTime().getMonth()+1;
 
 //Log.e("jkdhgjkd", String.valueOf(str));
 }

 },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
 //int n=newCalendar.get(Calendar.MONTH);
 }

 

 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 if(v == txtpdate) {
 fromDatePickerDialog.show();
 } 
 
 switch (v.getId()) {
 case R.id.btn_addrecord:

 if (txtpid.getText().toString().equals("") || txtpid.getText().toString().length()<9 || txtpname.getText().toString().equals("") 
 || txtpprice.getText().toString().equals("") || txtpdate.getText().toString().equals("")) {
 Toast.makeText(AddRecord.this, "Please add Required values..",
 Toast.LENGTH_LONG).show();}
 if(txtpname.getText().toString().length()<3){
 Toast.makeText(AddRecord.this, "Please Enter valid name.",
 Toast.LENGTH_LONG).show();
 }
 
 else {

 db = new DatabaseHelper(getApplicationContext());
 db.getWritableDatabase();
 pm = new Student();
 pm.idno = (txtpid.getText().toString());
 pm.name = txtpname.getText().toString();
 pm.mark = txtpprice.getText().toString();
 pm.date = txtpdate.getText().toString();

 pm.remark = txtpremark.getText().toString();
 
// Log.i("idno,productname,productprice,producttype,productdate,productfree,productpaid,productnopaid,productpay,productremark", "" + pm.idno + ""
// + pm.productname + "" + pm.productprice + "" + pm.producttype + "" + pm.productdate + "" + pm.productfree + "" + pm.productpaid + "" + pm.productnopaid + "" + pm.productpay + "" + pm.productremark );
 db.addmonth1(pm);
 

 
 
 Toast.makeText(AddRecord.this, "Record Added successfully.",
 Toast.LENGTH_LONG).show();
 finish();
 }
 break;

 default:
 break;
 }

 }
 public void Is_Valid_policy(int MinLen, int MaxLen,
 EditText edt) throws NumberFormatException {
 if (edt.getText().toString().length() <= 0) {
 edt.setError("Number Only");
 valid_policy = null;
 } else if (edt.getText().toString().length() < MinLen) {
 edt.setError("Minimum length " + MinLen);
 valid_policy = null;

 } else if (edt.getText().toString().length() > MaxLen) {
 edt.setError("Maximum length " + MaxLen);
 valid_policy = null;

 } else {
 valid_policy = edt.getText().toString();

 }

 } 
 
 public void Is_Valid_name(EditText edt) throws NumberFormatException {
 if (edt.getText().toString().length() <= 0) {
 edt.setError("Accept Alphabets Only.");
 valid_name = null;
 } else if (!edt.getText().toString().matches("[a-zA-Z ]+")) {
 edt.setError("Accept Alphabets Only.");
 valid_name = null;
 } 
 else {
 valid_name = edt.getText().toString();
 }

 }
 public void Is_Valid_type(int MinLen, int MaxLen,
 EditText edt) throws NumberFormatException {
 if (edt.getText().toString().length() <= 0) {
 edt.setError("Number Only");
 valid_type = null;
 } else if (edt.getText().toString().length() < MinLen) {
 edt.setError("Minimum length " + MinLen);
 valid_type = null;

 } else if (edt.getText().toString().length() > MaxLen) {
 edt.setError("Maximum length " + MaxLen);
 valid_type = null;

 } else {
 valid_type = edt.getText().toString();

 }

 } 

 public void Show_Toast(String msg) {
 Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
 }
}

 

So, Now I am designing layout for inserting new record inthe database. Here it is my layout file for inserting new record named as

 

AddNewrecord.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >

 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_marginBottom="15dp"
 android:layout_marginTop="10dp"
 android:gravity="center"
 android:text="ADD Record"
 android:textSize="18dp"
 android:textStyle="bold" />
 
 <ScrollView 
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 >
 <LinearLayout 
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical">

 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_marginLeft="5dp"
 android:text="ID No"
 />

 <EditText
 android:id="@+id/txtpid"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:hint="ID no"
 android:inputType="number"
 android:maxLength="9"/>

 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_marginLeft="5dp"
 android:text=" Student Name" />

 <EditText
 android:id="@+id/txtpname"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:hint="Student name" />

 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_marginLeft="5dp"
 android:text="Marks" />

 <EditText
 android:id="@+id/txtpprice"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:hint="marks"
 android:inputType="number"
 android:maxLength="4" />

 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_marginLeft="5dp"
 android:text="Date" />

 <EditText
 android:id="@+id/txtpdate"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:hint="Date" 
 android:inputType="none"/>

 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_marginLeft="5dp"
 android:text="Remarks" />
 <EditText
 android:id="@+id/txtpremark"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:hint="Remarks" />

 <Button
 android:id="@+id/btn_addrecord"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:text="Save" />
 </LinearLayout>
 </ScrollView>

</LinearLayout>

 

Now, implementing

java file for adding new record in SQLite database.

Here I have putted validation for required field and implemented date picker

dialog box.

 

Addnewrecord.java

package com.elogic.sqliteexample.data;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import com.elogic.sqliteexample.R;
import com.elogic.sqliteexample.database.DatabaseHelper;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class AddRecord extends Activity implements OnClickListener {
 

 private Button btn_addrecord;
 private EditText txtpname, txtpprice, txtpid,txtpdate,txtpremark;
 String valid_policy = null, valid_name = null, valid_type=null;
 private DatePickerDialog fromDatePickerDialog;

 int str;
 
 private SimpleDateFormat dateFormatter;
 DatabaseHelper db;
 Student pm;
 Intent i;


 @Override
 protected void onCreate(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onCreate(savedInstanceState);
 setContentView(R.layout.addrecord);
 dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
 
 findViewsById();
 
 setDateTimeField();
 i = getIntent();
 
 
 txtpname = (EditText) findViewById(R.id.txtpname);
 txtpprice = (EditText) findViewById(R.id.txtpprice);

 txtpdate = (EditText) findViewById(R.id.txtpdate);

 txtpremark = (EditText) findViewById(R.id.txtpremark);

 btn_addrecord = (Button) findViewById(R.id.btn_addrecord);

 txtpid = (EditText) findViewById(R.id.txtpid);
 txtpdate.setOnClickListener(this);
 btn_addrecord.setOnClickListener(this);

 // Country Item Selected Listener

 txtpid.addTextChangedListener(new TextWatcher() {

 @Override
 public void onTextChanged(CharSequence s, int start, int before,
 int count) {
 // TODO Auto-generated method stub

 }

 @Override
 public void beforeTextChanged(CharSequence s, int start, int count,
 int after) {
 // TODO Auto-generated method stub

 }

 @Override
 public void afterTextChanged(Editable s) {
 // TODO Auto-generated method stub
 // min lenth 10 and max lenth 12 (2 extra for - as per phone
 // matcher format)
 Is_Valid_policy(9, 9, txtpid);
 }
 });
 
 

 
 txtpname.addTextChangedListener(new TextWatcher() {

 @Override
 public void onTextChanged(CharSequence s, int start, int before,
 int count) {
 // TODO Auto-generated method stub

 }

 @Override
 public void beforeTextChanged(CharSequence s, int start, int count,
 int after) {
 // TODO Auto-generated method stub

 }
 @Override
 public void afterTextChanged(Editable s) {
 // TODO Auto-generated method stub
 Is_Valid_name(txtpname);
 }
 
 });


 }
 private void findViewsById() {
 txtpdate = (EditText) findViewById(R.id.txtpdate); 
 txtpdate.setInputType(InputType.TYPE_NULL);
 
 
 
 }

 private void setDateTimeField() {
 txtpdate.setOnClickListener(this);
 
 
 Calendar newCalendar = Calendar.getInstance();
 fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {

 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
 Calendar newDate = Calendar.getInstance();
 newDate.set(year, monthOfYear, dayOfMonth);
 txtpdate.setText(dateFormatter.format(newDate.getTime()));
 
 str = newDate.getTime().getMonth()+1;
 
 //Log.e("jkdhgjkd", String.valueOf(str));
 }

 },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
 //int n=newCalendar.get(Calendar.MONTH);
 }

 

 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 if(v == txtpdate) {
 fromDatePickerDialog.show();
 } 
 
 switch (v.getId()) {
 case R.id.btn_addrecord:

 if (txtpid.getText().toString().equals("") || txtpid.getText().toString().length()<9 || txtpname.getText().toString().equals("") 
 || txtpprice.getText().toString().equals("") || txtpdate.getText().toString().equals("")) {
 Toast.makeText(AddRecord.this, "Please add Required values..",
 Toast.LENGTH_LONG).show();}
 if(txtpname.getText().toString().length()<3){
 Toast.makeText(AddRecord.this, "Please Enter valid name.",
 Toast.LENGTH_LONG).show();
 }
 
 else {

 db = new DatabaseHelper(getApplicationContext());
 db.getWritableDatabase();
 pm = new Student();
 pm.idno = (txtpid.getText().toString());
 pm.name = txtpname.getText().toString();
 pm.mark = txtpprice.getText().toString();
 pm.date = txtpdate.getText().toString();

 pm.remark = txtpremark.getText().toString();
 
// Log.i("idno,productname,productprice,producttype,productdate,productfree,productpaid,productnopaid,productpay,productremark", "" + pm.idno + ""
// + pm.productname + "" + pm.productprice + "" + pm.producttype + "" + pm.productdate + "" + pm.productfree + "" + pm.productpaid + "" + pm.productnopaid + "" + pm.productpay + "" + pm.productremark );
 db.addmonth1(pm);
 

 
 
 Toast.makeText(AddRecord.this, "Record Added successfully.",
 Toast.LENGTH_LONG).show();
 finish();
 }
 break;

 default:
 break;
 }

 }
 public void Is_Valid_policy(int MinLen, int MaxLen,
 EditText edt) throws NumberFormatException {
 if (edt.getText().toString().length() <= 0) {
 edt.setError("Number Only");
 valid_policy = null;
 } else if (edt.getText().toString().length() < MinLen) {
 edt.setError("Minimum length " + MinLen);
 valid_policy = null;

 } else if (edt.getText().toString().length() > MaxLen) {
 edt.setError("Maximum length " + MaxLen);
 valid_policy = null;

 } else {
 valid_policy = edt.getText().toString();

 }

 } 
 
 public void Is_Valid_name(EditText edt) throws NumberFormatException {
 if (edt.getText().toString().length() <= 0) {
 edt.setError("Accept Alphabets Only.");
 valid_name = null;
 } else if (!edt.getText().toString().matches("[a-zA-Z ]+")) {
 edt.setError("Accept Alphabets Only.");
 valid_name = null;
 } 
 else {
 valid_name = edt.getText().toString();
 }

 }
 public void Is_Valid_type(int MinLen, int MaxLen,
 EditText edt) throws NumberFormatException {
 if (edt.getText().toString().length() <= 0) {
 edt.setError("Number Only");
 valid_type = null;
 } else if (edt.getText().toString().length() < MinLen) {
 edt.setError("Minimum length " + MinLen);
 valid_type = null;

 } else if (edt.getText().toString().length() > MaxLen) {
 edt.setError("Maximum length " + MaxLen);
 valid_type = null;

 } else {
 valid_type = edt.getText().toString();

 }

 } 

 public void Show_Toast(String msg) {
 Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
 }
}

 

Now, implementing list view for displaying records in a list.

so,layout for list view file with update and delete button is

 

Viewrecord.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >

 
 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_marginBottom="15dp"
 android:layout_marginTop="10dp"
 android:gravity="center"
 android:text="View Record"
 android:textSize="18dp"
 android:textStyle="bold" />
 <LinearLayout
 
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:layout_marginTop="10dp"
 android:orientation="horizontal"
 android:weightSum="2" >

 <EditText
 android:id="@+id/search"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:layout_marginLeft="5dp"
 android:layout_marginRight="5dp"
 android:layout_weight="1"
 android:hint="Search"
 />


 </LinearLayout>
 
 

 <TextView
 android:id="@+id/totalrecords"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_marginBottom="15dp"
 android:layout_marginTop="10dp"
 android:gravity="center"
 android:textSize="18dp"
 android:textStyle="bold" />

 <ListView
 android:id="@+id/listview"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" >
 </ListView>
 

</LinearLayout>

 

Now I am designing view of student record

 

Listview_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:background="#999999"
 android:orientation="vertical" >

 <LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="3dp"
 android:orientation="horizontal" >

 <TextView
 android:id="@+id/txt1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="ID no"
 android:textColor="@android:color/black"
 android:textStyle="bold" />

 <TextView
 android:id="@+id/txtdisplaypid"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginLeft="7dp"
 android:text="id no"
 android:textColor="@android:color/black" />
 </LinearLayout>

 <LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="3dp"
 android:orientation="horizontal" >

 <TextView
 android:id="@+id/txt2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Student Name"
 android:textColor="@android:color/black"
 android:textStyle="bold" />

 <TextView
 android:id="@+id/txtdisplaypname"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginLeft="7dp"
 android:text="Student Name"
 android:textColor="@android:color/black" />
 </LinearLayout>

 <LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="3dp"
 android:orientation="horizontal" >

 <TextView
 android:id="@+id/txt3"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Marks"
 android:textColor="@android:color/black"
 android:textStyle="bold" />

 <TextView
 android:id="@+id/txtdisplaypprice"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginLeft="7dp"
 android:text="marks"
 android:textColor="@android:color/black" />
 </LinearLayout>

 <LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="3dp"
 android:orientation="horizontal" >

 <TextView
 android:id="@+id/txt5"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Date"
 android:textColor="@android:color/black"
 android:textStyle="bold" />

 <TextView
 android:id="@+id/txtdisplaydate"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginLeft="7dp"
 android:text="date"
 android:textColor="@android:color/black" />
 </LinearLayout>



 
 <LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="3dp"
 android:orientation="horizontal" >

 <TextView
 android:id="@+id/txt9"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Remarks"
 android:textColor="@android:color/black"
 android:textStyle="bold" />

 <TextView
 android:id="@+id/txtdisplayremark"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginLeft="7dp"
 android:text="remarks"
 android:textColor="@android:color/black" />
 </LinearLayout>

 <LinearLayout
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_margin="3dp"
 android:orientation="horizontal" >

 <Button
 android:id="@+id/btn_update"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:text="update" />

 <Button
 android:id="@+id/btn_delete"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:text="Delete" />
 
 </LinearLayout>
 
 

</LinearLayout>

 

Now implementing coding part of displaying database

records to the user. Here I am storing database in an array

list of type student and passing this list to the adapter and

setting adapter in a list view.

Here I am also refreshing data on Resume because if user

updates or deletes record then it needs to reflect the same

to the user.

 

Viewrecord.java

package com.elogic.sqliteexample.data;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.elogic.sqliteexample.R;
import com.elogic.sqliteexample.database.DatabaseHelper;

import java.util.ArrayList;

public class ViewRecord extends Activity {

 private ListView listview;
 TextView totalrecords;
 Button b;
 EditText search;

 DatabaseHelper db;
 ListAdapter listadapter;
 public ArrayList<Student> _productlist = new ArrayList<Student>();

 private ArrayList<String> searchquery;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 // TODO Auto-generated method stub
 super.onCreate(savedInstanceState);
 setContentView(R.layout.january_1);


 search=(EditText) findViewById(R.id.search);
 totalrecords = (TextView) findViewById(R.id.totalrecords);
 listview = (ListView) findViewById(R.id.listview);
 searchquery = new ArrayList();
 final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_dropdown, searchquery);
 search.addTextChangedListener(new TextWatcher() {
 @Override
 public void beforeTextChanged(CharSequence s, int start, int count, int after) {

 }

 @Override
 public void onTextChanged(CharSequence s, int start, int before, int count) {
listadapter.getFilter().filter(s.toString());
 }

 @Override
 public void afterTextChanged(Editable s) {

 }
 });

 _productlist.clear();
 searchquery.clear();

 db = new DatabaseHelper(getApplicationContext());
 db.getWritableDatabase();
 ArrayList<Student> product_list = db.getmonth1();

 for (int i = 0; i < product_list.size(); i++) {


 String tidno = product_list.get(i).getIdno();

 System.out.println("tidno>>>>>" + tidno);
 String tname = product_list.get(i).getname();
 String tprice = product_list.get(i).getmark();
 String tdate = product_list.get(i).getdate();
 String tremark = product_list.get(i).getremark();


 searchquery.add(tname);


 Student _Student = new Student();

 _Student.setIdno(tidno);
 _Student.setname(tname);
 _Student.setmark(tprice);
 _Student.setdate(tdate);
 _Student.setremark(tremark);





 _productlist.add(_Student);
 }
 totalrecords.setText("Total Records :-" + _productlist.size());
 listadapter=new ListAdapter(ViewRecord.this,_productlist);
 listview.setAdapter(listadapter);
 db.close();

 }

 @Override
 protected void onResume() {
 // TODO Auto-generated method stub
 super.onResume();
 _productlist.clear();
 searchquery.clear();

 db = new DatabaseHelper(getApplicationContext());
 db.getWritableDatabase();
 ArrayList<Student> product_list = db.getmonth1();

 for (int i = 0; i < product_list.size(); i++) {


 String tidno = product_list.get(i).getIdno();

 System.out.println("tidno>>>>>" + tidno);
 String tname = product_list.get(i).getname();
 String tprice = product_list.get(i).getmark();
 String tdate = product_list.get(i).getdate();
 String tremark = product_list.get(i).getremark();


 searchquery.add(tname);


 Student _Student = new Student();

 _Student.setIdno(tidno);
 _Student.setname(tname);
 _Student.setmark(tprice);
 _Student.setdate(tdate);
 _Student.setremark(tremark);

 _productlist.add(_Student);
 }
 totalrecords.setText("Total Records :-" + _productlist.size());
 listadapter=new ListAdapter(ViewRecord.this,_productlist);
 listview.setAdapter(listadapter);
 db.close();


 }




}

 

Here, I have implemented custom adapter to display records.

 

ListAdapter.java

package com.elogic.sqliteexample.data;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;

import com.elogic.sqliteexample.R;
import com.elogic.sqliteexample.database.DatabaseHelper;

import java.util.ArrayList;

public class ListAdapter extends BaseAdapter implements Filterable {
 LayoutInflater inflater;
 Context con;
 ViewHolder viewHolder;
 ArrayList<Student> filteredlist;
 private Datafilter filter;
 public ArrayList<Student> _productlist = new ArrayList<Student>();

 DatabaseHelper db;

 public ListAdapter(Context context, ArrayList<Student> product_list) {
 // TODO Auto-generated constructor stub
 inflater = LayoutInflater.from(context);
 this.con=context;
 this._productlist=product_list;
 this.filteredlist=product_list;
 db = new DatabaseHelper(con);
 db.getWritableDatabase();
 }

 @Override
 public int getCount() {
 // TODO Auto-generated method stub
 return filteredlist.size();
 }

 @Override
 public Object getItem(int position) {
 // TODO Auto-generated method stub
 return filteredlist.get(position);
 }

 @Override
 public long getItemId(int position) {
 // TODO Auto-generated method stub
 return position;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
 // TODO Auto-generated method stub
 if (convertView == null) {

 convertView = inflater.inflate(R.layout.listview_row, null);
 viewHolder = new ViewHolder();

 viewHolder.txt_pname = (TextView) convertView
 .findViewById(R.id.txtdisplaypname);
 viewHolder.txt_pprice = (TextView) convertView
 .findViewById(R.id.txtdisplaypprice);

 viewHolder.txt_pdate = (TextView) convertView
 .findViewById(R.id.txtdisplaydate);

 viewHolder.txt_premark = (TextView) convertView
 .findViewById(R.id.txtdisplayremark);





 viewHolder.txtidno = (TextView) convertView
 .findViewById(R.id.txtdisplaypid);
 convertView.setTag(viewHolder);

 } else {
 viewHolder = (ViewHolder) convertView.getTag();
 }

 viewHolder.txt_pname.setText(filteredlist.get(position)
 .getname().trim());
 viewHolder.txt_pprice.setText(filteredlist.get(position)
 .getmark().trim());

 viewHolder.txt_pdate.setText(filteredlist.get(position)
 .getdate().trim());
 viewHolder.txt_premark.setText(filteredlist.get(position)
 .getremark().trim());

 viewHolder.txtidno.setText(filteredlist.get(position).getIdno()
 .trim());

 final int temp = position;
 (convertView.findViewById(R.id.btn_update))
 .setOnClickListener(new View.OnClickListener() {

 public void onClick(View arg0) {

 String _productid = String.valueOf(filteredlist
 .get(temp).getIdno());
 String _productname = filteredlist.get(temp)
 .getname();
 String _productprice = _productlist.get(temp)
 .getmark();
 String _productdate = filteredlist.get(temp)
 .getdate();
 String _productremark = filteredlist.get(temp)
 .getremark();

 Intent intent = new Intent(con,
 AddUpdateValues.class);

 Bundle bundle = new Bundle();
 bundle.putString("id", _productid);
 bundle.putString("name", _productname);
 bundle.putString("price", _productprice);
 bundle.putString("date", _productdate);
 bundle.putString("remark", _productremark);
 intent.putExtras(bundle);
 con.startActivity(intent);

 }
 });


 (convertView.findViewById(R.id.btn_delete))
 .setOnClickListener(new View.OnClickListener() {

 public void onClick(View arg0) {

 AlertDialog.Builder alertbox = new AlertDialog.Builder(
 con);
 alertbox.setCancelable(true);
 alertbox.setMessage("Are you sure you want to delete ?");
 alertbox.setPositiveButton("Yes",
 new DialogInterface.OnClickListener() {

 public void onClick(
 DialogInterface arg0, int arg1) {

 Log.i(">>>TEMP>>>", temp + "");
 Log.i(">>>getIdno>>>>>>",
 filteredlist.get(temp)
 .getIdno().trim()
 + "");
 System.out
 .println(">>>getIdno>>>>>>"
 + filteredlist
 .get(temp)
 .getIdno()
 .trim());
 db.removerecord(
 filteredlist.get(temp)
 .getIdno().trim());

 notifyDataSetChanged();

 Toast.makeText(
 con,
 "Record Deleted...",
 Toast.LENGTH_SHORT).show();

 }

 });
 alertbox.setNegativeButton("No",
 new DialogInterface.OnClickListener() {
 public void onClick(
 DialogInterface arg0, int arg1) {

 }
 });
 alertbox.show();
 }
 });
 return convertView;

 }

 @Override
 public Filter getFilter() {
 if (filter == null){
 filter = new Datafilter();
 }
 return filter;
 }
 private class Datafilter extends Filter {

 @Override
 protected FilterResults performFiltering(CharSequence constraint) {


 FilterResults result = new FilterResults();
 if (constraint != null && constraint.toString().length() > 0) {
 ArrayList<Student> filteredItems = new ArrayList<Student>();

 for (int i = 0; i<_productlist.size(); i++) {

 if ((_productlist.get(i).getname().toUpperCase()).contains(constraint.toString().toUpperCase())) {
 filteredItems.add(_productlist.get(i));
//
 }
 }
 result.count = filteredItems.size();
 result.values = filteredItems;
 } else {
 {
 result.values = _productlist;
 result.count = _productlist.size();

 }
 }
 return result;
 }

 @SuppressWarnings("unchecked")
 @Override
 protected void publishResults(CharSequence constraint,
 FilterResults results) {

 filteredlist = (ArrayList<Student>) results.values;
 notifyDataSetChanged();

//
 }
 }

 class ViewHolder {
 TextView txt_pname;
 TextView txt_pprice;
 TextView txt_pdate;
 TextView txt_premark;
 TextView txtidno;

 }

}
//


 

AndroidManifests.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.elogic.sqliteexample">

 <application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:supportsRtl="true"
 android:theme="@style/AppTheme">
 <activity android:name=".data.MainActivity">
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>

 <activity
 android:name=".data.AddRecord"
 android:label="@string/title_activity_add_record" >
 </activity>
 <activity
 android:name=".data.AddUpdateValues"
 android:label="@string/title_activity_add_update_values" >
 </activity>

 <activity
 android:name=".data.ViewRecord"
 android:label="Record" >
 </activity>
 </application>

</manifest>

 

Thank you For watching

For more information

Contact us

E-Mail: elogicsense@gmail.com

Leave a Reply