1 / 13

SQLite Database Tutorial In Android

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.

androidfive
Download Presentation

SQLite Database Tutorial In Android

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ? SQLite Database Tutorial In Android Posted on July 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 JDBC, 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 start by creating new project in Android Studio. 2. Create / Setup Project File ⇒ New Project New Project and select Basic Activity from the templates. 1. 1. Create a new project in Android Studio from File 2. 2. Open build.gradle build.gradle under app directory and add CardView CardView library. CardView CardView is used to display Student List inside the Card. 1 2 3 4 5 6 7 8 dependencies { //... implementation 'com.android.support:cardview-v7:27.1.1' //... } 3. 3. Add following code into colors.xml colors.xml and strings.xml strings.xml ?les. colors.xml colors.xml colors.xml 1 2 3 4 5 6 7 8 9 <?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> 10

  3. strings.xml strings.xml strings.xml 1 2 3 4 5 6 7 8 9 <resources> <string string name="app_name">Student Management</string <string string name="strAddNewStudent">Add New <string string name="strUpdateStudent">Update Student</string <string string name="strDelete">Delete</string <string string name="strStudentName">Enter Student Name</string <string string name="strStudentResult">Enter Pass/Fail</string <string string name="strStudentGrade">Enter Grade</string <string string name="strSave">Save</string </resources> string> New Student</string string> string> string> string> string> string> string> 10 4. 4. Create following packages named adapter, db, model adapter, db, model and ui ui. The following is the ?nal project structure and ?les are required. 3. Create SQLite Helper Classes 5. 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 StudentInfo.java under model model package. StudentInfo.java 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. StudentInfo.java 1 2 3 4 5 6 7 8 9 public public class int int studentId; String String studentName, studentResult, studentGrade; public public StudentInfo() { } public public StudentInfo(int int studentId) { this this.studentId = studentId; } public public StudentInfo(String String studentName, String this this.studentName = studentName; this this.studentResult = studentResult; this this.studentGrade = studentGrade; } public public StudentInfo(int int studentId, String this this.studentId = studentId; this this.studentName = studentName; this this.studentResult = studentResult; this this.studentGrade = studentGrade; } public public int int getStudentId() { return return studentId; class StudentInfo { 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 String studentResult, String String studentGrade) { String studentName, String String studentResult, String String studentGrade) {

  4. 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 public void this } public public String return return studentName; } public public void void setStudentName(String this this.studentName = studentName; } public public String String getStudentResult() { return return studentResult; } public public void void setStudentResult(String this this.studentResult = studentResult; } public public String String getStudentGrade() { return return studentGrade; } public public void void setStudentGrade(String this this.studentGrade = studentGrade; } } void setStudentId(int this.studentId = studentId; int studentId) { String getStudentName() { String studentName) { String studentResult) { String studentGrade) { 6. 6. Now we need to create a class that extends from SQLiteOpenHelper SQLiteOpenHelper. So create DBHelper.java DBHelper.java under db db package. DBHelper.java 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() 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() onUpgrade() method will be called when update the application. You need to change the DB_VERSION DB_VERSION in order to execute this methods. The StudentInfo StudentInfo table needs four column : _id, name, result _id, name, result and grade grade. Column _id _id is declared as Primary Key Primary Key and Auto Increment Auto Increment which means it is unique key to identify the Students. name name contains student name, result result is ether pass or fail, grade grade contains student grade. So let add the following code into DBHelper DBHelper Class. DBHelper.java 1 2 3 4 5 6 7 8 9 public public class // Database Name static static final final String // Database Version static static final final int // Table Name static static final final String // Table Field Name static static final final String static static final final String static static final final String static static final final String // Override constructor public public DBHelper(Context context) { super super(context, DATABASE, null } @Override public public void 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 public void void onUpgrade(SQLiteDatabase db, int class DBHelper extends extends SQLiteOpenHelper{ String DATABASE = "student.db"; int DB_VERSION = 1; 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 String TABLE = "StudentInfo"; String S_ID = "_id"; String S_NAME = "name"; String S_RESULT = "result"; String S_GRADE = "grade"; null, DB_VERSION); int oldVersion, int int newVersion) {

  5. 34 35 36 37 38 39 40 // Drop old version table db.execSQL("Drop table " + TABLE); // Create New Version table onCreate(db); } } 7. 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 SQLiteDatabase So Create instance using getWritableDatabase() getWritableDatabase(). ContentValues() ContentValues() is used to add database values in respective column. So setup all the value with respective column in ContentValues() ContentValues(), Skip _id _id because it’s auto inserted. Close the database connection after inserting is done. addStudentDetails 1 2 3 4 5 6 7 8 9 public public void SQLiteDatabase db = this ContentValues values = new values.put(S_NAME, studInfo.getStudentName()); values.put(S_RESULT, studInfo.getStudentResult()); values.put(S_GRADE, studInfo.getStudentGrade()); // Inserting Row db.insert(TABLE, null null, values); db.close(); } void addStudentDetails(StudentInfo studInfo) { this.getWritableDatabase(); new ContentValues(); 10 11 12 13 7.2 Update Student Data. Updating data also requiring writable access of the SQLiteDatabase SQLiteDatabase. Student data will be updated using _id _id column. updateStudentDetails 1 2 3 4 5 6 7 8 9 public public int SQLiteDatabase db = this ContentValues values = new values.put(S_NAME, studInfo.getStudentName()); values.put(S_RESULT, studInfo.getStudentResult()); values.put(S_GRADE, studInfo.getStudentGrade()); // updating row return return db.update(TABLE, values, S_ID + " = ?", new new String String[]{String String.valueOf(studInfo.getStudentId())}); } int updateStudentDetails(StudentInfo studInfo) { this.getWritableDatabase(); new ContentValues(); 10 11 12 13 7.3 Delete Student Data. To delete student data we also required to declare SQLiteDatabase SQLiteDatabase instance with writable access. The following methods will be Delete speci?ed student record from the database using _id _id deleteStudentDetails 1 2 3 4 5 6 7 8 public public void SQLiteDatabase db = this db.delete(TABLE, S_ID + " = ?", new new String String[]{String db.close(); } void deleteStudentDetails(StudentInfo studentInfo) { this.getWritableDatabase(); String.valueOf(studentInfo.getStudentId())}); 7.4 Fetch Student Data To read data from the database table requires SQLiteDatabase SQLiteDatabase instance as a read access. For that we can de?ne SQLiteDatabase SQLiteDatabase instance using getReadableDatabase() getReadableDatabase(). Following method will fetch all students data from the database table. getStudentDetails 1 public public List<StudentInfo> getStudentDetails() {

  6. 2 3 4 5 6 7 8 9 List<StudentInfo> StudentList = new // Select All Query String String selectQuery = "SELECT * FROM " + TABLE; SQLiteDatabase db = this this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null // looping through all rows and adding to list if if (cursor.moveToFirst()) { do do { StudentInfo studentInfo = new 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 while (cursor.moveToNext()); } cursor.close(); return return StudentList; } new ArrayList<>(); null); 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 new StudentInfo(); So add all above methods into DBHelper.java class DBHelper.java class, The ?nal code of the DBHelper.java DBHelper.java class looks like this. DBHelper.java 1 2 3 4 5 6 7 8 9 package 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 public class class DBHelper extends extends SQLiteOpenHelper{ // Static Final Variable database meta information static static final final String String DATABASE = "student.db"; static static final final int int DB_VERSION = 1; static static final final String String TABLE = "StudentInfo"; static static final final String String S_ID = "_id"; static static final final String String S_NAME = "name"; static static final final String String S_RESULT = "result"; static static final final String String S_GRADE = "grade"; // Override constructor public public DBHelper(Context context) { super super(context, DATABASE, null } @Override public public void 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 public void void onUpgrade(SQLiteDatabase db, int // Drop old version table db.execSQL("Drop table " + TABLE); // Create New Version table onCreate(db); } // Adding new detail public public void void addStudentDetails(StudentInfo studInfo) { SQLiteDatabase db = this this.getWritableDatabase(); ContentValues values = new 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 null, values); db.close(); // Closing database connection } // Updating details public public int int updateStudentDetails(StudentInfo studInfo) { SQLiteDatabase db = this this.getWritableDatabase(); ContentValues values = new new ContentValues(); 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 null, DB_VERSION); int oldVersion, int int newVersion) {

  7. 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 return db.update(TABLE, values, S_ID + " = ?", new new String String[]{String String.valueOf(studInfo.getStudentId())}); } // Deleting single recoed public public void void deleteStudentDetails(StudentInfo studentInfo) { SQLiteDatabase db = this this.getWritableDatabase(); db.delete(TABLE, S_ID + " = ?", new new String String[]{String String.valueOf(studentInfo.getStudentId())}); db.close(); } // Get all student information public public List<StudentInfo> getStudentDetails() { List<StudentInfo> StudentList = new // Select All Query String String selectQuery = "SELECT * FROM " + TABLE; SQLiteDatabase db = this this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null // looping through all rows and adding to list if if (cursor.moveToFirst()) { do do { StudentInfo studentInfo = new 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 while (cursor.moveToNext()); } cursor.close(); return return StudentList; } } new ArrayList<>(); null); new StudentInfo(); 4. Create List Adapter 8. 8. Create new layout ?les under layout folder named student_list_row.xml student_list_row.xml. This layout ?le holds single items in list. student_list_row.xml 1 2 3 4 5 6 7 8 9 <?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" 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

  8. 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> 9. 9. Now create the new class named StudentListAdapter.java StudentListAdapter.java under adapter 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. StudentListAdapter 1 2 3 4 5 6 7 8 9 public public class // Context Objects Context context; MainActivity display_data; // Primitive Variables public public List<StudentInfo> productList; public public static static LayoutInflater inflater = null // DB Objects DBHelper db; public public StudentListAdapter(@NonNull Context context, int super super(context, resource, productList); this this.context = context; this this.productList = productList; db = new new DBHelper(context); display_data = (MainActivity) this inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public public StudentInfo getItem(int int position) { return return productList.get(position); } @NonNull @Override public public View getView(int int position, @Nullable View convertView, @NonNull ViewGroup parent ViewProHolder holder; if if (convertView == null null) { View view = inflater.inflate(R.layout.student_list_row, null holder = ViewProHolder.create((LinearLayout) view); view.setTag(holder); } else else { holder = (ViewProHolder) convertView.getTag(); } try try { final final StudentInfo item = getItem(position); holder.txtName.setText(item.getStudentName()); class StudentListAdapter extends extends ArrayAdapter<StudentInfo> { null; 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 int resource, List<StudentInfo> productList) { this.context; parent) { null);

  9. 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 holder.txtStatus.setText(item.getStudentResult()); holder.txtGrade.setText(item.getStudentGrade()); // Update Student Data holder.imgEdit.setOnClickListener(new @Override public public void void onClick(View v) { Intent intent = new 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 @Override public public void void onClick(View v) { try try { AlertDialog.Builder alertDialog = new // 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 public public void void onClick(DialogInterface dialog, int db.deleteStudentDetails(new display_data.bindStudentData(); } }); // Setting Negative "NO" Button alertDialog.setNegativeButton("NO", new public public void void onClick(DialogInterface dialog, int dialog.cancel(); } }); alertDialog.show(); } catch catch (Exception e) { Log.e("Error ", e.getMessage()); e.printStackTrace(); } } }); } catch catch (Exception e) { Log.e("Error in adapter: ", e.getMessage()); e.printStackTrace(); } return return holder.view; } public public static static class class ViewProHolder { public public final final LinearLayout view; TextView txtName, txtStatus, txtGrade; ImageView imgEdit; ImageView imgDelete; public public ViewProHolder(LinearLayout view, TextView tv_name, TextView tv_status, TextView im_icon, ImageView im_edit, ImageView im_delete) { this this.view = view; this this.txtName = tv_name; this this.txtStatus = tv_status; this this.txtGrade = im_icon; this this.imgEdit = im_edit; this this.imgDelete = im_delete; } public public static 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 return new new ViewProHolder(view, tv_name, tv_status, tv_grade, im_edit, im_delete); } } } new View.OnClickListener() { new Intent(context, AddUpdateDetailsActivity.class class); new View.OnClickListener() { new AlertDialog.Builder(context); new DialogInterface.OnClickListener() { int which) { new StudentInfo(item.getStudentId())); new DialogInterface.OnClickListener() { int which) { 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 5. Create Add / Update Activity 10. 10. Create new layout ?les under layout layout folder named activity_add_update.xml activity_add_update.xml. This the layout of Add / Update student data activity. activity_add_update.xml 1 <?xml version="1.0" encoding="utf-8"?>

  10. 2 3 4 5 6 7 8 9 <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" 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

  11. 92 93 94 95 android:padding="@dimen/_10sdp" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout> 11 11. Now create the AddUpdateDetailsActivity.java AddUpdateDetailsActivity.java ?le under ui ui package. Using this class we can perform Add / Update operations. AddUpdateDetailsActivity.java 1 2 3 4 5 6 7 8 9 public public class // Primitive Variables int int strId; String String strName, strStatus, strGrade; // DB Objects public public DBHelper db; // Widget GUI Declare TextView tvHeading; EditText etName, etStatus, etGrade; Button btnSave; @Override protected protected void void onCreate(Bundle savedInstanceState) { super super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_update); getSupportActionBar().setDisplayHomeAsUpEnabled(true getSupportActionBar().setDisplayShowHomeEnabled(true // Initialize Database Instance db = new 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 if (opration == 0) { tvHeading.setText("Add Student Data"); } else else { tvHeading.setText("Update Student Data"); } Intent intent = getIntent(); if if (intent != null 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 public boolean boolean onSupportNavigateUp() { onBackPressed(); return return true true; } @Override public public void void onClick(View v) { if if (v.getId() == R.id.btnSave) { if if (TextUtils.isEmpty(etName.getText())) { Toast.makeText(this } else else if if (TextUtils.isEmpty(etStatus.getText())) { Toast.makeText(this this, "Status is empty..!", Toast.LENGTH_SHORT).show(); } else else if if (TextUtils.isEmpty(etGrade.getText())) { Toast.makeText(this this, "Grade is empty..!", Toast.LENGTH_SHORT).show(); } else else { // get values from edittext strName = etName.getText().toString(); strStatus = etStatus.getText().toString(); strGrade = etGrade.getText().toString(); if if (opration == 0) { // Call insert method addDetails(); } else else { // Call update method updateDetails(); } } } class AddUpdateDetailsActivity extends extends AppCompatActivity implements implements View.OnClickListener { 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 true); true); this); this, "Name is empty..!", Toast.LENGTH_SHORT).show();

  12. 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 } // Call update method of SQLiteDatabase Class and close after private private void void updateDetails() { Intent intent = new new Intent(); try try { db.updateStudentDetails(new showRecords(); intent.putExtra("msg", "Details updated successfully..!"); setResult(1, intent); finish(); } catch catch (Exception e) { e.printStackTrace(); intent.putExtra("msg", "Update Failed..!"); setResult(0, intent); finish(); } } // Call insert method of SQLiteDatabase Class and close after public public void void addDetails() { Intent intent = new new Intent(); try try { db.addStudentDetails(new new StudentInfo(strName, strStatus, strGrade)); showRecords(); intent.putExtra("msg", "Details added successfully..!"); setResult(1, intent); finish(); } catch catch (Exception e) { e.printStackTrace(); intent.putExtra("msg", "added failed..!"); setResult(0, intent); finish(); } } // Reading all contacts public public void void showRecords() { Log.e("Reading ", "Reading all records.."); List<StudentInfo> studentInfos = db.getStudentDetails(); for for (StudentInfo cn : studentInfos) { String String log = "SId: " + cn.getStudentId() + " ,StudName: " + cn.getStudentName() + " StudStatus: " + cn.getStudentResult ) + " StudeGrade: " + cn.getStudentGrade(); // Writing records to log Log.e("Student: ", log); } } } new StudentInfo(strId, strName, strStatus, strGrade)); 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 6. Setup Main Activity 12. 12. Finally open MainActivity.java MainActivity.java and add following code into this. MainActivity will show you all the student records in form of list. Using Floating Action Button Floating Action Button you can add new student data in table. Edit EditButton Button allows to edit perticular student data from the list. By tapping Delete DeleteButton Button from the list you can delete particular student data. MainActivity.java 1 2 3 4 5 6 7 8 9 public public class // Primitive Variables public public static static int List<StudentInfo> mStudentInfoList; // Widget GUI Declare ListView lstView; FloatingActionButton fab; // DB Objects DBHelper db; // Adapter Object StudentListAdapter adapter; @Override protected protected void void onCreate(Bundle savedInstanceState) { super super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize Database Instance db = new new DBHelper(MainActivity.this); // Widget GUI Init class MainActivity extends extends AppCompatActivity { int opration; 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

  13. 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 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 ckLi s t ener ( new @Over r i de publ i c publ i c voi d voi d onCl i ck( Vi ew v) { I nt ent i nt ent = new opr at i on = 0; s t ar t Act 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 c publ i c voi d voi d bi ndSt udent Dat a( ) { m St udent I nf oLi s t = db. get St udent Det ai l s( ) ; adapt er = new new St udent Li s t Adapt er ( M ai nAct i vi t y. t hi s , R. l ayout . s t udent _l i s t _r ow, m St udent I nf oLi s t ) ; l s t Vi ew. s et Adapt er ( adapt er ) ; l s t Vi ew. s et Em pt yVi ew( f i ndVi ewByI d( R. i d. em pt y) ) ; } @Over r i de publ i c publ i c bool ean bool ean onCr eat eOpt i ons M enu( M enu m enu) { M enuI nf l at er i nf l at er = get M enuI nf l at er ( ) ; i nf l at er . i nf l at e( R. m enu. m enu, m enu) ; r et ur n r et ur n t r ue t r ue; } @Over r i de publ i c publ i c bool ean bool ean onOpt i ons I t em Sel ect ed( M enuI t em i t em ) { s wi t ch s wi t ch ( i t em . get I t em I d( ) ) { cas e cas e R. i d. addDet ai l s : / / Cal l f or add dat a I nt ent i nt ent = new new I nt ent ( get Appl i cat i onCont ext ( ) , AddUpdat eDet ai l s Act i vi t y. cl as s opr at i on = 0; s t ar t Act i vi t yFor Res ul t ( i nt ent , 1) ; r et ur n r et ur n t r ue t r ue; } r et ur n r et ur n s uper s uper . onOpt i ons I t em Sel ect ed( i t em ) ; } @Over r i de pr ot ect ed pr ot ect ed voi d voi d onAct i vi t yRes ul t ( i nt i nt r eques t Code, i nt s uper s uper . onAct i vi t yRes ul t ( r eques t Code, r es ul t Code, dat a) ; t r y t r y { i f i f ( r eques t Code == r es ul t Code) { r ef er s hLayout ( ) ; Toas t . m akeText ( get Appl i cat i onCont ext ( ) , " Res ul t s ucces s : " + dat a. get St r i ngExt r a( " m s g" ) , Toas t . LENGTH_SHO } el s e el s e{ St r i ng St r i ng s t r = dat a. get St r i ngExt r a( " m s g" ) ; i f i f ( Text Ut i l s . i s Em pt y( s t r ) ) { Toas t . m akeText ( get Appl i cat i onCont ext ( ) , " em pt y" , Toas t . LENGTH_SHORT) . s how( ) ; } el s e el s e { Log. e( " Er r or " , s t r ) ; Toas t . m akeText ( get Appl i cat i onCont ext ( ) , " Er r or : " + dat a. get St r i ngExt r a( " m s g" ) , Toas t . LENGTH_SHORT } } } cat ch cat ch ( Except i on e) { e. pr i nt St ackTr ace( ) ; } } publ i c publ i c voi d voi d r ef er s hLayout ( ) { i f i f ( Bui l d. VERSI ON. SDK_I NT >= 16) { t hi s t hi s . r ecr eat e( ) ; } el s e el s e { f i nal f 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 M ATI ON) ; t hi s t hi s . f i ni s h( ) ; t hi s t hi s . over r i dePendi ngTr ans i t i on( 0, 0) ; t hi s t hi s . s t ar t Act i vi t y( i nt ent ) ; t hi s t hi s . over r i dePendi ngTr ans i t i on( 0, 0) ; } } } new Vi ew. OnCl i ckLi s t ener ( ) { new I nt ent ( get Appl i cat i onCont ext ( ) , AddUpdat eDet ai l s Act i vi t y. cl as s cl as s ) ; cl as s ) ; i nt r es ul t Code, I nt ent dat a) { 100 101 102 103 104 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

More Related