1 /* DatabaseManager.java
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, either version 3 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 package de.dhbwloe.campusapp.database;
17 import android.app.Activity;
18 import android.content.ContentValues;
19 import android.database.Cursor;
20 import android.database.sqlite.SQLiteDatabase;
22 import net.fortuna.ical4j.model.Component;
24 import java.util.ArrayList;
25 import java.util.Date;
27 import de.dhbwloe.campusapp.CampusAppContext;
28 import de.dhbwloe.campusapp.coursenames.CourseName;
29 import de.dhbwloe.campusapp.mensaplan.MensaTagesplan;
30 import de.dhbwloe.campusapp.news.NewsItem;
31 import de.dhbwloe.campusapp.search.SearchIndices;
32 import de.dhbwloe.campusapp.vorlesungen.CourseEvent;
33 import de.dhbwloe.campusapp.vorlesungen.CourseGroup;
36 * Created by pk910 on 19.01.2016.
38 public class DatabaseManager {
39 private static final String DATABASE_NAME = "DHBWLoe.CampusApp.db";
40 private static final int DATABASE_VERSION = 3; // Datenbank Version - muss bei strukturellen Anpassungen erhöht werden
42 private CampusAppContext AppContext;
43 private SQLiteDatabase database;
44 private NewsDatabaseHelper newsDBHelper;
45 private MensaplanDatabaseHelper mensaplanDBHelper;
46 private VorlesungsplanDatabaseHelper vorlesungsplanDBHelper;
49 public DatabaseManager(CampusAppContext context) {
53 private void openDatabase() {
57 database = AppContext.getMainActivity().openOrCreateDatabase(DATABASE_NAME, Activity.MODE_PRIVATE, null);
60 public void initializeDatabase() {
62 database.execSQL("CREATE TABLE IF NOT EXISTS Version(Version INT);");
64 // Abfragen der Datenbank Version
65 Cursor resultSet = database.rawQuery("Select * from Version", null);
67 if(resultSet.moveToFirst()) {
68 version = resultSet.getInt(0);
71 database.execSQL("INSERT INTO Version (Version) VALUES (0);");
75 if(version < DATABASE_VERSION) // Upgrade der Datenbank Struktur (oder auch Initialisierung)
76 upgradeTables(version, DATABASE_VERSION);
79 private void upgradeTables(int oldVersion, int newVersion) {
80 if(oldVersion == 0 && newVersion > 0) { // Initialisierung (noch keine Datenbank)
81 database.execSQL("CREATE TABLE IF NOT EXISTS RuntimeCache " +
86 "PRIMARY KEY (Reference)" +
88 database.execSQL("CREATE TABLE IF NOT EXISTS SearchIndex " +
93 "Description TEXT, " +
99 database.execSQL("CREATE TABLE IF NOT EXISTS CourseCalendar " +
101 "Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
102 "CourseName TEXT, " +
107 "EventTitle TEXT, " +
108 "EventLocation TEXT, " +
109 "EventStatus TEXT," +
111 "ExcludeDates TEXT," +
112 "CourseGroupId INT," +
113 "UNIQUE (CourseName, UniqueId)" +
115 database.execSQL("CREATE TABLE IF NOT EXISTS CourseCalendarEvent " +
120 "PRIMARY KEY (EventId, EventFrom, EventTo)" +
122 database.execSQL("CREATE INDEX CourseCalendarEventIdx ON CourseCalendarEvent (EventFrom, EventTo);");
123 database.execSQL("CREATE TABLE IF NOT EXISTS CourseCalendarGroup " +
125 "GroupId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
129 "UNIQUE (GroupName)" +
131 database.execSQL("CREATE INDEX CourseCalendarGroupIdx ON CourseCalendarGroup (CourseName, GroupName);");
133 // Mensa Karten History is this actually used?)
134 database.execSQL("CREATE TABLE IF NOT EXISTS NfcCardStore " +
138 "CardBalance INT, " +
139 "CardLastTransaction INT, " +
140 "PRIMARY KEY (CardId, UpdateTime)" +
144 database.execSQL("CREATE TABLE IF NOT EXISTS MensaPlan " +
151 "Additional TEXT, " +
153 "PriceStudents INT, " +
154 "PriceEmployees INT, " +
155 "PriceGuests INT, " +
156 "PriceSchool INT, " +
157 "PRIMARY KEY (PlanDate, MenuName)" +
161 database.execSQL("CREATE TABLE IF NOT EXISTS News " +
163 "Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
172 "Categories TEXT, " +
173 "UNIQUE(Source, UniqueId) " +
175 database.execSQL("CREATE INDEX NewsIdx ON News (Source, Time);");
177 if(oldVersion < 2 && newVersion >= 2) {
179 database.execSQL("ALTER TABLE CourseCalendarEvent ADD EventType INT;");
181 if(oldVersion < 3 && newVersion >= 3) {
183 database.execSQL("CREATE TABLE IF NOT EXISTS CourseNames " +
185 "CourseName TEXT, " +
190 if(oldVersion < 4 && newVersion >= 4) {
195 database.execSQL("UPDATE Version SET Version = " + Integer.toString(newVersion));
198 public void addSearchIndices(SearchIndices[] indices) {
199 // Hinzufügen oder Updaten mehrerer SearchIndice Objekte
201 for(int i = 0; i < indices.length; i++) {
202 String[] whereArgs = new String[] {
203 indices[i].getKeyName()
205 Cursor resultSet = database.rawQuery("SELECT UpdateTime FROM SearchIndex WHERE KeyName = ?", whereArgs);
206 if(resultSet.moveToFirst()) {
207 long updateTime = resultSet.getLong(0);
208 if (updateTime < indices[i].getUpdateTime()) {
210 database.rawQuery("DELETE FROM SearchIndex WHERE KeyName = ?", whereArgs);
217 ContentValues indexValues = new ContentValues();
218 indexValues.put("KeyName", indices[i].getKeyName());
219 indexValues.put("SearchText", indices[i].getKeyWords());
220 indexValues.put("SearchTitle", indices[i].getTitle());
221 indexValues.put("Description", indices[i].getDescription());
222 indexValues.put("StaticEntry", indices[i].getIsStatic() ? 1 : 0);
223 indexValues.put("UpdateTime", indices[i].getUpdateTime());
224 indexValues.put("TargetPage", indices[i].getTarget());
226 database.insertOrThrow("SearchIndex", null, indexValues);
227 } catch(Exception e) {
233 public SearchIndices[] performSearchRequest(String query, int maxResults) {
236 String[] whereArgs = new String[] {
239 Cursor resultSet = database.rawQuery("SELECT KeyName, SearchTitle, Description, StaticEntry, UpdateTime, TargetPage, SearchText FROM SearchIndex WHERE SearchText LIKE ? ORDER BY StaticEntry DESC, UpdateTime DESC", whereArgs);
240 ArrayList<SearchIndices> indices = new ArrayList<SearchIndices>();
241 if(resultSet.moveToFirst()) {
242 int[] columnIndexes = {
243 resultSet.getColumnIndex("KeyName"),
244 resultSet.getColumnIndex("SearchTitle"),
245 resultSet.getColumnIndex("Description"),
246 resultSet.getColumnIndex("StaticEntry"),
247 resultSet.getColumnIndex("UpdateTime"),
248 resultSet.getColumnIndex("TargetPage"),
249 resultSet.getColumnIndex("SearchText")
252 SearchIndices cIndices = new SearchIndices(resultSet.getString(columnIndexes[0]), (resultSet.getInt(columnIndexes[3]) == 1));
253 cIndices.setUpdateTime(resultSet.getLong(columnIndexes[4]));
254 cIndices.setTarget(resultSet.getString(columnIndexes[5]));
255 cIndices.addKeyWord(resultSet.getString(columnIndexes[6]));
256 cIndices.setTitle(resultSet.getString(columnIndexes[1]));
257 cIndices.setDescription(resultSet.getString(columnIndexes[2]));
258 indices.add(cIndices);
259 } while (resultSet.moveToNext() && indices.size() < maxResults);
263 SearchIndices[] indicesArr = new SearchIndices[indices.size()];
264 indicesArr = indices.toArray(indicesArr);
268 public void setRuntimeCache(String name, String value) {
269 // Simple cache for runtime options
271 long now = (new Date()).getTime() / 1000;
272 String[] whereArgs = new String[] {
275 Cursor resultSet = database.rawQuery("SELECT Value FROM RuntimeCache WHERE Reference = ?", whereArgs);
276 if(resultSet.moveToFirst()) {
277 if(resultSet.getString(0).equalsIgnoreCase(value))
280 ContentValues updateValues = new ContentValues();
281 updateValues.put("Value", value);
282 updateValues.put("LastUpdate", now);
284 database.update("RuntimeCache", updateValues, "Reference = ?", whereArgs);
285 } catch(Exception e) {
290 ContentValues indexValues = new ContentValues();
291 indexValues.put("Reference", name);
292 indexValues.put("Value", value);
293 indexValues.put("LastUpdate", now);
295 database.insertOrThrow("RuntimeCache", null, indexValues);
296 } catch(Exception e) {
303 public String getRuntimeCache(String name) {
306 String[] whereArgs = new String[] {
309 Cursor resultSet = database.rawQuery("SELECT Value FROM RuntimeCache WHERE Reference = ?", whereArgs);
310 if(resultSet.moveToFirst()) {
311 value = resultSet.getString(0);
317 public void addNfcCardData(NfcCardData nfcCardData) {
319 String[] whereArgs = new String[] {
320 Integer.toString(nfcCardData.getUniqueId()),
321 Long.toString(nfcCardData.getLastUpdate())
323 Cursor resultSet = database.rawQuery("SELECT CardBalance FROM NfcCardStore WHERE CardId = ? AND UpdateTime = ?", whereArgs);
324 if(resultSet.moveToFirst()) {
326 ContentValues updateValues = new ContentValues();
327 updateValues.put("CardBalance", nfcCardData.getBalance());
328 updateValues.put("CardLastTransaction", nfcCardData.getLastTransaction());
330 database.update("NfcCardStore", updateValues, "CardId = ? AND UpdateTime = ?", whereArgs);
331 } catch(Exception e) {
336 ContentValues indexValues = new ContentValues();
337 indexValues.put("CardId", nfcCardData.getUniqueId());
338 indexValues.put("UpdateTime", nfcCardData.getLastUpdate());
339 indexValues.put("CardBalance", nfcCardData.getBalance());
340 indexValues.put("CardLastTransaction", nfcCardData.getLastTransaction());
342 database.insertOrThrow("NfcCardStore", null, indexValues);
343 } catch(Exception e) {
350 public NfcCardData[] getNfcCardData(int lastLimit) {
355 String[] whereArgs = {
356 Integer.toString(lastLimit)
358 resultSet = database.rawQuery("SELECT CardId,UpdateTime,CardBalance,CardLastTransaction FROM NfcCardStore ORDER BY UpdateTime DESC LIMIT ?", whereArgs);
360 resultSet = database.rawQuery("SELECT CardId,UpdateTime,CardBalance,CardLastTransaction FROM NfcCardStore ORDER BY UpdateTime DESC", null);
361 ArrayList<NfcCardData> nfcCardDatas = new ArrayList<NfcCardData>();
362 if(resultSet.moveToFirst()) {
364 NfcCardData nfcCardData = new NfcCardData(resultSet.getInt(0), resultSet.getLong(1), resultSet.getInt(2), resultSet.getInt(3));
365 nfcCardDatas.add(nfcCardData);
366 } while (resultSet.moveToNext());
369 NfcCardData[] resultsArr = new NfcCardData[nfcCardDatas.size()];
370 resultsArr = nfcCardDatas.toArray(resultsArr);
374 public NfcCardData getLatestNfcCardData(int cardId) {
377 String[] whereArgs = {
378 Integer.toString(cardId)
380 Cursor resultSet = database.rawQuery("SELECT CardId,UpdateTime,CardBalance,CardLastTransaction FROM NfcCardStore WHERE CardId = ? ORDER BY UpdateTime DESC LIMIT 1", whereArgs);
381 NfcCardData nfcCardData = null;
382 if(resultSet.moveToFirst()) {
383 nfcCardData = new NfcCardData(resultSet.getInt(0), resultSet.getLong(1), resultSet.getInt(2), resultSet.getInt(3));
389 public CourseName[] getCourseNames() {
393 resultSet = database.rawQuery("SELECT CourseName, Status, LastUpdate FROM CourseNames ORDER BY CourseName ASC", null);
395 ArrayList<CourseName> courseNames = new ArrayList<CourseName>();
396 if(resultSet.moveToFirst()) {
398 CourseName cname = new CourseName(resultSet.getString(0), resultSet.getString(1), resultSet.getLong(2));
399 courseNames.add(cname);
400 } while (resultSet.moveToNext());
403 CourseName[] resultsArr = new CourseName[courseNames.size()];
404 resultsArr = courseNames.toArray(resultsArr);
408 public CourseName getLatestCourseName() {
410 CourseName lastCourse = null;
412 resultSet = database.rawQuery("SELECT CourseName, Status, LastUpdate FROM CourseNames ORDER BY LastUpdate DESC LIMIT 1", null);
414 if(resultSet.moveToFirst()) {
415 lastCourse = new CourseName(resultSet.getString(0), resultSet.getString(1), resultSet.getLong(2));
421 public void addCourseName(CourseName courseName) {
423 String[] whereArgs = new String[] {
426 Cursor resultSet = database.rawQuery("SELECT CourseName FROM CourseNames WHERE CourseName = ?", whereArgs);
427 if(resultSet.moveToFirst()) {
428 if(courseName.isActiveCourse()) {
430 ContentValues updateValues = new ContentValues();
431 updateValues.put("Status", courseName.getStatus());
432 updateValues.put("LastUpdate", courseName.getLastUpdate());
434 database.update("CourseNames", updateValues, "CourseName = ?", whereArgs);
435 } catch (Exception e) {
439 database.delete("CourseNames", "CourseName = ?", whereArgs);
441 } else if(courseName.isActiveCourse()) {
443 ContentValues indexValues = new ContentValues();
444 indexValues.put("CourseName", courseName.getName());
445 indexValues.put("Status", courseName.getStatus());
446 indexValues.put("LastUpdate", courseName.getLastUpdate());
448 database.insertOrThrow("CourseNames", null, indexValues);
449 } catch(Exception e) {
456 public boolean haveCourseName(String courseName) {
458 String[] whereArgs = new String[] {
461 Cursor resultSet = database.rawQuery("SELECT CourseName FROM CourseNames WHERE CourseName = ?", whereArgs);
463 if(resultSet.moveToFirst()) {
471 public void updateCourseCalendar(CourseEvent event, Component cevent) {
473 if(vorlesungsplanDBHelper == null)
474 vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
475 vorlesungsplanDBHelper.updateCourseCalendar(event, cevent);
478 public CourseEvent[] getCourseCalendarEvents(String coursename, long timeFrom, long timeTo) {
480 if(vorlesungsplanDBHelper == null)
481 vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
482 return vorlesungsplanDBHelper.getCourseCalendarEvents(coursename, timeFrom, timeTo);
485 public CourseEvent[] getCourseEventsByGroup(CourseGroup group) {
487 if(vorlesungsplanDBHelper == null)
488 vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
489 return vorlesungsplanDBHelper.getCourseEventsByGroup(group);
492 public CourseEvent[] getCourseCalendarTimetable(String coursename, long timeFrom, int days) {
494 if(vorlesungsplanDBHelper == null)
495 vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
496 return vorlesungsplanDBHelper.getCourseCalendarTimetable(coursename, timeFrom, days);
499 public CourseGroup getCourseGroup(int courseGroupId) {
501 if(vorlesungsplanDBHelper == null)
502 vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
503 return vorlesungsplanDBHelper.getCourseGroup(courseGroupId);
506 public CourseGroup getCourseGroup(String coursename, String groupname) {
508 if(vorlesungsplanDBHelper == null)
509 vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
510 return vorlesungsplanDBHelper.getCourseGroup(coursename, groupname);
513 public CourseGroup addCourseGroup(String coursename, String groupname) {
515 if(vorlesungsplanDBHelper == null)
516 vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
517 return vorlesungsplanDBHelper.addCourseGroup(coursename, groupname);
520 public CourseGroup[] getCourseGroups(String coursename, Date notBefore) {
522 if(vorlesungsplanDBHelper == null)
523 vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
524 return vorlesungsplanDBHelper.getCourseGroups(coursename, notBefore);
527 public CourseEvent[] getCourseExamEvents(String coursename, long timeFrom, long timeTo) {
529 if(vorlesungsplanDBHelper == null)
530 vorlesungsplanDBHelper = new VorlesungsplanDatabaseHelper(AppContext, database);
531 return vorlesungsplanDBHelper.getCourseExamEvents(coursename, timeFrom, timeTo);
534 public void updateMensaTagesplan(MensaTagesplan plan) {
536 if(mensaplanDBHelper == null)
537 mensaplanDBHelper = new MensaplanDatabaseHelper(AppContext, database);
538 mensaplanDBHelper.updateMensaTagesplan(plan);
541 public MensaTagesplan[] getMensaTagesplan(long timeFrom, long timeTo) {
543 if(mensaplanDBHelper == null)
544 mensaplanDBHelper = new MensaplanDatabaseHelper(AppContext, database);
545 return mensaplanDBHelper.getMensaTagesplan(timeFrom, timeTo);
548 public long[] getDaysWithPlanData(long timeFrom, long timeTo) {
550 if(mensaplanDBHelper == null)
551 mensaplanDBHelper = new MensaplanDatabaseHelper(AppContext, database);
552 return mensaplanDBHelper.getDaysWithPlanData(timeFrom, timeTo);
555 public long[] getWeeksWithPlanData(long timeFrom, long timeTo) {
557 if(mensaplanDBHelper == null)
558 mensaplanDBHelper = new MensaplanDatabaseHelper(AppContext, database);
559 return mensaplanDBHelper.getWeeksWithPlanData(timeFrom, timeTo);
562 public void updateNewsItem(NewsItem news) {
564 if(newsDBHelper == null)
565 newsDBHelper = new NewsDatabaseHelper(AppContext, database);
566 newsDBHelper.updateNewsItem(news);
569 public NewsItem[] getNewsItems(String source, long timeFrom, long timeTo) {
571 if(newsDBHelper == null)
572 newsDBHelper = new NewsDatabaseHelper(AppContext, database);
573 return newsDBHelper.getNewsItems(source, timeFrom, timeTo);