本文转自:http://instinctcoder.com/android-studio-sqlite-database-multiple-tables-example/
BY TAN WOON HOW · PUBLISHED JANUARY 29, 2016 · UPDATED MAY 6, 2016
In this tutorial we going to do a little complex SQL statement which I think will help you to further understand how to work with multiple tables in SQLite database.(Sorry, i don’t like things that are complicated too but when it come to more tables…Thing has to be a little bit complex then it’s only become make sense). And, we’ve a tutorial that helps readers who are new in SQLite database so I strongly suggest you to go through this tutorial. Tool Used
1. Android Studio 1.5.1
To Do
In this tutorial we will going to create a simple app that allow to Create, Retrieve, Update, and Delete, student records and will directly output the query’s result to Logcat’s window panel.
View Demo
Android Studio SQLite Database Multiple Tables Example
Table Structure
Sample Data
Before you find out, i’m getting the sample data from here :).
Screen Layout
From above image, these are few things we would like to show you
1. Display Student-Course-Grade – This button will show you how the INNER JOIN work
2. Display Course Name-Grade-Total – This button will show you how the COUNT, GROUP BY, ORDER BY work
3. COURSE NOT TAKE BY STUDENT – This button will show you how the LEFT OUTER JOIN work
4. FAIL STUDENT MAJOR IN ‘BU’ – This button will show you how to UPDATE 2 Tables In a Single Statement
5. DELETE ‘BU’ STUDENT FROM SCHOOL – This button will show you how the EXECUTE 2 DELETE Statements IN Transaction Block
Code The Layout
activity_main.xml
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 79 |
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Display Student-Course-Grade" android:id="@+id/btnStuCourseGrade" android:layout_below="@+id/textView" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Display Course Name-Grade-Total" android:id="@+id/btnCourseNameGradeTotal" android:layout_below="@+id/btnStuCourseGrade" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Course Not Taken By Student" android:id="@+id/btnCourseNotTakenByStudent" android:layout_below="@+id/btnCourseNameGradeTotal" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Fail Student Major In 'BU'" android:id="@+id/btnFail" android:layout_below="@+id/btnCourseNotTakenByStudent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="(Delete) KICK BU Student From School" android:id="@+id/btnDelete" android:layout_below="@+id/btnFail" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Reinsert All Sample Data" android:id="@+id/btnInsert" android:layout_below="@+id/btnDelete" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Check Result in Logcat's Debug Option" android:id="@+id/textView" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:textStyle="bold|italic" /> </RelativeLayout> |
Code
1. Let’s start create project, SQLiteDBMultiTbl. The setting of the project are show as below images which is quite straight forward.
2. Next, we’ll first create all packages as show in below image and then go through 1 by 1.
After all the packages has created as above image, please navigate to data > model. Inside this package will contains all the Classes/Schema that will use it to create table in SQLite database. Inside this package, add all classes name and code as below
Course.java
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 |
package com.instinctcoder.sqlitedbmultitbl.data.model; /** * Created by Tan on 1/26/2016. */ public class Course { public static final String TAG = Course.class.getSimpleName(); public static final String TABLE = "Course"; // Labels Table Columns names public static final String KEY_CourseId = "CourseId"; public static final String KEY_Name = "Name"; private String courseId; private String name; public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
Major.java
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 |
package com.instinctcoder.sqlitedbmultitbl.data.model; /** * Created by Tan on 1/26/2016. */ public class Major { public static final String TAG = Major.class.getSimpleName(); public static final String TABLE = "Major"; // Labels Table Columns names public static final String KEY_MajorId = "MajorId"; public static final String KEY_Name = "Name"; private String majorId; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMajorId() { return majorId; } public void setMajorId(String ref) { this.majorId = ref; } } |
Student.java
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 |
package com.instinctcoder.sqlitedbmultitbl.data.model; /** * Created by Tan on 1/26/2016. */ public class Student { public static final String TAG = Student.class.getSimpleName(); public static final String TABLE = "Student"; // Labels Table Columns names public static final String KEY_StudID = "StudentId"; public static final String KEY_Name = "Name"; public static final String KEY_MajorId = "MajorId"; private String ID ; private String name; private String majorId ; public String getStudentId() { return ID; } public void setStudentId(String ID) { this.ID = ID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMajor() { return majorId; } public void setMajor(String majorId) { this.majorId = majorId; } } |
StudentCourse.java
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 |
package com.instinctcoder.sqlitedbmultitbl.data.model; /** * Created by Tan on 1/27/2016. */ public class StudentCourse { public static final String TAG = StudentCourse.class.getSimpleName(); public static final String TABLE = "StudentCourse"; // Labels Table Columns names public static final String KEY_RunningID = "RunningID"; public static final String KEY_StudID = "StudentId"; public static final String KEY_CourseId = "CourseId"; public static final String KEY_Grade = "Grade"; public String studentId; public String courseId; public String grade; public String getStudentId() { return studentId; } public void setStudentId(String studentId) { this.studentId = studentId; } public String getCourseId() { return courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } } |
5. Let’s move on to data package, In order for us to create tables we need to use these classes SQLiteDatabase, SQLiteDatabase is the class for us to perform CRUD function, and SQLiteOpenHelper, SQLiteOpenHelper is a helper class to manage database creation and version management. We’ll create a class and name it DBHelper.java and paste the following contents.
DBHelper.java
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 |
package com.instinctcoder.sqlitedbmultitbl.data; /** * Created by Tan on 1/26/2016. */ import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.instinctcoder.sqlitedbmultitbl.app.App; import com.instinctcoder.sqlitedbmultitbl.data.model.Course; import com.instinctcoder.sqlitedbmultitbl.data.model.Major; import com.instinctcoder.sqlitedbmultitbl.data.model.Student; import com.instinctcoder.sqlitedbmultitbl.data.model.StudentCourse; import com.instinctcoder.sqlitedbmultitbl.data.repo.CourseRepo; import com.instinctcoder.sqlitedbmultitbl.data.repo.MajorRepo; import com.instinctcoder.sqlitedbmultitbl.data.repo.StudentCourseRepo; import com.instinctcoder.sqlitedbmultitbl.data.repo.StudentRepo; public class DBHelper extends SQLiteOpenHelper { //version number to upgrade database version //each time if you Add, Edit table, you need to change the //version number. private static final int DATABASE_VERSION =8; // Database Name private static final String DATABASE_NAME = "sqliteDBMultiTbl.db"; private static final String TAG = DBHelper.class.getSimpleName().toString(); public DBHelper( ) { super(App.getContext(), DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { //All necessary tables you like to create will create here db.execSQL(CourseRepo.createTable()); db.execSQL(StudentRepo.createTable()); db.execSQL(MajorRepo.createTable()); db.execSQL(StudentCourseRepo.createTable()); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, String.format("SQLiteDatabase.onUpgrade(%d -> %d)", oldVersion, newVersion)); // Drop table if existed, all data will be gone!!! db.execSQL("DROP TABLE IF EXISTS " + Course.TABLE); db.execSQL("DROP TABLE IF EXISTS " + Student.TABLE); db.execSQL("DROP TABLE IF EXISTS " + Major.TABLE); db.execSQL("DROP TABLE IF EXISTS " + StudentCourse.TABLE); onCreate(db); } } |
6. We’ll show you how to handle the database connection in better way in term of avoid any chances of memory leak and access to your android database in thread safe, blah, blah… In short, a better solution. We’re just trying to tell you D-R-Y and we know there are people out there already did their research and come out solution on handling the database connection and one of those is dmytrodanylyk. So, We as a programmer, need to keep in mind to D-R-Y. :). And now, in the same data package create a class name DatabaseManager.java and paste the following code
DatabaseManager.java
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 |
package com.instinctcoder.sqlitedbmultitbl.data; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Tan on 1/26/2016. */ public class DatabaseManager { private Integer mOpenCounter = 0; private static DatabaseManager instance; private static SQLiteOpenHelper mDatabaseHelper; private SQLiteDatabase mDatabase; public static synchronized void initializeInstance(SQLiteOpenHelper helper) { if (instance == null) { instance = new DatabaseManager(); mDatabaseHelper = helper; } } public static synchronized DatabaseManager getInstance() { if (instance == null) { throw new IllegalStateException(DatabaseManager.class.getSimpleName() + " is not initialized, call initializeInstance(..) method first."); } return instance; } public synchronized SQLiteDatabase openDatabase() { mOpenCounter+=1; if(mOpenCounter == 1) { // Opening new database mDatabase = mDatabaseHelper.getWritableDatabase(); } return mDatabase; } public synchronized void closeDatabase() { mOpenCounter-=1; if(mOpenCounter == 0) { // Closing database mDatabase.close(); } } } |
6. Now, let’s move on to the next package data > repo, the purpose of this package is for us to keep all database related query. And, We’ll begin with CourseRepo.java class
CourseRepo.java
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 |
package com.instinctcoder.sqlitedbmultitbl.data.repo; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.instinctcoder.sqlitedbmultitbl.data.DatabaseManager; import com.instinctcoder.sqlitedbmultitbl.data.model.Course; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by Tan on 1/26/2016. */ public class CourseRepo { private Course course; public CourseRepo(){ course= new Course(); } public static String createTable(){ return "CREATE TABLE " + Course.TABLE + "(" + Course.KEY_CourseId + " PRIMARY KEY ," + Course.KEY_Name + " TEXT )"; } public int insert(Course course) { int courseId; SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); ContentValues values = new ContentValues(); values.put(Course.KEY_CourseId, course.getCourseId()); values.put(Course.KEY_Name, course.getName()); // Inserting Row courseId=(int)db.insert(Course.TABLE, null, values); DatabaseManager.getInstance().closeDatabase(); return courseId; } public void delete( ) { SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); db.delete(Course.TABLE,null,null); DatabaseManager.getInstance().closeDatabase(); } } |
MajorRepo.java
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 |
package com.instinctcoder.sqlitedbmultitbl.data.repo; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.instinctcoder.sqlitedbmultitbl.data.DatabaseManager; import com.instinctcoder.sqlitedbmultitbl.data.model.Major; import java.util.List; /** * Created by Tan on 1/26/2016. */ public class MajorRepo { private Major major; public MajorRepo(){ major= new Major(); } public static String createTable(){ return "CREATE TABLE " + Major.TABLE + "(" + Major.KEY_MajorId + " TEXT PRIMARY KEY, " + Major.KEY_Name + " TEXT )"; } public int insert(Major major) { int majorId; SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); ContentValues values = new ContentValues(); values.put(Major.KEY_MajorId, major.getMajorId()); values.put(Major.KEY_Name, major.getName()); // Inserting Row majorId=(int)db.insert(Major.TABLE, null, values); DatabaseManager.getInstance().closeDatabase(); return majorId; } public void delete( ) { SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); db.delete(Major.TABLE, null,null); DatabaseManager.getInstance().closeDatabase(); } } |
StudentCourseRepo.java
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 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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
package com.instinctcoder.sqlitedbmultitbl.data.repo; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.instinctcoder.sqlitedbmultitbl.data.DatabaseManager; import com.instinctcoder.sqlitedbmultitbl.data.model.Course; import com.instinctcoder.sqlitedbmultitbl.data.model.Major; import com.instinctcoder.sqlitedbmultitbl.data.model.Student; import com.instinctcoder.sqlitedbmultitbl.data.model.StudentCourse; import com.instinctcoder.sqlitedbmultitbl.model.CourseGradeCount; import com.instinctcoder.sqlitedbmultitbl.model.CourseNotTakenByStudent; import com.instinctcoder.sqlitedbmultitbl.model.StudentCourseList; import java.util.ArrayList; import java.util.List; /** * Created by Tan on 1/27/2016. */ public class StudentCourseRepo { private final String TAG = StudentCourseRepo.class.getSimpleName().toString(); public StudentCourseRepo() { } private StudentCourse studentCourse; public static String createTable(){ return "CREATE TABLE " + StudentCourse.TABLE + "(" + StudentCourse.KEY_RunningID + " INTEGER PRIMARY KEY AUTOINCREMENT," + StudentCourse.KEY_StudID + " TEXT, " + StudentCourse.KEY_CourseId + " TEXT, " + StudentCourse.KEY_Grade + " TEXT )"; } public void insert(StudentCourse studentCourse) { SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); ContentValues values = new ContentValues(); values.put(studentCourse.KEY_StudID, studentCourse.getStudentId()); values.put(studentCourse.KEY_CourseId, studentCourse.getCourseId()); values.put(studentCourse.KEY_Grade, studentCourse.getGrade()); // Inserting Row db.insert(StudentCourse.TABLE, null, values); DatabaseManager.getInstance().closeDatabase(); } public void delete( ) { SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); db.delete(StudentCourse.TABLE, null, null); DatabaseManager.getInstance().closeDatabase(); } public List<StudentCourseList> getStudentCourse(){ StudentCourseList studentCourseList = new StudentCourseList(); List<StudentCourseList> studentCourseLists = new ArrayList<StudentCourseList>(); SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); String selectQuery = " SELECT Student." + Student.KEY_StudID + ", Student." + Student.KEY_Name + ", Course." + Course.KEY_CourseId + ", Course." + Course.KEY_Name + " As CourseName" + ", StuCourse." + StudentCourse.KEY_Grade + ", Major." + Major.KEY_MajorId + ", Major." + Major.KEY_Name + " As MajorName" + " FROM " + Student.TABLE + " As Student " + " INNER JOIN " + StudentCourse.TABLE + " StuCourse ON StuCourse." + StudentCourse.KEY_StudID + " = Student." + Student.KEY_StudID + " INNER JOIN " + Course.TABLE + " Course ON Course." + Course.KEY_CourseId + "= StuCourse." + StudentCourse.KEY_CourseId + " INNER JOIN " + Major.TABLE + " Major ON Major." + Major.KEY_MajorId + "= Student." + Student.KEY_MajorId ; Log.d(TAG, selectQuery); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { studentCourseList= new StudentCourseList(); studentCourseList.setStudentId(cursor.getString(cursor.getColumnIndex(Student.KEY_StudID))); studentCourseList.setStudentName(cursor.getString(cursor.getColumnIndex(Student.KEY_Name))); studentCourseList.setCourseID(cursor.getString(cursor.getColumnIndex(Course.KEY_CourseId))); studentCourseList.setCourseName(cursor.getString(cursor.getColumnIndex("CourseName"))); studentCourseList.setGrade(cursor.getString(cursor.getColumnIndex(StudentCourse.KEY_Grade))); studentCourseList.setMajorId(cursor.getString(cursor.getColumnIndex(Major.KEY_MajorId))); studentCourseList.setMajorName(cursor.getString(cursor.getColumnIndex("MajorName"))); studentCourseLists.add(studentCourseList); } while (cursor.moveToNext()); } cursor.close(); DatabaseManager.getInstance().closeDatabase(); return studentCourseLists; } //Show you the INNER JOIN //Only the matched records between tables will show, To join records from both tables, //we need to use "ON" keyword. //For example, to join StudentCourse and Course Table, Course.CourseId = StudentCourse.CourseId public List<CourseGradeCount> getCourseGradeCount(){ CourseGradeCount courseGradeCount = new CourseGradeCount(); List<CourseGradeCount> courseGradeCounts = new ArrayList<CourseGradeCount>(); SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); String selectQuery = " SELECT Course." + Course.KEY_CourseId + ", Course." + Course.KEY_Name + ", StudentCourse." + StudentCourse.KEY_Grade + ", COUNT(‘‘) AS Total" + " FROM " + StudentCourse.TABLE + " INNER JOIN " + Course.TABLE + " Course ON Course." + Course.KEY_CourseId + "= StudentCourse." + StudentCourse.KEY_CourseId + " GROUP BY Course." + Course.KEY_CourseId + ", Course." + Course.KEY_Name + " ORDER BY Course." + Course.KEY_Name ; Log.d(TAG, selectQuery); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { courseGradeCount= new CourseGradeCount(); courseGradeCount.setCourseID(cursor.getString(cursor.getColumnIndex(Course.KEY_CourseId))); courseGradeCount.setCourseName(cursor.getString(cursor.getColumnIndex(Course.KEY_Name))); courseGradeCount.setGrade(cursor.getString(cursor.getColumnIndex(StudentCourse.KEY_Grade))); courseGradeCount.setCount(cursor.getInt(cursor.getColumnIndex("Total"))); courseGradeCounts.add(courseGradeCount); } while (cursor.moveToNext()); } cursor.close(); DatabaseManager.getInstance().closeDatabase(); return courseGradeCounts; } //Show you the LEFT OUTER JOIN //The data from LEFT will be shown even not all records matched //In below query, Course will be the left table. //and if you like to see all data from Course, //remove this line WHERE RunningID IS NULL public List<CourseNotTakenByStudent> getCourseNotTakenByStudent(String studentId){ CourseNotTakenByStudent courseNotTakenByStudent = new CourseNotTakenByStudent(); List<CourseNotTakenByStudent> courseNotTakenByStudents = new ArrayList<CourseNotTakenByStudent>(); SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); String selectQuery = " SELECT Course." + Course.KEY_CourseId + ", Course." + Course.KEY_Name + " FROM " + Course.TABLE + " LEFT JOIN " +StudentCourse.TABLE + " ON Course." + Course.KEY_CourseId + "= StudentCourse." + StudentCourse.KEY_CourseId + " AND StudentCourse." + StudentCourse.KEY_StudID + "=?" + " WHERE RunningID IS NULL " ; Log.d(TAG, selectQuery); Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(studentId) }); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { courseNotTakenByStudent= new CourseNotTakenByStudent(); courseNotTakenByStudent.setCourseID(cursor.getString(cursor.getColumnIndex(Course.KEY_CourseId))); courseNotTakenByStudent.setCourseName(cursor.getString(cursor.getColumnIndex(Course.KEY_Name))); courseNotTakenByStudents.add(courseNotTakenByStudent); } while (cursor.moveToNext()); } cursor.close(); DatabaseManager.getInstance().closeDatabase(); return courseNotTakenByStudents; } //Show you update IN SINGLE statement with multiple tables public void failALLBUStudent(){ SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); String selectQuery = " UPDATE StudentCourse " + "SET Grade= (SELECT ‘F‘ FROM Student WHERE Student.StudentId=StudentCourse.StudentId) " + "WHERE EXISTS( " + "SELECT * " + "FROM Student " + "WHERE StudentCourse.StudentId=Student.StudentId AND MajorId=‘BU‘ " + ") " ; try{ db.beginTransaction(); Log.d(TAG, selectQuery); db.execSQL(selectQuery); db.setTransactionSuccessful(); } catch (Exception e) { Log.e(TAG, e.getMessage()); }finally { db.endTransaction(); } DatabaseManager.getInstance().closeDatabase(); } //Show you DELETE 2 statement execute in TRANSACTIONS //The reason we use TRANSACTIONS is because we need to make //sure data will delete properly so that if anything //happened during the execution of the statement is either COMPLETE or ROLLBACK //means either both tables data deleted or both tables not delete at all public void deleteAllBUStudent(){ SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); String selectQuery1 = " DELETE FROM StudentCourse WHERE StudentId IN (SELECT StudentId FROM Student WHERE MajorId=‘BU‘); " ; String selectQuery2 = " DELETE FROM Student WHERE MajorId=‘BU‘;" ; try{ db.beginTransaction(); Log.d(TAG, selectQuery1); Log.d(TAG, selectQuery2); db.execSQL(selectQuery1); db.execSQL(selectQuery2); db.setTransactionSuccessful(); } catch (Exception e) { Log.e(TAG, e.getMessage()); }finally { db.endTransaction(); } DatabaseManager.getInstance().closeDatabase(); } } |
StudentRepo.java
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 com.instinctcoder.sqlitedbmultitbl.data.repo; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.instinctcoder.sqlitedbmultitbl.data.DatabaseManager; import com.instinctcoder.sqlitedbmultitbl.data.model.Student; import java.util.List; /** * Created by Tan on 1/26/2016. */ public class StudentRepo { private Student student; public StudentRepo(){ student= new Student(); } public static String createTable(){ return "CREATE TABLE " + Student.TABLE + "(" + Student.KEY_StudID + " TEXT PRIMARY KEY ," + Student.KEY_Name + " TEXT, " + Student.KEY_MajorId + " TEXT )"; } public void insert(Student student) { SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); ContentValues values = new ContentValues(); values.put(Student.KEY_StudID, student.getStudentId()); values.put(Student.KEY_Name, student.getName()); values.put(Student.KEY_MajorId, student.getMajor()); // Inserting Row db.insert(Student.TABLE, null, values); DatabaseManager.getInstance().closeDatabase(); } public void delete( ) { SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); db.delete(Student.TABLE, null,null); DatabaseManager.getInstance().closeDatabase(); } } |
7. Let’s move on to App package, and app.java class under this package, this class will be the first file to be execute when the application running and it’s only execute once, the purpose of this file is to keep variable that we need to share across all the packages and these variables are mean to create one time and only has 1 instance in entire application life cycle, and we call this – Singleton.
app.java
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 |
package com.instinctcoder.sqlitedbmultitbl.app; import android.app.Application; import android.content.Context; import com.instinctcoder.sqlitedbmultitbl.data.DBHelper; import com.instinctcoder.sqlitedbmultitbl.data.DatabaseManager; /** * Created by Tan on 1/26/2016. */ public class App extends Application { private static Context context; private static DBHelper dbHelper; @Override public void onCreate() { super.onCreate(); context = this.getApplicationContext(); dbHelper = new DBHelper(); DatabaseManager.initializeInstance(dbHelper); } public static Context getContext(){ return context; } } |
8. We now move to the model package, all files under this package we serve as ViewModel which is use it to store data retrieve from database and then pass this view into activity to display. And then add the following class into this package
CourseGradeCount.java
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 |
package com.instinctcoder.sqlitedbmultitbl.model; /** * Created by Tan on 1/28/2016. */ public class CourseGradeCount { private String courseID; private String courseName; private String grade; private Integer count; public String getCourseID() { return courseID; } public void setCourseID(String courseID) { this.courseID = courseID; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } } |
CourseNotTakenByStudent.java
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 |
package com.instinctcoder.sqlitedbmultitbl.model; /** * Created by Tan on 1/28/2016. */ public class CourseNotTakenByStudent { private String courseID; private String courseName; public String getCourseID() { return courseID; } public void setCourseID(String courseID) { this.courseID = courseID; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } } |
StudentCourseList.java
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 |
package com.instinctcoder.sqlitedbmultitbl.model; /** * Created by Tan on 1/27/2016. */ public class StudentCourseList { private String studentId; private String studentName; private String courseID; private String courseName; private String MajorId; private String MajorName; public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } private String grade; public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getStudentId() { return studentId; } public void setStudentId(String studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getCourseID() { return courseID; } public void setCourseID(String courseID) { this.courseID = courseID; } public String getMajorId() { return MajorId; } public void setMajorId(String majorId) { MajorId = majorId; } public String getMajorName() { return MajorName; } public void setMajorName(String majorName) { MajorName = majorName; } } |
9. Now, go back to MainActivity.java. Paste the following code
MainActivity.java
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 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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 |
package com.instinctcoder.sqlitedbmultitbl; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import com.instinctcoder.sqlitedbmultitbl.data.model.Course; import com.instinctcoder.sqlitedbmultitbl.data.model.Major; import com.instinctcoder.sqlitedbmultitbl.data.model.Student; import com.instinctcoder.sqlitedbmultitbl.data.model.StudentCourse; import com.instinctcoder.sqlitedbmultitbl.data.repo.CourseRepo; import com.instinctcoder.sqlitedbmultitbl.data.repo.MajorRepo; import com.instinctcoder.sqlitedbmultitbl.data.repo.StudentCourseRepo; import com.instinctcoder.sqlitedbmultitbl.data.repo.StudentRepo; import com.instinctcoder.sqlitedbmultitbl.model.CourseGradeCount; import com.instinctcoder.sqlitedbmultitbl.model.CourseNotTakenByStudent; import com.instinctcoder.sqlitedbmultitbl.model.StudentCourseList; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { Button btnStuCourseGrade,btnCourseNameGradeTotal,btnCourseNotTakenByStudent,btnFail,btnDelete,btnInsert; public static final String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnStuCourseGrade= (Button)findViewById(R.id.btnStuCourseGrade); btnStuCourseGrade.setOnClickListener(this); btnCourseNameGradeTotal= (Button) findViewById(R.id.btnCourseNameGradeTotal); btnCourseNameGradeTotal.setOnClickListener(this); btnCourseNotTakenByStudent= (Button) findViewById(R.id.btnCourseNotTakenByStudent); btnCourseNotTakenByStudent.setOnClickListener(this); btnFail= (Button) findViewById(R.id.btnFail); btnFail.setOnClickListener(this); btnDelete= (Button) findViewById(R.id.btnDelete); btnDelete.setOnClickListener(this); btnInsert= (Button) findViewById(R.id.btnInsert); btnInsert.setOnClickListener(this); insertSampleData(); } private void insertSampleData(){ StudentRepo studentRepo = new StudentRepo(); CourseRepo courseRepo = new CourseRepo(); MajorRepo majorRepo = new MajorRepo(); StudentCourseRepo studentCourseRepo = new StudentCourseRepo(); studentCourseRepo.delete(); majorRepo.delete(); courseRepo.delete(); studentRepo.delete(); //Insert Sample data if the table is empty Course course = new Course(); course.setName("Intro to Computer Info Systems"); course.setCourseId("CIS11"); courseRepo.insert(course); course.setName("Internet User/Developer"); course.setCourseId("CIS44"); courseRepo.insert(course); course.setName("Oracle and SQL"); course.setCourseId("CIS50"); courseRepo.insert(course); course.setName("Visual Basic"); course.setCourseId("CIS56"); courseRepo.insert(course); course.setName("Intro to Management"); course.setCourseId("MAN11"); courseRepo.insert(course); course.setName("Marketing Principles"); course.setCourseId("MAR11"); courseRepo.insert(course); Major major = new Major(); major.setName("Business Administration"); major.setMajorId("BU"); majorRepo.insert(major); major.setName("Computer Information Systems"); major.setMajorId("CI"); majorRepo.insert(major); Student student = new Student(); student.setStudentId("1111"); student.setName("Stephen Daniels"); student.setMajor("BU"); studentRepo.insert(student); student.setStudentId("1212"); student.setName("Jennifer Ames"); student.setMajor("CI"); studentRepo.insert(student); student.setStudentId("2222"); student.setName("Carl Hersey"); student.setMajor("BU"); studentRepo.insert(student); student.setStudentId("2345"); student.setName("Mary Stanton"); student.setMajor("CI"); studentRepo.insert(student); student.setStudentId("3333"); student.setName("John Richards"); student.setMajor("CI"); studentRepo.insert(student); StudentCourse studentCourse = new StudentCourse(); studentCourse.setStudentId("1111"); studentCourse.setCourseId("CIS11"); studentCourse.setGrade("A-"); studentCourseRepo.insert(studentCourse); studentCourse.setStudentId("1111"); studentCourse.setCourseId("MAR11"); studentCourse.setGrade("A"); studentCourseRepo.insert(studentCourse); studentCourse.setStudentId("1111"); studentCourse.setCourseId("CIS44"); studentCourse.setGrade("A"); studentCourseRepo.insert(studentCourse); studentCourse.setStudentId("1212"); studentCourse.setCourseId("CIS44"); studentCourse.setGrade("A"); studentCourseRepo.insert(studentCourse); studentCourse.setStudentId("2222"); studentCourse.setCourseId("CIS44"); studentCourse.setGrade("A"); studentCourseRepo.insert(studentCourse); studentCourse.setStudentId("2222"); studentCourse.setCourseId("MAN11"); studentCourse.setGrade("A-"); studentCourseRepo.insert(studentCourse); studentCourse.setStudentId("3333"); studentCourse.setCourseId("CIS44"); studentCourse.setGrade("B"); studentCourseRepo.insert(studentCourse); studentCourse.setStudentId("3333"); studentCourse.setCourseId("CIS44"); studentCourse.setGrade("B"); studentCourseRepo.insert(studentCourse); studentCourse.setStudentId("3333"); studentCourse.setCourseId("CIS50"); studentCourse.setGrade("B+"); studentCourseRepo.insert(studentCourse); studentCourse.setStudentId("3333"); studentCourse.setCourseId("CIS56"); studentCourse.setGrade("A-"); studentCourseRepo.insert(studentCourse); studentCourse.setStudentId("2345"); studentCourse.setCourseId("CIS50"); studentCourse.setGrade("I"); studentCourseRepo.insert(studentCourse); } private void ListStudentWithCourseNameAndGrade(){ StudentCourseRepo studentCourseRepo = new StudentCourseRepo(); List<StudentCourseList> studentCourseLists= studentCourseRepo.getStudentCourse(); Log.d(TAG,String.format("%-11s", "Student ID") + String.format("%-35s", "Student Name") + String.format("%-7s", "Course") + String.format("%-31s", "Course Name") + String.format("%-6s", "Grade") + String.format("%-6s", "Major") + String.format("%-35s", "Major Name") ); Log.d(TAG,"============================================================="); for (int i= 0; i< studentCourseLists.size();i++ ){ Log.d(TAG, "0000000000".substring( studentCourseLists.get(i).getStudentId().length())+ studentCourseLists.get(i).getStudentId() + " " + String.format("%-35s", studentCourseLists.get(i).getStudentName())+ String.format("%-7s", studentCourseLists.get(i).getCourseID())+ String.format("%-31s", studentCourseLists.get(i).getCourseName())+ String.format("%-6s", studentCourseLists.get(i).getGrade())+ String.format("%-6s", studentCourseLists.get(i).getMajorId())+ String.format("%-35s", studentCourseLists.get(i).getMajorName()) ); } Log.d(TAG,"============================================================="); } private void ListCourseNameAndGradeCount(){ StudentCourseRepo studentCourseRepo = new StudentCourseRepo(); List<CourseGradeCount> courseGradeCounts= studentCourseRepo.getCourseGradeCount(); Log.d(TAG,String.format("%-7s", "Course") + String.format("%-31s", "Course Name") + String.format("%-6s", "Grade") + String.format("%-5s", "Total") ); Log.d(TAG,"============================================================="); for (int i= 0; i< courseGradeCounts.size();i++ ){ Log.d(TAG,String.format("%-7s", courseGradeCounts.get(i).getCourseID())+ String.format("%-31s", courseGradeCounts.get(i).getCourseName()) + String.format("%-6s", courseGradeCounts.get(i).getGrade()) + String.format("%-5s", courseGradeCounts.get(i).getCount())); } Log.d(TAG,"============================================================="); } private void ListCourseNotTakenByStudent(){ StudentCourseRepo studentCourseRepo = new StudentCourseRepo(); List<CourseNotTakenByStudent> courseGradeCounts= studentCourseRepo.getCourseNotTakenByStudent("1212"); Log.d(TAG,"Course Not taken By Student ID = 1212 (Jennifer Ames )") ; Log.d(TAG, String.format("%-7s", "Course") + String.format("%-31s", "Course Name")); Log.d(TAG,"============================================================="); for (int i= 0; i< courseGradeCounts.size();i++ ){ Log.d(TAG,String.format("%-7s", courseGradeCounts.get(i).getCourseID())+ String.format("%-31s", courseGradeCounts.get(i).getCourseName())); } Log.d(TAG,"============================================================="); } private void failAllBUStudent(){ StudentCourseRepo studentCourseRepo = new StudentCourseRepo(); studentCourseRepo.failALLBUStudent(); } private void deleteAllBUStudent(){ StudentCourseRepo studentCourseRepo = new StudentCourseRepo(); studentCourseRepo.deleteAllBUStudent(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View view) { if (view ==findViewById(R.id.btnStuCourseGrade)){ ListStudentWithCourseNameAndGrade(); }else if (view ==findViewById(R.id.btnCourseNameGradeTotal)){ ListCourseNameAndGradeCount(); }else if (view ==findViewById(R.id.btnCourseNotTakenByStudent)){ ListCourseNotTakenByStudent(); }else if (view ==findViewById(R.id.btnFail)){ failAllBUStudent(); }else if (view ==findViewById(R.id.btnDelete)) { deleteAllBUStudent(); }else if (view ==findViewById(R.id.btnInsert)) { insertSampleData(); } } } |
10. You may have question, How the IDE know need to execute App >app.java first? Good question!, They won’t know unless we configure this in app> src > main > AndroidManifest.xml and add the highlighted line as shown below
AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.instinctcoder.sqlitedbmultitbl" > <application android:name=".app.App" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
OK, That’s all for this tutorial and you will see result as above video if everything went smooth. A’m i confuse you? :). Please feel free to comment.