SQLite Database
Android provides several options to save persistent application data. SQlite database is ideal for saving repeating and structured data . Using Sqlite we can save structured data in a private database.
This is a simple application showing use of Sqlite database in android . This example shows how to perform Insert , select , update and delete operation in SQlite database
This is a Registration app. New user can register by clicking registration button . Registered users are shown in cards below that button . we can update or delete registered users by clicking overflow menu in each card.
1.First we need to create database for our application .
a. Create a contract class .Contract class contains constants that defines names of Tables and columns of our database. Contract class allows us to use same constant across all classes and let us change column name at one place and have it propagate throughout our code.
Our contract class UserDatabaseContract.java
Our contract class UserDatabaseContract.java
package com.androidtuts4u.arun.registartionapp.database; import android.provider.BaseColumns; public final class UserDatabaseContract { private UserDatabaseContract() { } public static class UserDatabase implements BaseColumns { public static final String TABLE_NAME = "user_details"; public static final String COLUMN_NAME_COL1 = "name"; public static final String COLUMN_NAME_COL2 = "address"; public static final String COLUMN_NAME_COL3 = "phone_no"; public static final String COLUMN_NAME_COL4 = "profession"; } }By implementing BaseColumns Our class inherit primary key field called _ID . so we do not need to create separate primary key field.
b.Next we need a SQL Helper class . This class is created by extending SQLiteOpenHelper . This Class is used for creating and maintaining database and tables.
Our SQLHelper class UserDatabaseHelper.java
package com.androidtuts4u.arun.registartionapp.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.androidtuts4u.arun.registartionapp.database.UserDatabaseContract.UserDatabase; public class UserDatabaseHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "UserRegistration.db"; public UserDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_USER_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersio, int newVersion) { db.execSQL(DELETE_USER_TABLE); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } private static final String CREATE_USER_TABLE = "CREATE TABLE " + UserDatabase.TABLE_NAME + "( " + UserDatabase._ID + " INTEGER PRIMARY KEY," + UserDatabase.COLUMN_NAME_COL1 + " text," + UserDatabase.COLUMN_NAME_COL2 + " text," + UserDatabase.COLUMN_NAME_COL3 + " text," + UserDatabase.COLUMN_NAME_COL4 + " text)"; private static final String DELETE_USER_TABLE = "DROP TABLE IF EXISTS " + UserDatabase.TABLE_NAME; }
Database for our application is now completed .
2. Next we need to add dependencies for RecyclerView and CardView in our buil.gradle file .
buil.gradle file
apply plugin: 'com.android.application' android { compileSdkVersion 27 buildToolsVersion "27.0.3" defaultConfig { applicationId "com.androidtuts4u.arun.registartionapp" minSdkVersion 16 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } allprojects { repositories { jcenter() google() } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support.constraint:constraint-layout:1.0.2' testCompile 'junit:junit:4.12' implementation 'com.android.support:appcompat-v7:27.0.2' implementation 'com.android.support:recyclerview-v7:27.0.2' implementation 'com.android.support:cardview-v7:27.0.2' }3.Next we need to create layout for our application. We are using ConstraintLayout in our applicaion. Our application consist of three activities . MainActivity,RegistrationActivity and updateActivity
A. mainActivity has one user Registration button for new user registration and below that we have a RecyclerView for showing registered users .
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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" android:scrollbars="vertical" tools:context="com.androidtuts4u.arun.registartionapp.MainActivity"> <Button android:id="@+id/bt_register" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:backgroundTint="@color/colorAccent" android:text="User Registration" android:textColor="@color/cardview_light_background" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView" style="?android:textAppearanceLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:text="Registered Users" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/bt_register" /> <android.support.v7.widget.RecyclerView android:id="@+id/rv_users" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginBottom="8dp" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:layout_marginTop="8dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView"> </android.support.v7.widget.RecyclerView> </android.support.constraint.ConstraintLayout>B. Our Registration activity consist of Texfields for entering name,address,phone number,profession
registration_actiivty.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/et_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:hint="Name" android:inputType="textPersonName" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/et_address" android:layout_width="368dp" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:hint="Address" android:inputType="textPersonName" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_name" /> <EditText android:id="@+id/et_phone" android:layout_width="368dp" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginStart="8dp" android:hint="phone number" android:inputType="textPersonName" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_address" /> <EditText android:id="@+id/et_pro" android:layout_width="368dp" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:ems="10" android:hint="profession" android:inputType="textPersonName" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_phone" /> <Button android:id="@+id/bt_registration" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:backgroundTint="@color/colorAccent" android:text="Register" android:textColor="@color/cardview_light_background" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_pro" /> </android.support.constraint.ConstraintLayout>C. Next is update Activity , it also contains textFields for updating user details and an update button for updating details.
update_activity.xml file
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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"> <EditText android:id="@+id/et_up_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:hint="Name" android:inputType="textPersonName" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/et_up_address" android:layout_width="368dp" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:hint="Address" android:inputType="textPersonName" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_up_name" /> <EditText android:id="@+id/et_up_phone" android:layout_width="368dp" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginStart="8dp" android:hint="phone number" android:inputType="textPersonName" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_up_address" /> <EditText android:id="@+id/et_up_pro" android:layout_width="368dp" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:ems="10" android:hint="profession" android:inputType="textPersonName" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_up_phone" /> <Button android:id="@+id/bt_update" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:backgroundTint="@color/colorAccent" android:text="Update" android:textColor="@color/cardview_light_background" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_up_pro" /> </android.support.constraint.ConstraintLayout>d.Next is our last layout , we are using recyclerView in our main activity for showing registered users , so we need to create layout for the row in the recyclerview . Our Row is a CardView cointaing TexFields and menu icon for updating
list_item.xml file
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/cv_user" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" > <android.support.constraint.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/tv_name" style="?android:textAppearanceLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginTop="8dp" android:text="Name" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/tv_address" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:layout_marginTop="8dp" android:text="Address" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@+id/tv_name" /> <TextView android:id="@+id/tv_phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:text="TextView" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@+id/tv_address" /> <TextView android:id="@+id/tv_profession" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="8dp" android:text="TextView" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@+id/tv_phone" /> <ImageView android:id="@+id/iv_menu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintRight_toLeftOf="parent" app:srcCompat="@drawable/ic_more_vert_black" /> </android.support.constraint.ConstraintLayout> </android.support.v7.widget.CardView>Layouts for our application is now completed . next we need to write java class.
4.a.first is our MainActivity.java
Mainactivity contains a new user registration button on top for new user registration . Below that we have a recyclerview showing registered users. Details of the registerd users is saved in the database . When application starts we retrieve data from the database and show registered users as list.
package com.androidtuts4u.arun.registartionapp; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import com.androidtuts4u.arun.registartionapp.adapter.UserDetailsAdapter; import com.androidtuts4u.arun.registartionapp.database.UserDatabaseContract.UserDatabase; import com.androidtuts4u.arun.registartionapp.database.UserDatabaseHelper; import com.androidtuts4u.arun.registartionapp.model.UserDetails; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { UserDatabaseHelper dbHelper; private RecyclerView recyclerView; private RecyclerView.Adapter userAdapter; private RecyclerView.LayoutManager layoutManager; Button btnRegister; List<UserDetails> userDetailsList; SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbHelper = new UserDatabaseHelper(this); db = dbHelper.getReadableDatabase(); recyclerView = (RecyclerView) findViewById(R.id.rv_users); btnRegister = (Button) findViewById(R.id.bt_register); btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, RegistrationActivity.class); startActivity(intent); finish(); } }); userDetailsList = new ArrayList<UserDetails>(); userDetailsList.clear(); Cursor c1 = db.query(UserDatabase.TABLE_NAME, null, null, null, null, null, null); if (c1 != null && c1.getCount() != 0) { userDetailsList.clear(); while (c1.moveToNext()) { UserDetails userDetailsItem = new UserDetails(); userDetailsItem.setUserId(c1.getInt(c1.getColumnIndex(UserDatabase._ID))); userDetailsItem.setName(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL1))); userDetailsItem.setAddress(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL2))); userDetailsItem.setMobileNo(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL3))); userDetailsItem.setProfessiion(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL4))); userDetailsList.add(userDetailsItem); } } c1.close(); layoutManager = new LinearLayoutManager(this); userAdapter = new UserDetailsAdapter(userDetailsList); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(userAdapter); } @Override protected void onDestroy() { db.close(); super.onDestroy(); } }We use query() method for reading data from database
Cursor query (String table, // table to query String[] columns, // array of columns to return String selection, // column for where clause String[] selectionArgs, // values for where clause String groupBy, // group the rows String having, // filter by row groups String orderBy // sort order )
We only need to pass the argument we need to the query function, put other arguments as null. In our application we need all data from the user_details table .so we are only passing table name to query() function, other arguments are null .It will select all data from user_details. query() function returns result as Cursor object . we nee to loop though the Cursor object to read data. we use while loop for this.
Cursor c1 = db.query(UserDatabase.TABLE_NAME, null, null, null, null, null, null); if (c1 != null && c1.getCount() != 0) { userDetailsList.clear(); while (c1.moveToNext()) { UserDetails userDetailsItem = new UserDetails(); userDetailsItem.setUserId(c1.getInt(c1.getColumnIndex(UserDatabase._ID))); userDetailsItem.setName(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL1))); userDetailsItem.setAddress(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL2))); userDetailsItem.setMobileNo(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL3))); userDetailsItem.setProfessiion(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL4))); userDetailsList.add(userDetailsItem); } }We are creating an Arraylist(userDetailsList) from the Data retrieved from from the database. then we pass this userDetailsList to our Adapter.
layoutManager = new LinearLayoutManager(this); userAdapter = new UserDetailsAdapter(userDetailsList); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(userAdapter);b. MainActivity.java is completed next we need a custom adapter for our RecyclerView. if you want to know more about RecyclerView and custom Adapter refer my older post
http://androidtuts4u.blogspot.in/2017/09/android-card-view-example.html
Our custom adapter is UserDetailsAdapter.java
package com.androidtuts4u.arun.registartionapp.adapter; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.androidtuts4u.arun.registartionapp.R; import com.androidtuts4u.arun.registartionapp.UpdateActivity; import com.androidtuts4u.arun.registartionapp.database.UserDatabaseContract.UserDatabase; import com.androidtuts4u.arun.registartionapp.database.UserDatabaseHelper; import com.androidtuts4u.arun.registartionapp.model.UserDetails; import java.util.List; public class UserDetailsAdapter extends RecyclerView.Adapter<UserDetailsAdapter.UserViewHolder> { List<UserDetails> userDetailsList; Context context; UserDatabaseHelper dbHelper; SQLiteDatabase db; public UserDetailsAdapter(List<UserDetails> userDetailsList) { this.userDetailsList = userDetailsList; } @Override public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); View iteView = inflater.inflate(R.layout.list_item, parent, false); UserViewHolder viewHolder = new UserViewHolder(iteView); return viewHolder; } @Override public void onBindViewHolder(final UserViewHolder holder, final int position) { UserDetails userDetails = userDetailsList.get(position); holder.tvName.setText(userDetails.getName()); holder.tvAddress.setText(userDetails.getAddress()); holder.tvPhone.setText(userDetails.getMobileNo()); holder.tvProfession.setText(userDetails.getProfessiion()); holder.ivMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final UserDetails userDetails = userDetailsList.get(position); final int userId = userDetails.getUserId(); dbHelper = new UserDatabaseHelper(context); db = dbHelper.getWritableDatabase(); PopupMenu menu = new PopupMenu(context, holder.ivMenu); menu.inflate(R.menu.popup_menu); menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.delete: db.delete(UserDatabase.TABLE_NAME,UserDatabase._ID + " = " + userId,null); notifyItemRangeChanged(position,userDetailsList.size()); userDetailsList.remove(position); notifyItemRemoved(position); db.close(); break; case R.id.update: Intent intent = new Intent(context, UpdateActivity.class); intent.putExtra("USERID", userId); context.startActivity(intent); break; } return false; } }); menu.show(); } }); } @Override public int getItemCount() { return userDetailsList.size(); } public class UserViewHolder extends RecyclerView.ViewHolder { TextView tvName, tvAddress, tvPhone, tvProfession; ImageView ivMenu; public UserViewHolder(View itemView) { super(itemView); tvName = (TextView) itemView.findViewById(R.id.tv_name); tvAddress = (TextView) itemView.findViewById(R.id.tv_address); tvPhone = (TextView) itemView.findViewById(R.id.tv_phone); tvProfession = (TextView) itemView.findViewById(R.id.tv_profession); ivMenu = (ImageView) itemView.findViewById(R.id.iv_menu); } } }popup is shown with update an delete option on clicking the overflow icon in the carview . if you want to know more about creating popup menu refer my previous post
http://androidtuts4u.blogspot.in/2017/09/android-carview-with-popupmenu.html
PopupMenu menu = new PopupMenu(context, holder.ivMenu); menu.inflate(R.menu.popup_menu); menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.delete: db.delete(UserDatabase.TABLE_NAME,UserDatabase._ID + " = " + userId,null); notifyItemRangeChanged(position,userDetailsList.size()); userDetailsList.remove(position); notifyItemRemoved(position); db.close(); break; case R.id.update: Intent intent = new Intent(context, UpdateActivity.class); intent.putExtra("USERID", userId); context.startActivity(intent); break; } return false; } }); menu.show();We are using delete() function for deleting data from database
int delete (String table, String whereClause, String[] whereArgs)we need to pass table name , where clause and where arguments to delete() function. In our application we need to delete row with particular userId . so we need to pass our table name ,_Id and user id of the particular row to be deleted as the argument to our delete() function
db.delete(UserDatabase.TABLE_NAME,UserDatabase._ID + " = " + userId,null); notifyItemRangeChanged(position,userDetailsList.size()); userDetailsList.remove(position); notifyItemRemoved(position); db.close();c. Next is our getter and setter class. we are creating getter an setter function for every column in our database.
UserDetails.java
1.2package com.androidtuts4u.arun.registartionapp.model; public class UserDetails { private String name,address,mobileNo,professiion; int userId; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMobileNo() { return mobileNo; } public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } public String getProfessiion() { return professiion; } public void setProfessiion(String professiion) { this.professiion = professiion; } }d. Next is our RegistrationActivity .when user clicks on new registration button on the main activity , user is directed to registration activity.New user enters details on the textfields and when submit button is clicked data is inserted into our database.
RegistrationActivity .java
package com.androidtuts4u.arun.registartionapp; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.androidtuts4u.arun.registartionapp.database.UserDatabaseContract; import com.androidtuts4u.arun.registartionapp.database.UserDatabaseContract.UserDatabase; import com.androidtuts4u.arun.registartionapp.database.UserDatabaseHelper; public class RegistrationActivity extends AppCompatActivity { UserDatabaseHelper dbHelper; String name, address, phone, profession; SQLiteDatabase db; private EditText etName, etAddress, etPhone, etProfession; private Button btRegister; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.registration_activity); dbHelper = new UserDatabaseHelper(this); db = dbHelper.getWritableDatabase(); etName = (EditText) findViewById(R.id.et_name); etAddress = (EditText) findViewById(R.id.et_address); etPhone = (EditText) findViewById(R.id.et_phone); etProfession = (EditText) findViewById(R.id.et_pro); btRegister = (Button) findViewById(R.id.bt_registration); btRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { name = etName.getText().toString(); address = etAddress.getText().toString(); phone = etPhone.getText().toString(); profession = etProfession.getText().toString(); ContentValues values = new ContentValues(); values.put(UserDatabase.COLUMN_NAME_COL1, name); values.put(UserDatabase.COLUMN_NAME_COL2, address); values.put(UserDatabase.COLUMN_NAME_COL3, phone); values.put(UserDatabase.COLUMN_NAME_COL4, profession); long rowId = db.insert(UserDatabaseContract.UserDatabase.TABLE_NAME, null, values); if (rowId != -1) { Toast.makeText(RegistrationActivity.this, "User regstered succesfully", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RegistrationActivity.this, MainActivity.class); startActivity(intent); finish(); } else { Toast.makeText(RegistrationActivity.this, "Something Went Wrong! ", Toast.LENGTH_SHORT).show(); } } }); } @Override protected void onDestroy() { db.close(); super.onDestroy(); } }we use insert() function for inserting rows in database. it returns a long value showing how many rows inserted.
long insert (String table, String nullColumnHack, ContentValues values)we need to pass table name and values to be inserted to this function . Values are passed as ContentValues. ContentValues is a map , it's key should be column names and values should be column values to be inserted.In our applictation first we neet to create Content values then pass this and table name to the insert() function.
ContentValues values = new ContentValues(); values.put(UserDatabase.COLUMN_NAME_COL1, name); values.put(UserDatabase.COLUMN_NAME_COL2, address); values.put(UserDatabase.COLUMN_NAME_COL3, phone); values.put(UserDatabase.COLUMN_NAME_COL4, profession); long rowId = db.insert(UserDatabaseContract.UserDatabase.TABLE_NAME, null, values); if (rowId != -1) { Toast.makeText(RegistrationActivity.this, "User regstered succesfully", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RegistrationActivity.this, MainActivity.class); startActivity(intent); finish(); } else { Toast.makeText(RegistrationActivity.this, "Something Went Wrong! ", Toast.LENGTH_SHORT).show(); }e. Next is our UpdateActivity. it is used to update the registered user details.
UpdateActivity.java
package com.androidtuts4u.arun.registartionapp; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.androidtuts4u.arun.registartionapp.database.UserDatabaseContract.UserDatabase; import com.androidtuts4u.arun.registartionapp.database.UserDatabaseHelper; import com.androidtuts4u.arun.registartionapp.model.UserDetails; import java.util.ArrayList; import java.util.List; public class UpdateActivity extends AppCompatActivity { UserDatabaseHelper dbHelper; EditText upName, upAddress, upPhone, upProfession; Button btUpdate; List<UserDetails> userDetailsList; String name, address, phone, profession; SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.update_activity); dbHelper = new UserDatabaseHelper(this); db = dbHelper.getWritableDatabase(); upName = (EditText) findViewById(R.id.et_up_name); upAddress = (EditText) findViewById(R.id.et_up_address); upPhone = (EditText) findViewById(R.id.et_up_phone); upProfession = (EditText) findViewById(R.id.et_up_pro); btUpdate = (Button) findViewById(R.id.bt_update); final int rowId = getIntent().getIntExtra("USERID", -1); Cursor c1 = db.query(UserDatabase.TABLE_NAME, null, UserDatabase._ID + " = " + rowId, null, null, null, null); userDetailsList = new ArrayList<UserDetails>(); userDetailsList.clear(); if (c1 != null && c1.getCount() != 0) { while (c1.moveToNext()) { upName.setText(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL1))); upAddress.setText(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL2))); upPhone.setText(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL3))); upProfession.setText(c1.getString(c1.getColumnIndex(UserDatabase.COLUMN_NAME_COL4))); } } btUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { name = upName.getText().toString(); address = upAddress.getText().toString(); phone = upPhone.getText().toString(); profession = upProfession.getText().toString(); ContentValues values = new ContentValues(); values.put(UserDatabase.COLUMN_NAME_COL1, name); values.put(UserDatabase.COLUMN_NAME_COL2, address); values.put(UserDatabase.COLUMN_NAME_COL3, phone); values.put(UserDatabase.COLUMN_NAME_COL4, profession); int updateId = db.update(UserDatabase.TABLE_NAME, values, UserDatabase._ID + " = " + rowId, null); if (updateId != -1) { Toast.makeText(UpdateActivity.this, "User Details Upated succesfully", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(UpdateActivity.this, MainActivity.class); startActivity(intent); finish(); } else { Toast.makeText(UpdateActivity.this, "User Updation Failed", Toast.LENGTH_SHORT).show(); } } }); } @Override protected void onDestroy() { db.close(); super.onDestroy(); } }update() function is used to update rows in database. It returns a integer value showing how many rows upated
int update (String table, ContentValues values, String whereClause, String[] whereArgs)update() function is same as delete() function . we need to pass table name , ContentValues,where clause and where arguments to the update function. ContentValue contains name of the columns to be upated and its new values.In our application first we have to create ContentValues , then pass it to the update() function with table name and where clause.
ContentValues values = new ContentValues(); values.put(UserDatabase.COLUMN_NAME_COL1, name); values.put(UserDatabase.COLUMN_NAME_COL2, address); values.put(UserDatabase.COLUMN_NAME_COL3, phone); values.put(UserDatabase.COLUMN_NAME_COL4, profession); int updateId = db.update(UserDatabase.TABLE_NAME, values, UserDatabase._ID + " = " + rowId, null); if (updateId != -1) { Toast.makeText(UpdateActivity.this, "User Details Upated succesfully", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(UpdateActivity.this, MainActivity.class); startActivity(intent); finish(); } else { Toast.makeText(UpdateActivity.this, "User Updation Failed", Toast.LENGTH_SHORT).show(); }
Source code of this application can be downlaoded from below Google drive link 1.https://drive.google.com/drive/folders/0BySLpWhqmbbdS0dtT1R2TXdBWEE?usp=sharing OR source code can be downloaded from the below Github link 2.https://github.com/arunkfedex/RegistartionApp
Thank you!
ReplyDeleteI borrowed a menu implementation and app styles for my project.