SQLite Database Tutorial In Android Posted on J uly 9, 2018 by Bhadresh SQLite Database in Android used to store persistent data. If you want to store some data into local storage then SQLite Database is the most common storage option. It is lightweight database that comes with Android OS. In Android There are others data storage options also available Like Shared Preference to store small amount of data in form of Key / Value pair. SQLite Database File System Here we are going to learn how to use SQLite Database in Android application. SQLite is an open source SQL database which store the data into text le on android device. SQLite database in android also support relational database features. In order to access SQLite Database you don’t need to establish any kind of connections like J DBC, ODBC. 1. Overview In this tutorial we are going to create Student App to learn all the operation related the SQLite Database. The app is very simple and which allow us to insert, update, delete and view student data. We will use 2 screen to perform all this operations. In rst screen we fetch full list of student from the student table while using second screen update or add new student record. Following is the Student app screen shot.
Now let’s start by creating new project in Android Studio. 2. Create / Setup Project 1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from the templates. 2. Open build.gradle under app directory and add CardView library. CardView is used to display Student List inside the Card. 3. Add following code into colors.xml and strings.xml les. colors.xml 1 2 3 4 5 6 7 8 dependencies { //... implementation 'com.android.support:cardview-v7:27.1.1' //... } 1 2 3 4 5 6 7 8 9 10 <?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> <color name="mainText">#212121</color> <color name="subText">#737373</color> <color name="view">#c0c0c0</color> <color name="colorWhite">#ffffff</color> </resources> colors.xml
strings.xml 4. Create following packages named adapter, db, model and ui. The following is the nal project structure and les are required. 3. Create SQLite Helper Classes 5. In this tutorial we have taken student example to perform all operation. So rst we need to create one model class named StudentInfo.java under model package. StudentInfo.java contain student information like id, name, grade and result. Further we will used this class to store and retrieve student information from the SQLite database. 1 2 3 4 5 6 7 8 9 10 <resources> <string name="app_name">Student Management</string> <string name="strAddNewStudent">Add New Student</string> <string name="strUpdateStudent">Update Student</string> <string name="strDelete">Delete</string> <string name="strStudentName">Enter Student Name</string> <string name="strStudentResult">Enter Pass/Fail</string> <string name="strStudentGrade">Enter Grade</string> <string name="strSave">Save</string> </resources> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public class StudentInfo { int studentId; String studentName, studentResult, studentGrade; public StudentInfo() { } public StudentInfo(int studentId) { this.studentId = studentId; } public StudentInfo(String studentName, String studentResult, String studentGrade) { this.studentName = studentName; this.studentResult = studentResult; this.studentGrade = studentGrade; } public StudentInfo(int studentId, String studentName, String studentResult, String studentGrade) { this.studentId = studentId; this.studentName = studentName; this.studentResult = studentResult; this.studentGrade = studentGrade; } public int getStudentId() { return studentId; strings.xml StudentInfo.java
6. Now we need to create a class that extends from SQLiteOpenHelper. So create DBHelper.java under db package. DBHelper.java perform all the database operations like Create, Update, Delete and Read. Before the proceed let’s understand use of all the methods and table structure of the StudentInfo. onCreate() method will be called only once when application launch rst time in android phone. So from this method we will execute sql statement to create Student table. onUpgrade() method will be called when update the application. You need to change the DB_VERSION in order to execute this methods. The StudentInfo table needs four column : _id, name, result and grade. Column _id is declared as Primary Key and Auto Increment which means it is unique key to identify the Students. name contains student name, result is ether pass or fail, grade contains student grade. So let add the following code into DBHelper Class. 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 } public void setStudentId(int studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentResult() { return studentResult; } public void setStudentResult(String studentResult) { this.studentResult = studentResult; } public String getStudentGrade() { return studentGrade; } public void setStudentGrade(String studentGrade) { this.studentGrade = studentGrade; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 public class DBHelper extends SQLiteOpenHelper{ // Database Name static final String DATABASE = "student.db"; // Database Version static final int DB_VERSION = 1; // Table Name static final String TABLE = "StudentInfo"; // Table Field Name static final String S_ID = "_id"; static final String S_NAME = "name"; static final String S_RESULT = "result"; static final String S_GRADE = "grade"; // Override constructor public DBHelper(Context context) { super(context, DATABASE, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // Create StudentInfo table using SQL query db.execSQL("CREATE TABLE " + TABLE + " ( " + S_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + S_NAME + " text, " + S_RESULT + " text, " + S_GRADE + " text )"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { DBHelper.java
7. Now we need to implement four methods to perform CRUD [Create, Read, Update, Delete] operations with student data. Let’s have look of each methods. 7.1 Insert Student Data Inserting data requires writable instance of the SQLiteDatabase So Create instance using getWritableDatabase(). ContentValues() is used to add database values in respective column. So setup all the value with respective column in ContentValues(), Skip _id because it’s auto inserted. Close the database connection after inserting is done. 7.2 Update Student Data. Updating data also requiring writable access of the SQLiteDatabase. Student data will be updated using _id column. 7.3 Delete Student Data. To delete student data we also required to declare SQLiteDatabase instance with writable access. The following methods will be Delete speci ed student record from the database using _id 7.4 Fetch Student Data To read data from the database table requires SQLiteDatabase instance as a read access. For that we can de ne SQLiteDatabase instance using getReadableDatabase(). Following method will fetch all students data from the database table. 34 35 36 37 38 39 40 // Drop old version table db.execSQL("Drop table " + TABLE); // Create New Version table onCreate(db); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 public void addStudentDetails(StudentInfo studInfo) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(S_NAME, studInfo.getStudentName()); values.put(S_RESULT, studInfo.getStudentResult()); values.put(S_GRADE, studInfo.getStudentGrade()); // Inserting Row db.insert(TABLE, null, values); db.close(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 public int updateStudentDetails(StudentInfo studInfo) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(S_NAME, studInfo.getStudentName()); values.put(S_RESULT, studInfo.getStudentResult()); values.put(S_GRADE, studInfo.getStudentGrade()); // updating row return db.update(TABLE, values, S_ID + " = ?", new String[]{String.valueOf(studInfo.getStudentId())}); } 1 2 3 4 5 6 7 8 public void deleteStudentDetails(StudentInfo studentInfo) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE, S_ID + " = ?", new String[]{String.valueOf(studentInfo.getStudentId())}); db.close(); } 1 public List<StudentInfo> getStudentDetails() { addStudentDetails updateStudentDetails deleteStudentDetails getStudentDetails
So add all above methods into DBHelper.java class, The nal code of the DBHelper.java class looks like this. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 List<StudentInfo> StudentList = new ArrayList<>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { StudentInfo studentInfo = new StudentInfo(); studentInfo.setStudentId(cursor.getInt(0)); studentInfo.setStudentName(cursor.getString(1)); studentInfo.setStudentResult(cursor.getString(2)); studentInfo.setStudentGrade(cursor.getString(3)); // Adding student information to list StudentList.add(studentInfo); } while (cursor.moveToNext()); } cursor.close(); return StudentList; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 package dwi.db.operations.student.management.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; import dwi.db.operations.student.management.model.StudentInfo; public class DBHelper extends SQLiteOpenHelper{ // Static Final Variable database meta information static final String DATABASE = "student.db"; static final int DB_VERSION = 1; static final String TABLE = "StudentInfo"; static final String S_ID = "_id"; static final String S_NAME = "name"; static final String S_RESULT = "result"; static final String S_GRADE = "grade"; // Override constructor public DBHelper(Context context) { super(context, DATABASE, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // Create StudentInfo table using SQL query db.execSQL("CREATE TABLE " + TABLE + " ( " + S_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + S_NAME + " text, " + S_RESULT + " text, " + S_GRADE + " text )"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop old version table db.execSQL("Drop table " + TABLE); // Create New Version table onCreate(db); } // Adding new detail public void addStudentDetails(StudentInfo studInfo) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(S_NAME, studInfo.getStudentName()); values.put(S_RESULT, studInfo.getStudentResult()); values.put(S_GRADE, studInfo.getStudentGrade()); // Inserting Row db.insert(TABLE, null, values); db.close(); // Closing database connection } // Updating details public int updateStudentDetails(StudentInfo studInfo) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); DBHelper.java
4. Create List Adapter 8. Create new layout les under layout folder named student_list_row.xml. This layout le holds single items in list. 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 values.put(S_NAME, studInfo.getStudentName()); values.put(S_RESULT, studInfo.getStudentResult()); values.put(S_GRADE, studInfo.getStudentGrade()); // updating row return db.update(TABLE, values, S_ID + " = ?", new String[]{String.valueOf(studInfo.getStudentId())}); } // Deleting single recoed public void deleteStudentDetails(StudentInfo studentInfo) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE, S_ID + " = ?", new String[]{String.valueOf(studentInfo.getStudentId())}); db.close(); } // Get all student information public List<StudentInfo> getStudentDetails() { List<StudentInfo> StudentList = new ArrayList<>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { StudentInfo studentInfo = new StudentInfo(); studentInfo.setStudentId(cursor.getInt(0)); studentInfo.setStudentName(cursor.getString(1)); studentInfo.setStudentResult(cursor.getString(2)); studentInfo.setStudentGrade(cursor.getString(3)); // Adding student information to list StudentList.add(studentInfo); } while (cursor.moveToNext()); } cursor.close(); return StudentList; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <android.support.v7.widget.CardView android:id="@+id/card_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/_15sdp" android:layout_marginLeft="@dimen/_5sdp" android:layout_marginRight="@dimen/_5sdp" app:cardBackgroundColor="#FFFFFF" card_view:cardCornerRadius="2dp" card_view:contentPadding="10dp"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_weight="0.5" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/txtName" android:hint="Name" android:layout_weight="6" android:textSize="15dp" android:textColor="#000" android:layout_gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" /> <TextView android:id="@+id/txtStatus" android:hint="Status" android:layout_weight="6" android:textSize="15dp" android:textColor="#000" android:layout_gravity="center" android:layout_width="match_parent" student_list_row.xml
9. Now create the new class named StudentListAdapter.java under adapter package. This is the Student List adapter and it will show you all the student records from the database. From the list you can Delete or Update particular student data by tapping on Delete or Update button. 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 android:layout_height="wrap_content" android:padding="5dp" /> <TextView android:id="@+id/txtGrade" android:hint="Grade" android:layout_weight="6" android:textSize="15dp" android:textColor="#000" android:layout_gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" /> </LinearLayout> <LinearLayout android:layout_weight="1.9" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imgEdit" android:layout_weight="2" android:src="@drawable/ic_edit" android:layout_width="@dimen/_20sdp" android:layout_height="@dimen/_20sdp" android:layout_gravity="center" /> <ImageView android:id="@+id/imgDelete" android:layout_weight="2" android:src="@drawable/ic_delete" android:layout_width="@dimen/_20sdp" android:layout_height="@dimen/_20sdp" android:layout_gravity="center" /> </LinearLayout> </LinearLayout> </android.support.v7.widget.CardView> </LinearLayout> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 public class StudentListAdapter extends ArrayAdapter<StudentInfo> { // Context Objects Context context; MainActivity display_data; // Primitive Variables public List<StudentInfo> productList; public static LayoutInflater inflater = null; // DB Objects DBHelper db; public StudentListAdapter(@NonNull Context context, int resource, List<StudentInfo> productList) { super(context, resource, productList); this.context = context; this.productList = productList; db = new DBHelper(context); display_data = (MainActivity) this.context; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public StudentInfo getItem(int position) { return productList.get(position); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { ViewProHolder holder; if (convertView == null) { View view = inflater.inflate(R.layout.student_list_row, null); holder = ViewProHolder.create((LinearLayout) view); view.setTag(holder); } else { holder = (ViewProHolder) convertView.getTag(); } try { final StudentInfo item = getItem(position); holder.txtName.setText(item.getStudentName()); StudentListAdapter
5. Create Add / Update Activity 10. Create new layout les under layout folder named activity_add_update.xml. This the layout of Add / Update student data activity. 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 holder.txtStatus.setText(item.getStudentResult()); holder.txtGrade.setText(item.getStudentGrade()); // Update Student Data holder.imgEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, AddUpdateDetailsActivity.class); intent.putExtra("sid", item.getStudentId()); intent.putExtra("sname", item.getStudentName()); intent.putExtra("sstatus", item.getStudentResult()); intent.putExtra("sgrade", item.getStudentGrade()); MainActivity.opration = 1; display_data.startActivityForResult(intent, 1); } }); // Delete Student Data holder.imgDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); // Setting Dialog Title alertDialog.setTitle("Confirm Delete..."); // Setting Dialog Message alertDialog.setMessage("Are you sure you want delete this?"); // Setting Icon to Dialog alertDialog.setIcon(R.drawable.ic_delete); // Setting Positive "Yes" Button alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { db.deleteStudentDetails(new StudentInfo(item.getStudentId())); display_data.bindStudentData(); } }); // Setting Negative "NO" Button alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } catch (Exception e) { Log.e("Error ", e.getMessage()); e.printStackTrace(); } } }); } catch (Exception e) { Log.e("Error in adapter: ", e.getMessage()); e.printStackTrace(); } return holder.view; } public static class ViewProHolder { public final LinearLayout view; TextView txtName, txtStatus, txtGrade; ImageView imgEdit; ImageView imgDelete; public ViewProHolder(LinearLayout view, TextView tv_name, TextView tv_status, TextView im_icon, ImageView im_edit, ImageView im_delete) { this.view = view; this.txtName = tv_name; this.txtStatus = tv_status; this.txtGrade = im_icon; this.imgEdit = im_edit; this.imgDelete = im_delete; } public static ViewProHolder create(LinearLayout view) { // Widget GUI Init TextView tv_name = view.findViewById(R.id.txtName); TextView tv_status = view.findViewById(R.id.txtStatus); TextView tv_grade = view.findViewById(R.id.txtGrade); ImageView im_edit = view.findViewById(R.id.imgEdit); ImageView im_delete = view.findViewById(R.id.imgDelete); return new ViewProHolder(view, tv_name, tv_status, tv_grade, im_edit, im_delete); } } } 1 <?xml version="1.0" encoding="utf-8"?> activity_add_update.xml
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".ui.AddUpdateDetailsActivity"> <TextView android:id="@+id/tvHeading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/strAddNewStudent" android:layout_gravity="center" android:gravity="center" android:paddingTop="@dimen/_15sdp" android:layout_marginBottom="@dimen/_10sdp" android:textSize="30sp" /> <LinearLayout android:orientation="vertical" android:paddingLeft="@dimen/_15sdp" android:paddingRight="@dimen/_15sdp" android:layout_height="wrap_content" android:layout_width="match_parent"> <EditText android:id="@+id/etName" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textEmailAddress" android:maxLines="1" android:textSize="@dimen/_12sdp" android:hint="@string/strStudentName" android:layout_marginBottom="@dimen/_5sdp" android:textColor="@color/mainText" android:textColorHint="@color/subText" android:paddingTop="@dimen/_10sdp" android:paddingBottom="@dimen/_5sdp" android:background="@android:color/transparent" /> <View android:layout_width="fill_parent" android:layout_height="@dimen/_2sdp" android:layout_marginBottom="@dimen/_5sdp" android:background="@color/view"/> <EditText android:id="@+id/etStatus" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textEmailAddress" android:maxLines="1" android:textSize="@dimen/_12sdp" android:hint="@string/strStudentResult" android:layout_marginBottom="@dimen/_5sdp" android:textColor="@color/mainText" android:textColorHint="@color/subText" android:paddingTop="@dimen/_10sdp" android:paddingBottom="@dimen/_5sdp" android:background="@android:color/transparent" /> <View android:layout_width="fill_parent" android:layout_height="@dimen/_2sdp" android:layout_marginBottom="@dimen/_5sdp" android:background="@color/view"/> <EditText android:id="@+id/etGrade" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textEmailAddress" android:maxLines="1" android:textSize="@dimen/_12sdp" android:hint="@string/strStudentGrade" android:layout_marginBottom="@dimen/_5sdp" android:textColor="@color/mainText" android:textColorHint="@color/subText" android:paddingTop="@dimen/_10sdp" android:paddingBottom="@dimen/_5sdp" android:background="@android:color/transparent" /> <View android:layout_width="fill_parent" android:layout_height="@dimen/_2sdp" android:layout_marginBottom="@dimen/_40sdp" android:background="@color/view"/> <Button android:id="@+id/btnSave" android:text="@string/strSave" android:layout_gravity="center" android:gravity="center" android:background="@color/colorAccent" android:textColor="@color/colorWhite" android:layout_width="wrap_content"
11. Now create the AddUpdateDetailsActivity.java le under ui package. Using this class we can perform Add / Update operations. 92 93 94 95 android:padding="@dimen/_10sdp" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 public class AddUpdateDetailsActivity extends AppCompatActivity implements View.OnClickListener { // Primitive Variables int strId; String strName, strStatus, strGrade; // DB Objects public DBHelper db; // Widget GUI Declare TextView tvHeading; EditText etName, etStatus, etGrade; Button btnSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_update); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); // Initialize Database Instance db = new DBHelper(AddUpdateDetailsActivity.this); etName = findViewById(R.id.etName); etStatus = findViewById(R.id.etStatus); etGrade = findViewById(R.id.etGrade); tvHeading = findViewById(R.id.tvHeading); btnSave = findViewById(R.id.btnSave); // Set Title According To Operation if (opration == 0) { tvHeading.setText("Add Student Data"); } else { tvHeading.setText("Update Student Data"); } Intent intent = getIntent(); if (intent != null) { strId = intent.getIntExtra("sid", 0); strName = intent.getStringExtra("sname"); strStatus = intent.getStringExtra("sstatus"); strGrade = intent.getStringExtra("sgrade"); etName.setText(strName); etStatus.setText(strStatus); etGrade.setText(strGrade); } btnSave.setOnClickListener(this); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public void onClick(View v) { if (v.getId() == R.id.btnSave) { if (TextUtils.isEmpty(etName.getText())) { Toast.makeText(this, "Name is empty..!", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(etStatus.getText())) { Toast.makeText(this, "Status is empty..!", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(etGrade.getText())) { Toast.makeText(this, "Grade is empty..!", Toast.LENGTH_SHORT).show(); } else { // get values from edittext strName = etName.getText().toString(); strStatus = etStatus.getText().toString(); strGrade = etGrade.getText().toString(); if (opration == 0) { // Call insert method addDetails(); } else { // Call update method updateDetails(); } } } AddUpdateDetailsActivity.java
6. Setup Main Activity 12. Finally open MainActivity.java and add following code into this. MainActivity will show you all the student records in form of list. Using Floating Action Button you can add new student data in table. Edit Button allows to edit perticular student data from the list. By tapping Delete Button from the list you can delete particular student data. 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 } // Call update method of SQLiteDatabase Class and close after private void updateDetails() { Intent intent = new Intent(); try { db.updateStudentDetails(new StudentInfo(strId, strName, strStatus, strGrade)); showRecords(); intent.putExtra("msg", "Details updated successfully..!"); setResult(1, intent); finish(); } catch (Exception e) { e.printStackTrace(); intent.putExtra("msg", "Update Failed..!"); setResult(0, intent); finish(); } } // Call insert method of SQLiteDatabase Class and close after public void addDetails() { Intent intent = new Intent(); try { db.addStudentDetails(new StudentInfo(strName, strStatus, strGrade)); showRecords(); intent.putExtra("msg", "Details added successfully..!"); setResult(1, intent); finish(); } catch (Exception e) { e.printStackTrace(); intent.putExtra("msg", "added failed..!"); setResult(0, intent); finish(); } } // Reading all contacts public void showRecords() { Log.e("Reading ", "Reading all records.."); List<StudentInfo> studentInfos = db.getStudentDetails(); for (StudentInfo cn : studentInfos) { String log = "SId: " + cn.getStudentId() + " ,StudName: " + cn.getStudentName() + " StudStatus: " + cn.getStudentRes ) + " StudeGrade: " + cn.getStudentGrade(); // Writing records to log Log.e("Student: ", log); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public class MainActivity extends AppCompatActivity { // Primitive Variables public static int opration; List<StudentInfo> mStudentInfoList; // Widget GUI Declare ListView lstView; FloatingActionButton fab; // DB Objects DBHelper db; // Adapter Object StudentListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize Database Instance db = new DBHelper(MainActivity.this); // Widget GUI Init MainActivity.java
I hope you like this article. If you have followed this tutorial carefully then application run without any issue. Write us if there is any issue to implement SQLite Database In Android. Happy Coding 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 l s t Vi ew = f i ndVi ewByI d( R. i d. l s t St udent Det ai l s ) ; f ab = f i ndVi ewByI d( R. i d. f ab) ; / / Fet ch Dat a f r om dat abas e bi ndSt udent Dat a( ) ; / / At t ached Li s t ener f ab. s et OnCl i c kLi s t ener ( newnew Vi ew. OnCl i c kLi s t ener ( ) { @Over r i de publ i cpubl i c voi dvoi d onCl i c k( Vi ew v) { I nt ent i nt ent = newnew I nt ent ( get Appl i c at i onCont ext ( ) , AddUpdat eDet ai l s Ac t i vi t y . c l as sc l as s ) ; opr at i on = 0; s t ar t Ac t i vi t yFor Res ul t ( i nt ent , 1) ; } } ) ; } / / Get Al l St udent Dat a Fr om The Dat abas e publ i cpubl i c voi dvoi d bi ndSt udent Dat a( ) { mSt udent I nf oLi s t = db. get St udent Det ai l s ( ) ; adapt er = newnew St udent Li s t Adapt er ( Mai nAc t i vi t y. t hi s , R. l ayout . s t udent _l i s t _r ow, mSt udent I nf oLi s t ) ; l s t Vi ew. s et Adapt er ( adapt er ) ; l s t Vi ew. s et Empt yVi ew( f i ndVi ewByI d( R. i d. empt y) ) ; } @Over r i de publ i cpubl i c bool eanbool ean onCr eat eOpt i ons Menu( Menu menu) { MenuI nf l at er i nf l at er = get MenuI nf l at er ( ) ; i nf l at er . i nf l at e( R. menu. menu, menu) ; r et ur nr et ur n t r uet r ue ; } @Over r i de publ i cpubl i c bool eanbool ean onOpt i ons I t emSel ec t ed( MenuI t em i t em) { s wi t c hs wi t c h ( i t em. get I t emI d( ) ) { c as ec as e R. i d. addDet ai l s : / / Cal l f or add dat a I nt ent i nt ent = newnew I nt ent ( get Appl i c at i onCont ext ( ) , AddUpdat eDet ai l s Ac t i vi t y . c l as sc l as s ) ; opr at i on = 0; s t ar t Ac t i vi t yFor Res ul t ( i nt ent , 1) ; r et ur nr et ur n t r uet r ue ; } r et ur nr et ur n s upers uper . onOpt i ons I t emSel ec t ed( i t em) ; } @Over r i de pr ot ec t edpr ot ec t ed voi dvoi d onAc t i vi t yRes ul t ( i nti nt r eques t Code, i nti nt r es ul t Code, I nt ent dat a) { s upers uper . onAc t i vi t yRes ul t ( r eques t Code, r es ul t Code, dat a) ; t r yt r y { i fi f ( r eques t Code == r es ul t Code) { r ef er s hLayout ( ) ; Toas t . makeText ( get Appl i c at i onCont ext ( ) , " Res ul t s uc c es s : " + dat a. get St r i ngExt r a( " ms g" ) , Toas t . LENGTH_SHO } el s eel s e { St r i ngSt r i ng s t r = dat a. get St r i ngExt r a( " ms g" ) ; i fi f ( Text Ut i l s . i s Empt y( s t r ) ) { Toas t . makeText ( get Appl i c at i onCont ext ( ) , " empt y" , Toas t . LENGTH_SHORT) . s how( ) ; } el s eel s e { Log. e( " Er r or " , s t r ) ; Toas t . makeText ( get Appl i c at i onCont ext ( ) , " Er r or : " + dat a. get St r i ngExt r a( " ms g" ) , Toas t . LENGTH_SHORT } } } c at c hc at c h ( Exc ept i on e) { e. pr i nt St ac kTr ac e( ) ; } } publ i cpubl i c voi dvoi d r ef er s hLayout ( ) { i fi f ( Bui l d. VERSI ON. SDK_I NT >= 16) { t hi st hi s . r ec r eat e( ) ; } el s eel s e { f i nalf i nal I nt ent i nt ent = get I nt ent ( ) ; i nt ent . addFl ags ( I nt ent . FLAG_ACTI VI TY_NO_ANI MATI ON) ; t hi st hi s . f i ni s h( ) ; t hi st hi s . over r i dePendi ngTr ans i t i on( 0, 0) ; t hi st hi s . s t ar t Ac t i vi t y( i nt ent ) ; t hi st hi s . over r i dePendi ngTr ans i t i on( 0, 0) ; } } }

SQLite Database Tutorial In Android

  • 1.
    SQLite Database TutorialIn Android Posted on J uly 9, 2018 by Bhadresh SQLite Database in Android used to store persistent data. If you want to store some data into local storage then SQLite Database is the most common storage option. It is lightweight database that comes with Android OS. In Android There are others data storage options also available Like Shared Preference to store small amount of data in form of Key / Value pair. SQLite Database File System Here we are going to learn how to use SQLite Database in Android application. SQLite is an open source SQL database which store the data into text le on android device. SQLite database in android also support relational database features. In order to access SQLite Database you don’t need to establish any kind of connections like J DBC, ODBC. 1. Overview In this tutorial we are going to create Student App to learn all the operation related the SQLite Database. The app is very simple and which allow us to insert, update, delete and view student data. We will use 2 screen to perform all this operations. In rst screen we fetch full list of student from the student table while using second screen update or add new student record. Following is the Student app screen shot.
  • 2.
    Now let’s startby creating new project in Android Studio. 2. Create / Setup Project 1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from the templates. 2. Open build.gradle under app directory and add CardView library. CardView is used to display Student List inside the Card. 3. Add following code into colors.xml and strings.xml les. colors.xml 1 2 3 4 5 6 7 8 dependencies { //... implementation 'com.android.support:cardview-v7:27.1.1' //... } 1 2 3 4 5 6 7 8 9 10 <?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> <color name="mainText">#212121</color> <color name="subText">#737373</color> <color name="view">#c0c0c0</color> <color name="colorWhite">#ffffff</color> </resources> colors.xml
  • 3.
    strings.xml 4. Create followingpackages named adapter, db, model and ui. The following is the nal project structure and les are required. 3. Create SQLite Helper Classes 5. In this tutorial we have taken student example to perform all operation. So rst we need to create one model class named StudentInfo.java under model package. StudentInfo.java contain student information like id, name, grade and result. Further we will used this class to store and retrieve student information from the SQLite database. 1 2 3 4 5 6 7 8 9 10 <resources> <string name="app_name">Student Management</string> <string name="strAddNewStudent">Add New Student</string> <string name="strUpdateStudent">Update Student</string> <string name="strDelete">Delete</string> <string name="strStudentName">Enter Student Name</string> <string name="strStudentResult">Enter Pass/Fail</string> <string name="strStudentGrade">Enter Grade</string> <string name="strSave">Save</string> </resources> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public class StudentInfo { int studentId; String studentName, studentResult, studentGrade; public StudentInfo() { } public StudentInfo(int studentId) { this.studentId = studentId; } public StudentInfo(String studentName, String studentResult, String studentGrade) { this.studentName = studentName; this.studentResult = studentResult; this.studentGrade = studentGrade; } public StudentInfo(int studentId, String studentName, String studentResult, String studentGrade) { this.studentId = studentId; this.studentName = studentName; this.studentResult = studentResult; this.studentGrade = studentGrade; } public int getStudentId() { return studentId; strings.xml StudentInfo.java
  • 4.
    6. Now weneed to create a class that extends from SQLiteOpenHelper. So create DBHelper.java under db package. DBHelper.java perform all the database operations like Create, Update, Delete and Read. Before the proceed let’s understand use of all the methods and table structure of the StudentInfo. onCreate() method will be called only once when application launch rst time in android phone. So from this method we will execute sql statement to create Student table. onUpgrade() method will be called when update the application. You need to change the DB_VERSION in order to execute this methods. The StudentInfo table needs four column : _id, name, result and grade. Column _id is declared as Primary Key and Auto Increment which means it is unique key to identify the Students. name contains student name, result is ether pass or fail, grade contains student grade. So let add the following code into DBHelper Class. 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 } public void setStudentId(int studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getStudentResult() { return studentResult; } public void setStudentResult(String studentResult) { this.studentResult = studentResult; } public String getStudentGrade() { return studentGrade; } public void setStudentGrade(String studentGrade) { this.studentGrade = studentGrade; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 public class DBHelper extends SQLiteOpenHelper{ // Database Name static final String DATABASE = "student.db"; // Database Version static final int DB_VERSION = 1; // Table Name static final String TABLE = "StudentInfo"; // Table Field Name static final String S_ID = "_id"; static final String S_NAME = "name"; static final String S_RESULT = "result"; static final String S_GRADE = "grade"; // Override constructor public DBHelper(Context context) { super(context, DATABASE, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // Create StudentInfo table using SQL query db.execSQL("CREATE TABLE " + TABLE + " ( " + S_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + S_NAME + " text, " + S_RESULT + " text, " + S_GRADE + " text )"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { DBHelper.java
  • 5.
    7. Now weneed to implement four methods to perform CRUD [Create, Read, Update, Delete] operations with student data. Let’s have look of each methods. 7.1 Insert Student Data Inserting data requires writable instance of the SQLiteDatabase So Create instance using getWritableDatabase(). ContentValues() is used to add database values in respective column. So setup all the value with respective column in ContentValues(), Skip _id because it’s auto inserted. Close the database connection after inserting is done. 7.2 Update Student Data. Updating data also requiring writable access of the SQLiteDatabase. Student data will be updated using _id column. 7.3 Delete Student Data. To delete student data we also required to declare SQLiteDatabase instance with writable access. The following methods will be Delete speci ed student record from the database using _id 7.4 Fetch Student Data To read data from the database table requires SQLiteDatabase instance as a read access. For that we can de ne SQLiteDatabase instance using getReadableDatabase(). Following method will fetch all students data from the database table. 34 35 36 37 38 39 40 // Drop old version table db.execSQL("Drop table " + TABLE); // Create New Version table onCreate(db); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 public void addStudentDetails(StudentInfo studInfo) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(S_NAME, studInfo.getStudentName()); values.put(S_RESULT, studInfo.getStudentResult()); values.put(S_GRADE, studInfo.getStudentGrade()); // Inserting Row db.insert(TABLE, null, values); db.close(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 public int updateStudentDetails(StudentInfo studInfo) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(S_NAME, studInfo.getStudentName()); values.put(S_RESULT, studInfo.getStudentResult()); values.put(S_GRADE, studInfo.getStudentGrade()); // updating row return db.update(TABLE, values, S_ID + " = ?", new String[]{String.valueOf(studInfo.getStudentId())}); } 1 2 3 4 5 6 7 8 public void deleteStudentDetails(StudentInfo studentInfo) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE, S_ID + " = ?", new String[]{String.valueOf(studentInfo.getStudentId())}); db.close(); } 1 public List<StudentInfo> getStudentDetails() { addStudentDetails updateStudentDetails deleteStudentDetails getStudentDetails
  • 6.
    So add allabove methods into DBHelper.java class, The nal code of the DBHelper.java class looks like this. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 List<StudentInfo> StudentList = new ArrayList<>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { StudentInfo studentInfo = new StudentInfo(); studentInfo.setStudentId(cursor.getInt(0)); studentInfo.setStudentName(cursor.getString(1)); studentInfo.setStudentResult(cursor.getString(2)); studentInfo.setStudentGrade(cursor.getString(3)); // Adding student information to list StudentList.add(studentInfo); } while (cursor.moveToNext()); } cursor.close(); return StudentList; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 package dwi.db.operations.student.management.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; import dwi.db.operations.student.management.model.StudentInfo; public class DBHelper extends SQLiteOpenHelper{ // Static Final Variable database meta information static final String DATABASE = "student.db"; static final int DB_VERSION = 1; static final String TABLE = "StudentInfo"; static final String S_ID = "_id"; static final String S_NAME = "name"; static final String S_RESULT = "result"; static final String S_GRADE = "grade"; // Override constructor public DBHelper(Context context) { super(context, DATABASE, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // Create StudentInfo table using SQL query db.execSQL("CREATE TABLE " + TABLE + " ( " + S_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + S_NAME + " text, " + S_RESULT + " text, " + S_GRADE + " text )"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop old version table db.execSQL("Drop table " + TABLE); // Create New Version table onCreate(db); } // Adding new detail public void addStudentDetails(StudentInfo studInfo) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(S_NAME, studInfo.getStudentName()); values.put(S_RESULT, studInfo.getStudentResult()); values.put(S_GRADE, studInfo.getStudentGrade()); // Inserting Row db.insert(TABLE, null, values); db.close(); // Closing database connection } // Updating details public int updateStudentDetails(StudentInfo studInfo) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); DBHelper.java
  • 7.
    4. Create ListAdapter 8. Create new layout les under layout folder named student_list_row.xml. This layout le holds single items in list. 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 values.put(S_NAME, studInfo.getStudentName()); values.put(S_RESULT, studInfo.getStudentResult()); values.put(S_GRADE, studInfo.getStudentGrade()); // updating row return db.update(TABLE, values, S_ID + " = ?", new String[]{String.valueOf(studInfo.getStudentId())}); } // Deleting single recoed public void deleteStudentDetails(StudentInfo studentInfo) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE, S_ID + " = ?", new String[]{String.valueOf(studentInfo.getStudentId())}); db.close(); } // Get all student information public List<StudentInfo> getStudentDetails() { List<StudentInfo> StudentList = new ArrayList<>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { StudentInfo studentInfo = new StudentInfo(); studentInfo.setStudentId(cursor.getInt(0)); studentInfo.setStudentName(cursor.getString(1)); studentInfo.setStudentResult(cursor.getString(2)); studentInfo.setStudentGrade(cursor.getString(3)); // Adding student information to list StudentList.add(studentInfo); } while (cursor.moveToNext()); } cursor.close(); return StudentList; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <android.support.v7.widget.CardView android:id="@+id/card_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/_15sdp" android:layout_marginLeft="@dimen/_5sdp" android:layout_marginRight="@dimen/_5sdp" app:cardBackgroundColor="#FFFFFF" card_view:cardCornerRadius="2dp" card_view:contentPadding="10dp"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_weight="0.5" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/txtName" android:hint="Name" android:layout_weight="6" android:textSize="15dp" android:textColor="#000" android:layout_gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" /> <TextView android:id="@+id/txtStatus" android:hint="Status" android:layout_weight="6" android:textSize="15dp" android:textColor="#000" android:layout_gravity="center" android:layout_width="match_parent" student_list_row.xml
  • 8.
    9. Now createthe new class named StudentListAdapter.java under adapter package. This is the Student List adapter and it will show you all the student records from the database. From the list you can Delete or Update particular student data by tapping on Delete or Update button. 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 android:layout_height="wrap_content" android:padding="5dp" /> <TextView android:id="@+id/txtGrade" android:hint="Grade" android:layout_weight="6" android:textSize="15dp" android:textColor="#000" android:layout_gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" /> </LinearLayout> <LinearLayout android:layout_weight="1.9" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imgEdit" android:layout_weight="2" android:src="@drawable/ic_edit" android:layout_width="@dimen/_20sdp" android:layout_height="@dimen/_20sdp" android:layout_gravity="center" /> <ImageView android:id="@+id/imgDelete" android:layout_weight="2" android:src="@drawable/ic_delete" android:layout_width="@dimen/_20sdp" android:layout_height="@dimen/_20sdp" android:layout_gravity="center" /> </LinearLayout> </LinearLayout> </android.support.v7.widget.CardView> </LinearLayout> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 public class StudentListAdapter extends ArrayAdapter<StudentInfo> { // Context Objects Context context; MainActivity display_data; // Primitive Variables public List<StudentInfo> productList; public static LayoutInflater inflater = null; // DB Objects DBHelper db; public StudentListAdapter(@NonNull Context context, int resource, List<StudentInfo> productList) { super(context, resource, productList); this.context = context; this.productList = productList; db = new DBHelper(context); display_data = (MainActivity) this.context; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public StudentInfo getItem(int position) { return productList.get(position); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { ViewProHolder holder; if (convertView == null) { View view = inflater.inflate(R.layout.student_list_row, null); holder = ViewProHolder.create((LinearLayout) view); view.setTag(holder); } else { holder = (ViewProHolder) convertView.getTag(); } try { final StudentInfo item = getItem(position); holder.txtName.setText(item.getStudentName()); StudentListAdapter
  • 9.
    5. Create Add/ Update Activity 10. Create new layout les under layout folder named activity_add_update.xml. This the layout of Add / Update student data activity. 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 holder.txtStatus.setText(item.getStudentResult()); holder.txtGrade.setText(item.getStudentGrade()); // Update Student Data holder.imgEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, AddUpdateDetailsActivity.class); intent.putExtra("sid", item.getStudentId()); intent.putExtra("sname", item.getStudentName()); intent.putExtra("sstatus", item.getStudentResult()); intent.putExtra("sgrade", item.getStudentGrade()); MainActivity.opration = 1; display_data.startActivityForResult(intent, 1); } }); // Delete Student Data holder.imgDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); // Setting Dialog Title alertDialog.setTitle("Confirm Delete..."); // Setting Dialog Message alertDialog.setMessage("Are you sure you want delete this?"); // Setting Icon to Dialog alertDialog.setIcon(R.drawable.ic_delete); // Setting Positive "Yes" Button alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { db.deleteStudentDetails(new StudentInfo(item.getStudentId())); display_data.bindStudentData(); } }); // Setting Negative "NO" Button alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } catch (Exception e) { Log.e("Error ", e.getMessage()); e.printStackTrace(); } } }); } catch (Exception e) { Log.e("Error in adapter: ", e.getMessage()); e.printStackTrace(); } return holder.view; } public static class ViewProHolder { public final LinearLayout view; TextView txtName, txtStatus, txtGrade; ImageView imgEdit; ImageView imgDelete; public ViewProHolder(LinearLayout view, TextView tv_name, TextView tv_status, TextView im_icon, ImageView im_edit, ImageView im_delete) { this.view = view; this.txtName = tv_name; this.txtStatus = tv_status; this.txtGrade = im_icon; this.imgEdit = im_edit; this.imgDelete = im_delete; } public static ViewProHolder create(LinearLayout view) { // Widget GUI Init TextView tv_name = view.findViewById(R.id.txtName); TextView tv_status = view.findViewById(R.id.txtStatus); TextView tv_grade = view.findViewById(R.id.txtGrade); ImageView im_edit = view.findViewById(R.id.imgEdit); ImageView im_delete = view.findViewById(R.id.imgDelete); return new ViewProHolder(view, tv_name, tv_status, tv_grade, im_edit, im_delete); } } } 1 <?xml version="1.0" encoding="utf-8"?> activity_add_update.xml
  • 10.
    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".ui.AddUpdateDetailsActivity"> <TextView android:id="@+id/tvHeading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/strAddNewStudent" android:layout_gravity="center" android:gravity="center" android:paddingTop="@dimen/_15sdp" android:layout_marginBottom="@dimen/_10sdp" android:textSize="30sp" /> <LinearLayout android:orientation="vertical" android:paddingLeft="@dimen/_15sdp" android:paddingRight="@dimen/_15sdp" android:layout_height="wrap_content"android:layout_width="match_parent"> <EditText android:id="@+id/etName" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textEmailAddress" android:maxLines="1" android:textSize="@dimen/_12sdp" android:hint="@string/strStudentName" android:layout_marginBottom="@dimen/_5sdp" android:textColor="@color/mainText" android:textColorHint="@color/subText" android:paddingTop="@dimen/_10sdp" android:paddingBottom="@dimen/_5sdp" android:background="@android:color/transparent" /> <View android:layout_width="fill_parent" android:layout_height="@dimen/_2sdp" android:layout_marginBottom="@dimen/_5sdp" android:background="@color/view"/> <EditText android:id="@+id/etStatus" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textEmailAddress" android:maxLines="1" android:textSize="@dimen/_12sdp" android:hint="@string/strStudentResult" android:layout_marginBottom="@dimen/_5sdp" android:textColor="@color/mainText" android:textColorHint="@color/subText" android:paddingTop="@dimen/_10sdp" android:paddingBottom="@dimen/_5sdp" android:background="@android:color/transparent" /> <View android:layout_width="fill_parent" android:layout_height="@dimen/_2sdp" android:layout_marginBottom="@dimen/_5sdp" android:background="@color/view"/> <EditText android:id="@+id/etGrade" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textEmailAddress" android:maxLines="1" android:textSize="@dimen/_12sdp" android:hint="@string/strStudentGrade" android:layout_marginBottom="@dimen/_5sdp" android:textColor="@color/mainText" android:textColorHint="@color/subText" android:paddingTop="@dimen/_10sdp" android:paddingBottom="@dimen/_5sdp" android:background="@android:color/transparent" /> <View android:layout_width="fill_parent" android:layout_height="@dimen/_2sdp" android:layout_marginBottom="@dimen/_40sdp" android:background="@color/view"/> <Button android:id="@+id/btnSave" android:text="@string/strSave" android:layout_gravity="center" android:gravity="center" android:background="@color/colorAccent" android:textColor="@color/colorWhite" android:layout_width="wrap_content"
  • 11.
    11. Now createthe AddUpdateDetailsActivity.java le under ui package. Using this class we can perform Add / Update operations. 92 93 94 95 android:padding="@dimen/_10sdp" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 public class AddUpdateDetailsActivity extends AppCompatActivity implements View.OnClickListener { // Primitive Variables int strId; String strName, strStatus, strGrade; // DB Objects public DBHelper db; // Widget GUI Declare TextView tvHeading; EditText etName, etStatus, etGrade; Button btnSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_update); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); // Initialize Database Instance db = new DBHelper(AddUpdateDetailsActivity.this); etName = findViewById(R.id.etName); etStatus = findViewById(R.id.etStatus); etGrade = findViewById(R.id.etGrade); tvHeading = findViewById(R.id.tvHeading); btnSave = findViewById(R.id.btnSave); // Set Title According To Operation if (opration == 0) { tvHeading.setText("Add Student Data"); } else { tvHeading.setText("Update Student Data"); } Intent intent = getIntent(); if (intent != null) { strId = intent.getIntExtra("sid", 0); strName = intent.getStringExtra("sname"); strStatus = intent.getStringExtra("sstatus"); strGrade = intent.getStringExtra("sgrade"); etName.setText(strName); etStatus.setText(strStatus); etGrade.setText(strGrade); } btnSave.setOnClickListener(this); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } @Override public void onClick(View v) { if (v.getId() == R.id.btnSave) { if (TextUtils.isEmpty(etName.getText())) { Toast.makeText(this, "Name is empty..!", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(etStatus.getText())) { Toast.makeText(this, "Status is empty..!", Toast.LENGTH_SHORT).show(); } else if (TextUtils.isEmpty(etGrade.getText())) { Toast.makeText(this, "Grade is empty..!", Toast.LENGTH_SHORT).show(); } else { // get values from edittext strName = etName.getText().toString(); strStatus = etStatus.getText().toString(); strGrade = etGrade.getText().toString(); if (opration == 0) { // Call insert method addDetails(); } else { // Call update method updateDetails(); } } } AddUpdateDetailsActivity.java
  • 12.
    6. Setup MainActivity 12. Finally open MainActivity.java and add following code into this. MainActivity will show you all the student records in form of list. Using Floating Action Button you can add new student data in table. Edit Button allows to edit perticular student data from the list. By tapping Delete Button from the list you can delete particular student data. 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 } // Call update method of SQLiteDatabase Class and close after private void updateDetails() { Intent intent = new Intent(); try { db.updateStudentDetails(new StudentInfo(strId, strName, strStatus, strGrade)); showRecords(); intent.putExtra("msg", "Details updated successfully..!"); setResult(1, intent); finish(); } catch (Exception e) { e.printStackTrace(); intent.putExtra("msg", "Update Failed..!"); setResult(0, intent); finish(); } } // Call insert method of SQLiteDatabase Class and close after public void addDetails() { Intent intent = new Intent(); try { db.addStudentDetails(new StudentInfo(strName, strStatus, strGrade)); showRecords(); intent.putExtra("msg", "Details added successfully..!"); setResult(1, intent); finish(); } catch (Exception e) { e.printStackTrace(); intent.putExtra("msg", "added failed..!"); setResult(0, intent); finish(); } } // Reading all contacts public void showRecords() { Log.e("Reading ", "Reading all records.."); List<StudentInfo> studentInfos = db.getStudentDetails(); for (StudentInfo cn : studentInfos) { String log = "SId: " + cn.getStudentId() + " ,StudName: " + cn.getStudentName() + " StudStatus: " + cn.getStudentRes ) + " StudeGrade: " + cn.getStudentGrade(); // Writing records to log Log.e("Student: ", log); } } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public class MainActivity extends AppCompatActivity { // Primitive Variables public static int opration; List<StudentInfo> mStudentInfoList; // Widget GUI Declare ListView lstView; FloatingActionButton fab; // DB Objects DBHelper db; // Adapter Object StudentListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize Database Instance db = new DBHelper(MainActivity.this); // Widget GUI Init MainActivity.java
  • 13.
    I hope youlike this article. If you have followed this tutorial carefully then application run without any issue. Write us if there is any issue to implement SQLite Database In Android. Happy Coding 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 l s t Vi ew = f i ndVi ewByI d( R. i d. l s t St udent Det ai l s ) ; f ab = f i ndVi ewByI d( R. i d. f ab) ; / / Fet ch Dat a f r om dat abas e bi ndSt udent Dat a( ) ; / / At t ached Li s t ener f ab. s et OnCl i c kLi s t ener ( newnew Vi ew. OnCl i c kLi s t ener ( ) { @Over r i de publ i cpubl i c voi dvoi d onCl i c k( Vi ew v) { I nt ent i nt ent = newnew I nt ent ( get Appl i c at i onCont ext ( ) , AddUpdat eDet ai l s Ac t i vi t y . c l as sc l as s ) ; opr at i on = 0; s t ar t Ac t i vi t yFor Res ul t ( i nt ent , 1) ; } } ) ; } / / Get Al l St udent Dat a Fr om The Dat abas e publ i cpubl i c voi dvoi d bi ndSt udent Dat a( ) { mSt udent I nf oLi s t = db. get St udent Det ai l s ( ) ; adapt er = newnew St udent Li s t Adapt er ( Mai nAc t i vi t y. t hi s , R. l ayout . s t udent _l i s t _r ow, mSt udent I nf oLi s t ) ; l s t Vi ew. s et Adapt er ( adapt er ) ; l s t Vi ew. s et Empt yVi ew( f i ndVi ewByI d( R. i d. empt y) ) ; } @Over r i de publ i cpubl i c bool eanbool ean onCr eat eOpt i ons Menu( Menu menu) { MenuI nf l at er i nf l at er = get MenuI nf l at er ( ) ; i nf l at er . i nf l at e( R. menu. menu, menu) ; r et ur nr et ur n t r uet r ue ; } @Over r i de publ i cpubl i c bool eanbool ean onOpt i ons I t emSel ec t ed( MenuI t em i t em) { s wi t c hs wi t c h ( i t em. get I t emI d( ) ) { c as ec as e R. i d. addDet ai l s : / / Cal l f or add dat a I nt ent i nt ent = newnew I nt ent ( get Appl i c at i onCont ext ( ) , AddUpdat eDet ai l s Ac t i vi t y . c l as sc l as s ) ; opr at i on = 0; s t ar t Ac t i vi t yFor Res ul t ( i nt ent , 1) ; r et ur nr et ur n t r uet r ue ; } r et ur nr et ur n s upers uper . onOpt i ons I t emSel ec t ed( i t em) ; } @Over r i de pr ot ec t edpr ot ec t ed voi dvoi d onAc t i vi t yRes ul t ( i nti nt r eques t Code, i nti nt r es ul t Code, I nt ent dat a) { s upers uper . onAc t i vi t yRes ul t ( r eques t Code, r es ul t Code, dat a) ; t r yt r y { i fi f ( r eques t Code == r es ul t Code) { r ef er s hLayout ( ) ; Toas t . makeText ( get Appl i c at i onCont ext ( ) , " Res ul t s uc c es s : " + dat a. get St r i ngExt r a( " ms g" ) , Toas t . LENGTH_SHO } el s eel s e { St r i ngSt r i ng s t r = dat a. get St r i ngExt r a( " ms g" ) ; i fi f ( Text Ut i l s . i s Empt y( s t r ) ) { Toas t . makeText ( get Appl i c at i onCont ext ( ) , " empt y" , Toas t . LENGTH_SHORT) . s how( ) ; } el s eel s e { Log. e( " Er r or " , s t r ) ; Toas t . makeText ( get Appl i c at i onCont ext ( ) , " Er r or : " + dat a. get St r i ngExt r a( " ms g" ) , Toas t . LENGTH_SHORT } } } c at c hc at c h ( Exc ept i on e) { e. pr i nt St ac kTr ac e( ) ; } } publ i cpubl i c voi dvoi d r ef er s hLayout ( ) { i fi f ( Bui l d. VERSI ON. SDK_I NT >= 16) { t hi st hi s . r ec r eat e( ) ; } el s eel s e { f i nalf i nal I nt ent i nt ent = get I nt ent ( ) ; i nt ent . addFl ags ( I nt ent . FLAG_ACTI VI TY_NO_ANI MATI ON) ; t hi st hi s . f i ni s h( ) ; t hi st hi s . over r i dePendi ngTr ans i t i on( 0, 0) ; t hi st hi s . s t ar t Ac t i vi t y( i nt ent ) ; t hi st hi s . over r i dePendi ngTr ans i t i on( 0, 0) ; } } }