· 4 years ago · Jun 29, 2021, 06:32 PM
1package com.example.bibliotaph;
2
3import android.content.ContentValues;
4import android.content.Context;
5import android.database.Cursor;
6import android.database.sqlite.SQLiteDatabase;
7import android.database.sqlite.SQLiteOpenHelper;
8import android.util.Log;
9import com.example.bibliotaph.models.Article;
10import com.example.bibliotaph.params.AppGlobals;
11import java.util.ArrayList;
12
13public class DbHandler extends SQLiteOpenHelper {
14
15 public DbHandler(Context context) {
16 super(context, AppGlobals.DB_NAME, null, AppGlobals.DB_VERSION);
17 }
18
19 @Override
20 public void onCreate(SQLiteDatabase db) {
21 String create = "Create table if not exists " + AppGlobals.TABLE_NAME + "(" +
22 AppGlobals.KEY_NAME + " Varchar Primary key, " + AppGlobals.KEY_BODY +
23 " Text, " + AppGlobals.KEY_DATE + " Datetime)";
24 db.execSQL(create);
25 Log.i("database", "Database created");
26 }
27
28 @Override
29 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
30
31 }
32
33 public void addArticle(Article article) {
34 SQLiteDatabase db = this.getWritableDatabase();
35 ContentValues values = new ContentValues();
36 values.put(AppGlobals.KEY_NAME, article.getFileName());
37 values.put(AppGlobals.KEY_BODY, article.getTextBody());
38 values.put(AppGlobals.KEY_DATE, article.getDateAdded());
39 db.insert(AppGlobals.TABLE_NAME, null, values);
40 }
41
42 public ArrayList<Article> getAllArticles(int sortIndex) {
43 ArrayList<Article> articleList = new ArrayList<>();
44 SQLiteDatabase db = this.getReadableDatabase();
45 String select;
46
47 if(sortIndex == 0) {
48 select = "Select * from " + AppGlobals.TABLE_NAME
49 + " Order by " + AppGlobals.KEY_DATE + " Desc";
50 }
51 else {
52 select = "Select * from " + AppGlobals.TABLE_NAME
53 + " Order by Upper(" + AppGlobals.KEY_NAME + ")" + " Asc";
54 }
55
56 Cursor cursor = db.rawQuery(select, null);
57
58 if(cursor.moveToFirst()) {
59 do {
60 Article article = new Article();
61 article.setFileName(cursor.getString(0));
62 article.setTextBody(cursor.getString(1));
63 article.setDateAdded(cursor.getString(2));
64 articleList.add(article);
65 } while (cursor.moveToNext());
66 }
67 cursor.close();
68 return articleList;
69 }
70
71 public String getArticleBody(String articleName) {
72 SQLiteDatabase db = this.getReadableDatabase();
73 String select = "Select " + AppGlobals.KEY_BODY + " from " +
74 AppGlobals.TABLE_NAME + " where " + AppGlobals.KEY_NAME +
75 " = '" + articleName + "'";
76
77 Cursor cursor = db.rawQuery(select, null);
78 String textBody = null;
79 if(cursor.moveToFirst()) {
80 textBody = cursor.getString(0);
81 }
82 cursor.close();
83 return textBody;
84 }
85}
86