This tutorial is about android SQLite database. Here we will discuss about what is SQLite database, What is Cursor and how to save data in SQLite database.After that we will fetch the data from SQLite database and show the result in ListView.
What is SQLite Database
Android SQLite is a very lightweight database which comes with Android OS.It is an open source which is used to perform database operation in android application. SQLiteOpenHelper class provides the functionality to use the SQLite database, for creating database we have to extend SQLiteOpenHelper class. This class helps us to manage database creation and version management. SQLiteOpenHelper takes care of all the database management activities. Since, SQLiteOpenHelper is an abstract class so we have to implement abstract method of this class given below:
1. public void onCreate(SQLiteDatabase db) { } 2. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete() to create, read, update and delete rows of your table.
Other Interesting Posts CreateCustom Adpter in List view Android Asynctask Example Android Service Example Broadcastreceiver Example Tutorial
Steps to Create SQLite Database
1.Create a class DataBaseHelper which extends SQLiteOpenHelper.
2.Implement the abstract method public void onCreate(SQLiteDatabase db) and public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
public void onCreate(SQLiteDatabase db) :-This method is called first time when database is created. We usually create tables and the initialize here.
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion): This method is run when database is upgraded / changed, like drop tables, add tables etc.
Here is a simplified database code.We need to write our own class to handle database operations such as creation, upgrading, reading and writing. Database operations are defined using the SQLiteOpenHelper:/p>
Writing Variables and SQL query for Creating Table
private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "devglan_database.db"; //data base field name private static final String FULL_NAME = "full_name"; private static final String EMAIL_ADDRESS = "email_address"; private static final String _ADDRESS = "_address"; private static final String PHONE_NUMBER = "phone"; //table name private static final String REG_TABLE = " reg_table"; private static final String _ID = "_id"; public DataBaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mContext = context; } private static final String CREATE_TABLE_TBL_REGISTRATION = "CREATE TABLE" + REG_TABLE + "" + "(" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + FULL_NAME + " TEXT NOT NULL," + EMAIL_ADDRESS + " TEXT NOT NULL," + _ADDRESS + " TEXT NOT NULL,"+ PHONE_NUMBER + " TEXT NOT NULL"+ ")"; @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(CREATE_TABLE_TBL_REGISTRATION); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldversion, int newversion) { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS" + CREATE_TABLE_TBL_REGISTRATION); onCreate(sqLiteDatabase); }
Read, Insert, Update and Delete Operations
Let us write basic operation of database, insert, read, update and delete.
Insert:-First we start with inserting data in database we use ContentValue is a name value pair used to insert or update values into database table.Content values objects will be passed to SQLiteDatabase Objects insert and update method.The SQLiteOpenHelper class provides the getReadableDatabase()
and getWriteableDatabase()
methods to get access to an SQLiteDatabase object either in read or write mode.Following is the example.
public void addRegistrationData(RegistrationDataModel registrationDataModel){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(FULL_NAME,registrationDataModel.getName()); cv.put(EMAIL_ADDRESS,registrationDataModel.getEmail()); cv.put(_ADDRESS,registrationDataModel.getAddress()); cv.put(PHONE_NUMBER,registrationDataModel.getPhone()); // Inserting Row db.insert(REG_TABLE, null, cv); db.close(); // Closing database connection }
ReadNow we will read the values from database using Cursor.
Cursor:A query returns a Cursor object. A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory.
To get the number of elements of the resulting query use the getCount()
method.
To move between individual data rows, you can use the moveToFirst()
and moveToNext()
methods. The isAfterLast()
method allows to check if the end of the query result has been reached.Cursor provides typed get*()
methods, e.g. getLong(columnIndex), getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing.
Cursor also provides the getColumnIndexOrThrow(String)
method which allows to get the column index for a column name of the table.
A Cursor needs to be closed with the close()
method call.
Here we get the result from Table one by one and we storing in a Arraylist.
public ArrayListgetRegistrationData(){ String selectQuery = "SELECT * FROM " + REG_TABLE; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery,null,null); ArrayList dataModelArrayList = new ArrayList (); if(cursor.moveToFirst()){ do { RegistrationDataModel regdm = new RegistrationDataModel(); regdm.setName(cursor.getString(cursor.getColumnIndex(FULL_NAME))); regdm.setEmail(cursor.getString(cursor.getColumnIndex(EMAIL_ADDRESS))); regdm.setAddress(cursor.getString(cursor.getColumnIndex(_ADDRESS))); regdm.setPhone(cursor.getString(cursor.getColumnIndex(PHONE_NUMBER))); regdm.setId(cursor.getString(cursor.getColumnIndex(_ID))); dataModelArrayList.add(regdm); } while (cursor.moveToNext()); } cursor.close(); db.close(); return dataModelArrayList; }
Update:Updating is little similar to Inserting a record in table to update the table we need to create an Object of ContentValues and put the new Values in ContentValues object.
public void updateRegistrationdata(RegistrationDataModel registrationDataModel) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(FULL_NAME, registrationDataModel.getName()); contentValues.put(EMAIL_ADDRESS, registrationDataModel.getEmail()); contentValues.put(_ADDRESS, registrationDataModel.getAddress()); contentValues.put(PHONE_NUMBER, registrationDataModel.getPhone()); db.update(REG_TABLE, contentValues, _ID + " = ?", new String[]{"" + registrationDataModel.getId()}); db.close(); }
delete:-The SQLite DELETE statement allows you to delete one row, multiple rows, and all rows in a table.
public void deleteRegdata() { SQLiteDatabase db = this.getReadableDatabase(); db.delete(REG_TABLE, null, null); db.close(); }
Here we have written how to insert,Read, update and delete.Now we will show how to interact with user interface.First we have created a Registration form in Mainactivity from where we can insert the result in database.
Creating Database Helper Class
Following is the complete database class.
DataBaseHelper.javapackage com.devglan.sqlitedatabase.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.devglan.sqlitedatabase.datamodel.RegistrationDataModel; import java.util.ArrayList; /** * Created by sanjeevksaroj on 4/4/17. */ public class DataBaseHelper extends SQLiteOpenHelper { Context mContext; //data base version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "devglan_database.db"; //data base field name private static final String FULL_NAME = "full_name"; private static final String EMAIL_ADDRESS = "email_address"; private static final String _ADDRESS = "_address"; private static final String PHONE_NUMBER = "phone"; //table name private static final String REG_TABLE = " reg_table"; private static final String _ID = "_id"; public DataBaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mContext = context; } private static final String CREATE_TABLE_TBL_REGISTRATION = "CREATE TABLE" + REG_TABLE + "" + "(" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + FULL_NAME + " TEXT NOT NULL," + EMAIL_ADDRESS + " TEXT NOT NULL," + _ADDRESS + " TEXT NOT NULL," + PHONE_NUMBER + " TEXT NOT NULL"+ ")"; @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(CREATE_TABLE_TBL_REGISTRATION); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldversion, int newversion) { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS" + CREATE_TABLE_TBL_REGISTRATION); onCreate(sqLiteDatabase); } public void addRegistrationData(RegistrationDataModel registrationDataModel){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(FULL_NAME,registrationDataModel.getName()); cv.put(EMAIL_ADDRESS,registrationDataModel.getEmail()); cv.put(_ADDRESS,registrationDataModel.getAddress()); cv.put(PHONE_NUMBER,registrationDataModel.getPhone()); // Inserting Row db.insert(REG_TABLE, null, cv); db.close(); // Closing database connection } public ArrayListgetRegistrationData(){ String selectQuery = "SELECT * FROM " + REG_TABLE; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery,null,null); ArrayList dataModelArrayList = new ArrayList (); if(cursor.moveToFirst()){ do { RegistrationDataModel regdm = new RegistrationDataModel(); regdm.setName(cursor.getString(cursor.getColumnIndex(FULL_NAME))); regdm.setEmail(cursor.getString(cursor.getColumnIndex(EMAIL_ADDRESS))); regdm.setAddress(cursor.getString(cursor.getColumnIndex(_ADDRESS))); regdm.setPhone(cursor.getString(cursor.getColumnIndex(PHONE_NUMBER))); regdm.setId(cursor.getString(cursor.getColumnIndex(_ID))); dataModelArrayList.add(regdm); } while (cursor.moveToNext()); } cursor.close(); db.close(); return dataModelArrayList; } public void updateRegistrationdata(RegistrationDataModel registrationDataModel) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(FULL_NAME, registrationDataModel.getName()); contentValues.put(EMAIL_ADDRESS, registrationDataModel.getEmail()); contentValues.put(_ADDRESS, registrationDataModel.getAddress()); contentValues.put(PHONE_NUMBER, registrationDataModel.getPhone()); db.update(REG_TABLE, contentValues, _ID + " = ?", new String[]{"" + registrationDataModel.getId()}); db.close(); } public void deleteRegdata() { SQLiteDatabase db = this.getReadableDatabase(); db.delete(REG_TABLE, null, null); db.close(); } }
Creating Datamodel Class
public class RegistrationDataModel { private String name = ""; private String email = ""; private String phone = ""; private String address = ""; private String id = ""; // getter setter goes here. }
Creating MainActivity Class
MainActivity.javapackage com.devglan.sqlitedatabase; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.devglan.sqlitedatabase.database.DataBaseHelper; import com.devglan.sqlitedatabase.datamodel.RegistrationDataModel; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { TextView tv_name,tv_email,tv_address,tv_phone,tv_submit,tv_show,tv_regid; EditText et_name,et_email,et_address,et_phone,et_regid; DataBaseHelper dataBaseHelper; ArrayListregistrationDataModelArrayList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dataBaseHelper = new DataBaseHelper(this); initView(); } public void initView(){ tv_name= (TextView) findViewById(R.id.tv_name); tv_email= (TextView) findViewById(R.id.tv_email); tv_address= (TextView) findViewById(R.id.tv_address); tv_phone= (TextView) findViewById(R.id.tv_phone); tv_regid= (TextView) findViewById(R.id.tv_regid); tv_submit= (TextView) findViewById(R.id.tv_submit); et_name= (EditText) findViewById(R.id.et_name); et_email= (EditText) findViewById(R.id.et_email); et_address= (EditText) findViewById(R.id.et_address); et_phone= (EditText) findViewById(R.id.et_phone); et_regid= (EditText) findViewById(R.id.et_regid); tv_show= (TextView) findViewById(R.id.tv_show); tv_submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // save data in data base if(validateField()){ String name=et_name.getText().toString(); String address=et_address.getText().toString(); String phone=et_phone.getText().toString(); String email=et_email.getText().toString(); RegistrationDataModel regDmodel = new RegistrationDataModel(); regDmodel.setName(name); regDmodel.setEmail(email); regDmodel.setAddress(address); regDmodel.setPhone(phone); dataBaseHelper.addRegistrationData(regDmodel); Toast.makeText(MainActivity.this,"Data Inserted successfully",Toast.LENGTH_SHORT).show(); } } }); tv_show.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { registrationDataModelArrayList= dataBaseHelper.getRegistrationData(); if(registrationDataModelArrayList.size()>0){ Intent intent = new Intent(MainActivity.this,ListActivity.class); startActivity(intent); }else { Toast.makeText(MainActivity.this,"No data found in table",Toast.LENGTH_SHORT).show(); } } }); } public boolean validateField(){ boolean isValidationSuccessful = true; if(et_name.getText().toString().trim().equalsIgnoreCase("")){ Toast.makeText(MainActivity.this,"Name can't be empty",Toast.LENGTH_SHORT).show(); isValidationSuccessful = false; } else if(et_email.getText().toString().trim().equalsIgnoreCase("") ){ Toast.makeText(MainActivity.this,"Email can't be empty", Toast.LENGTH_SHORT).show(); isValidationSuccessful = false; } else if(et_address.getText().toString().trim().equalsIgnoreCase("")){ Toast.makeText(MainActivity.this,"Address can't be empty", Toast.LENGTH_SHORT).show(); isValidationSuccessful = false; }else if(et_phone.getText().toString().trim().equalsIgnoreCase("")){ Toast.makeText(MainActivity.this,"Phone can't be empty",Toast.LENGTH_SHORT).show(); isValidationSuccessful = false; }else if(!isValidEmail(et_email.getText().toString())){ Toast.makeText(MainActivity.this,"Email is not valid",Toast.LENGTH_SHORT).show(); isValidationSuccessful = false; } return isValidationSuccessful; } public boolean isValidEmail(CharSequence target) { if (target == null) { return false; } else { return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } } }
Creating MainActivity.xml
activity_main.xml<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="com.devglan.sqlitedatabase.MainActivity" android:layout_marginRight="20dp" android:layout_marginLeft="20dp"> <TextView android:id="@+id/tv_regid" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Registration" android:textSize="20sp" android:textColor="@color/colorAccent" android:layout_marginTop="20dp" android:visibility="gone"/> <EditText android:id="@+id/et_regid" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="please enter Registration" android:textSize="20sp" android:layout_below="@+id/tv_regid" android:background="@color/transparent" android:inputType="number" android:layout_marginTop="10dp" android:maxLines="1" android:singleLine="true" android:visibility="gone"/> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:textSize="20sp" android:textColor="@color/colorAccent" android:layout_below="@+id/et_regid"/> <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="please enter name" android:textSize="20sp" android:layout_below="@+id/tv_name" android:background="@color/transparent" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" android:inputType="textCapWords" android:maxLines="1" android:singleLine="true"/> <TextView android:id="@+id/tv_email" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Email" android:textSize="20sp" android:layout_below="@+id/et_name" android:textColor="@color/colorAccent" /> <EditText android:id="@+id/et_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="please enter email" android:textSize="20sp" android:layout_below="@+id/tv_email" android:background="@color/transparent" android:layout_marginTop="10dp" android:inputType="textEmailAddress" android:maxLines="1" android:singleLine="true"/> <TextView android:id="@+id/tv_address" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Address" android:textSize="20sp" android:layout_below="@+id/et_email" android:textColor="@color/colorAccent" android:layout_marginTop="20dp"/> <EditText android:id="@+id/et_address" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="please enter address" android:textSize="20sp" android:layout_below="@+id/tv_address" android:background="@color/transparent" android:inputType="textCapWords" android:layout_marginTop="10dp" android:maxLines="1" android:singleLine="true"/> <TextView android:id="@+id/tv_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Phone" android:textSize="20sp" android:layout_below="@+id/et_address" android:textColor="@color/colorAccent" android:layout_marginTop="20dp"/> <EditText android:id="@+id/et_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="please enter phone" android:textSize="20sp" android:layout_below="@+id/tv_phone" android:background="@color/transparent" android:inputType="number" android:layout_marginTop="10dp" android:maxLines="1" android:singleLine="true"/> <TextView android:id="@+id/tv_submit" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Submit" android:textSize="20sp" android:layout_below="@+id/et_phone" android:textColor="@color/colorAccent" android:layout_marginTop="20dp" android:gravity="center" android:padding="10dp" android:background="@color/colorPrimary"/> <TextView android:id="@+id/tv_show" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Show" android:textSize="20sp" android:layout_below="@+id/tv_submit" android:textColor="@color/colorAccent" android:layout_marginTop="20dp" android:gravity="center" android:padding="10dp" android:background="@color/colorPrimary"/> </RelativeLayout>
Creating ListActivity Class
In this class we will get data from database and we are showing the result in a listview.
ListActivity.java:package com.devglan.sqlitedatabase; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.devglan.sqlitedatabase.adapter.ListActivityAdapter; import com.devglan.sqlitedatabase.database.DataBaseHelper; import com.devglan.sqlitedatabase.datamodel.RegistrationDataModel; import java.util.ArrayList; public class ListActivity extends AppCompatActivity { ListView show_list; DataBaseHelper dataBaseHelper; ArrayListactivity_list.xml:registrationDataModelArrayList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); dataBaseHelper = new DataBaseHelper(this); registrationDataModelArrayList= dataBaseHelper.getRegistrationData(); show_list= (ListView) findViewById(R.id.show_list); ListActivityAdapter listActivityAdapter = new ListActivityAdapter(this,registrationDataModelArrayList); show_list.setAdapter(listActivityAdapter); show_list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> adapterView, View view, int i, long l) { Intent intent = new Intent(ListActivity.this,UpdateActivity.class); intent.putExtra("id",registrationDataModelArrayList.get(i).getId()); intent.putExtra("name",registrationDataModelArrayList.get(i).getName()); intent.putExtra("email",registrationDataModelArrayList.get(i).getEmail()); intent.putExtra("address",registrationDataModelArrayList.get(i).getAddress()); intent.putExtra("phone",registrationDataModelArrayList.get(i).getPhone()); startActivity(intent); finish(); } }); } }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="com.devglan.sqlitedatabase.ListActivity"> <ListView android:id="@+id/show_list" android:layout_width="match_parent" android:layout_height="match_parent"></ListView> </RelativeLayout>ListActivityAdapter.java:
package com.devglan.sqlitedatabase.adapter; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.devglan.sqlitedatabase.R; import com.devglan.sqlitedatabase.datamodel.RegistrationDataModel; import java.util.ArrayList; /** * Created by sanjeevksaroj on 5/4/17. */ public class ListActivityAdapter extends BaseAdapter { Activity activity; ArrayListxml for showing the individual result in adapter class. list_rowcell:arrayList = new ArrayList (); LayoutInflater layoutInflater = null; public ListActivityAdapter(Activity activity,ArrayList dataModelArrayList){ this.activity=activity; this.arrayList=dataModelArrayList; layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return arrayList.size(); } @Override public Object getItem(int i) { return arrayList.get(i); } @Override public long getItemId(int i) { return i; } public class ViewHolder{ TextView tv_name,tv_email,tv_address,tv_phone,tv_regid; } ViewHolder viewHolder = null; @Override public View getView(int position, View view, ViewGroup viewGroup) { View vi = view; final int pos = position; if(vi == null){ // create viewholder object for list_rowcell View. viewHolder = new ViewHolder(); // inflate list_rowcell for each row vi = layoutInflater.inflate(R.layout.list_rowcell, null); viewHolder.tv_name = (TextView) vi.findViewById(R.id.tv_name); viewHolder.tv_email = (TextView) vi.findViewById(R.id.tv_email); viewHolder.tv_address = (TextView) vi.findViewById(R.id.tv_address); viewHolder.tv_phone = (TextView) vi.findViewById(R.id.tv_phone); viewHolder.tv_regid = (TextView) vi.findViewById(R.id.tv_regid); vi.setTag(viewHolder); }else { /* We recycle a View that already exists */ viewHolder= (ViewHolder) vi.getTag(); } viewHolder.tv_name.setText(arrayList.get(pos).getName()); viewHolder.tv_phone.setText(arrayList.get(pos).getPhone()); viewHolder.tv_address.setText(arrayList.get(pos).getAddress()); viewHolder.tv_email.setText(arrayList.get(pos).getEmail()); viewHolder.tv_regid.setText(arrayList.get(pos).getId()); return vi; } }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/tv_regid" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="DADSDSDSDS" android:gravity="center" android:textColor="@color/blue" android:padding="5dp" android:textStyle="bold"/> <TextView android:id="@+id/tv_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="DADSDcSDSDS" android:textColor="@color/blue" android:padding="5dp" android:gravity="center" android:layout_below="@+id/tv_regid" android:textStyle="bold" /> <TextView android:id="@+id/tv_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="DADSDSDSDcS" android:textColor="@color/blue" android:padding="5dp" android:layout_below="@+id/tv_name" android:gravity="center" android:textStyle="bold" /> <TextView android:id="@+id/tv_address" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="DADSDSDSDS" android:textColor="@color/blue" android:padding="5dp" android:layout_below="@+id/tv_email" android:gravity="center" android:textStyle="bold" /> <TextView android:id="@+id/tv_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="DADSDSDSDS" android:gravity="center" android:textColor="@color/blue" android:padding="5dp" android:layout_below="@+id/tv_address" android:textStyle="bold" /> </RelativeLayout> </RelativeLayout>
For updating the table and deleting table data we have created a seprate Activity i.e UpdateActivity.java.
UpdateActivity.javapackage com.devglan.sqlitedatabase; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.devglan.sqlitedatabase.database.DataBaseHelper; import com.devglan.sqlitedatabase.datamodel.RegistrationDataModel; import java.util.ArrayList; public class UpdateActivity extends AppCompatActivity { TextView tv_name,tv_email,tv_address,tv_phone,tv_update,tv_regid,tv_delete; EditText et_name,et_email,et_address,et_phone,et_regid; DataBaseHelper dataBaseHelper; String registration=""; String name=""; String email=""; String address=""; String phone=""; ArrayListregistrationDataModelArrayList = new ArrayList<>(); RegistrationDataModel regDmodel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update); dataBaseHelper = new DataBaseHelper(this); registration = getIntent().getExtras().getString( "id"); name=getIntent().getExtras().getString("name"); email=getIntent().getExtras().getString("email"); address=getIntent().getExtras().getString("address"); phone=getIntent().getExtras().getString("phone"); initView(); } public void initView(){ tv_name= (TextView) findViewById(R.id.tv_name); tv_email= (TextView) findViewById(R.id.tv_email); tv_address= (TextView) findViewById(R.id.tv_address); tv_phone= (TextView) findViewById(R.id.tv_phone); tv_regid= (TextView) findViewById(R.id.tv_regid); tv_update= (TextView) findViewById(R.id.tv_update); tv_delete= (TextView) findViewById(R.id.tv_delete); et_name= (EditText) findViewById(R.id.et_name); et_email= (EditText) findViewById(R.id.et_email); et_address= (EditText) findViewById(R.id.et_address); et_phone= (EditText) findViewById(R.id.et_phone); et_regid= (EditText) findViewById(R.id.et_regid); et_regid.setText(registration); et_name.setText(name); et_email.setText(email); et_address.setText(address); et_phone.setText(phone); tv_update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // save data in data base if(validateField()){ String name = et_name.getText().toString(); String address=et_address.getText().toString(); String phone=et_phone.getText().toString(); String email=et_email.getText().toString(); String regid=et_regid.getText().toString(); regDmodel= new RegistrationDataModel(); regDmodel.setName(name); regDmodel.setEmail(email); regDmodel.setAddress(address); regDmodel.setPhone(phone); regDmodel.setId(regid); dataBaseHelper.updateRegistrationdata(regDmodel); registrationDataModelArrayList= dataBaseHelper.getRegistrationData(); if(registrationDataModelArrayList.size() > 0){ Intent intent = new Intent(UpdateActivity.this,ListActivity.class); startActivity(intent); finish(); }else { Toast.makeText(UpdateActivity.this,"No Record to Update",Toast.LENGTH_SHORT).show(); } } } }); tv_delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { registrationDataModelArrayList= dataBaseHelper.getRegistrationData(); if(registrationDataModelArrayList.size() > 0){ dataBaseHelper.deleteRegdata(); }else { Toast.makeText(UpdateActivity.this,"Registration data deleted",Toast.LENGTH_SHORT).show(); } } }); } public boolean validateField(){ boolean isValidationSuccessful = true; if(et_name.getText().toString().trim().equalsIgnoreCase("")){ Toast.makeText(UpdateActivity.this,"Name can't be empty",Toast.LENGTH_SHORT).show(); isValidationSuccessful = false; } else if(et_email.getText().toString().trim().equalsIgnoreCase("") ){ Toast.makeText(UpdateActivity.this,"Email can't be empty", Toast.LENGTH_SHORT).show(); isValidationSuccessful = false; } else if(et_address.getText().toString().trim().equalsIgnoreCase("")){ Toast.makeText(UpdateActivity.this,"Address can't be empty",Toast.LENGTH_SHORT).show(); isValidationSuccessful = false; }else if(et_phone.getText().toString().trim().equalsIgnoreCase("")){ Toast.makeText(UpdateActivity.this,"Phone can't be empty",Toast.LENGTH_SHORT).show(); isValidationSuccessful = false; }else if(!isValidEmail(et_email.getText().toString())){ Toast.makeText(UpdateActivity.this,"Email is not valid",Toast.LENGTH_SHORT).show(); isValidationSuccessful = false; }else if (et_regid.getText().toString().trim().equalsIgnoreCase("")){ Toast.makeText(UpdateActivity.this,"Registration id can't be empty",Toast.LENGTH_SHORT).show(); isValidationSuccessful = false; } return isValidationSuccessful; } public boolean isValidEmail(CharSequence target) { if (target == null) { return false; } else { return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } } }
User interface for UpdateActivity Class
activity_update.xml<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="com.devglan.sqlitedatabase.MainActivity" android:layout_marginRight="20dp" android:layout_marginLeft="20dp"> <TextView android:id="@+id/tv_regid" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Registration" android:textSize="20sp" android:textColor="@color/colorAccent" android:layout_marginTop="20dp" /> <EditText android:id="@+id/et_regid" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="please enter Registration" android:textSize="20sp" android:layout_below="@+id/tv_regid" android:background="@color/transparent" android:inputType="number" android:layout_marginTop="10dp" android:maxLines="1" android:singleLine="true" android:editable="false" android:clickable="false" android:focusable="false" /> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:textSize="20sp" android:textColor="@color/colorAccent" android:layout_below="@+id/et_regid" /> <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="please enter name" android:textSize="20sp" android:layout_below="@+id/tv_name" android:background="@color/transparent" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" android:inputType="textCapWords" android:maxLines="1" android:singleLine="true"/> <TextView android:id="@+id/tv_email" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Email" android:textSize="20sp" android:layout_below="@+id/et_name" android:textColor="@color/colorAccent" /> <EditText android:id="@+id/et_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="please enter email" android:textSize="20sp" android:layout_below="@+id/tv_email" android:background="@color/transparent" android:layout_marginTop="10dp" android:inputType="textEmailAddress" android:maxLines="1" android:singleLine="true"/> <TextView android:id="@+id/tv_address" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Address" android:textSize="20sp" android:layout_below="@+id/et_email" android:textColor="@color/colorAccent" android:layout_marginTop="20dp" /> <EditText android:id="@+id/et_address" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="please enter address" android:textSize="20sp" android:layout_below="@+id/tv_address" android:background="@color/transparent" android:inputType="textCapWords" android:layout_marginTop="10dp" android:maxLines="1" android:singleLine="true"/> <TextView android:id="@+id/tv_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Phone" android:textSize="20sp" android:layout_below="@+id/et_address" android:textColor="@color/colorAccent" android:layout_marginTop="20dp" /> <EditText android:id="@+id/et_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="please enter phone" android:textSize="20sp" android:layout_below="@+id/tv_phone" android:background="@color/transparent" android:inputType="number" android:layout_marginTop="10dp" android:maxLines="1" android:singleLine="true"/> <TextView android:id="@+id/tv_update" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Update" android:textSize="20sp" android:layout_below="@+id/et_phone" android:textColor="@color/colorAccent" android:layout_marginTop="20dp" android:gravity="center" android:padding="10dp" android:background="@color/colorPrimary" /> <TextView android:id="@+id/tv_delete" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Delete Record" android:textSize="20sp" android:layout_below="@+id/tv_update" android:textColor="@color/colorAccent" android:layout_marginTop="20dp" android:gravity="center" android:padding="10dp" android:background="@color/colorPrimary" /> </RelativeLayout>
And finally following is the AndroidManifest.xml
AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.devglan.sqlitedatabase"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ListActivity" android:label="@string/title_activity_list" android:theme="@style/AppTheme.NoActionBar" /> <activity android:name=".UpdateActivity" android:label="@string/title_activity_update" android:theme="@style/AppTheme.NoActionBar"></activity> </application> </manifest>
Conclusion
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.