首页 技术 正文
技术 2022年11月14日
0 收藏 576 点赞 3,193 浏览 44566 个字

本文转自: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

Download Code

Android Studio SQLite Database Multiple Tables Example

Table Structure
[转]Android Studio SQLite Database Multiple Tables Example

Sample Data
[转]Android Studio SQLite Database Multiple Tables Example

Before you find out, i’m getting the sample data from here :).

Screen Layout

[转]Android Studio SQLite Database Multiple Tables Example
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

  

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 <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 &apos;BU&apos;”        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&apos;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.

[转]Android Studio SQLite Database Multiple Tables Example[转]Android Studio SQLite Database Multiple Tables Example[转]Android Studio SQLite Database Multiple Tables Example[转]Android Studio SQLite Database Multiple Tables Example

2. Next, we’ll first create all packages as show in below image and then go through 1 by 1.
[转]Android Studio SQLite Database Multiple Tables Example

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

  

123456789101112131415161718192021222324252627282930313233 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

  

1234567891011121314151617181920212223242526272829303132 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

  

12345678910111213141516171819202122232425262728293031323334353637383940414243 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

  

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 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

  

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 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

  

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 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

  

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 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

  

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 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

  

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253 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

  

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 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

  

123456789101112131415161718192021222324252627282930 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

  

1234567891011121314151617181920212223242526272829303132333435363738394041424344 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

  

12345678910111213141516171819202122232425 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

  

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 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

  

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332 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

  

12345678910111213141516171819202122 <?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.

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,556
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,405
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898