Skip to content

Instantly share code, notes, and snippets.

@indywidualny
Created March 2, 2016 10:26
Show Gist options
  • Save indywidualny/4a1e435ab75228c8b8bf to your computer and use it in GitHub Desktop.
Save indywidualny/4a1e435ab75228c8b8bf to your computer and use it in GitHub Desktop.
Data source for Centrum.fm Android app
package org.indywidualni.centrumfm.util.database;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.preference.PreferenceManager;
import org.indywidualni.centrumfm.MyApplication;
import org.indywidualni.centrumfm.rest.model.Channel;
import org.indywidualni.centrumfm.rest.model.Schedule;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
public class DataSource {
private static volatile DataSource instance;
private SQLiteDatabase database;
private Random random = new Random();
private SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(MyApplication.getContextOfApplication());
private static final String[] NEWS_COLUMNS = {
MySQLiteHelper.COLUMN_NEWS_GUID, MySQLiteHelper.COLUMN_NEWS_LINK,
MySQLiteHelper.COLUMN_NEWS_TITLE, MySQLiteHelper.COLUMN_NEWS_DATE,
MySQLiteHelper.COLUMN_NEWS_DESCRIPTION, MySQLiteHelper.COLUMN_NEWS_CATEGORY,
MySQLiteHelper.COLUMN_NEWS_ENCLOSURE
};
private static final String[] SCHEDULE_COLUMNS = {
MySQLiteHelper.COLUMN_SCHEDULE_ID, MySQLiteHelper.COLUMN_SCHEDULE_NAME,
MySQLiteHelper.COLUMN_SCHEDULE_BAND, MySQLiteHelper.COLUMN_SCHEDULE_DAYS,
MySQLiteHelper.COLUMN_SCHEDULE_DATE, MySQLiteHelper.COLUMN_SCHEDULE_LENGTH
};
private DataSource() {
MySQLiteHelper dbHelper = new MySQLiteHelper();
database = dbHelper.getWritableDatabase();
}
public static DataSource getInstance() {
if (instance == null) {
synchronized (DataSource.class) {
if (instance == null)
instance = new DataSource();
}
}
return instance;
}
public List<Channel.Item> getAllNews() {
List<Channel.Item> allNews = new ArrayList<>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_NEWS,
NEWS_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Channel.Item item = cursorToNews(cursor);
allNews.add(item);
cursor.moveToNext();
}
cursor.close();
Collections.sort(allNews);
return allNews;
}
private Channel.Item cursorToNews(Cursor cursor) {
Channel.Item item = new Channel.Item();
item.setGuid(cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_NEWS_GUID)));
item.setLink(cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_NEWS_LINK)));
item.setTitle(cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_NEWS_TITLE)));
item.setDate(convertDate(cursor.getString(cursor.getColumnIndex(MySQLiteHelper
.COLUMN_NEWS_DATE))));
item.setDescription(cursor.getString(cursor.getColumnIndex(MySQLiteHelper
.COLUMN_NEWS_DESCRIPTION)));
item.setCategory(cursor.getString(cursor.getColumnIndex(MySQLiteHelper
.COLUMN_NEWS_CATEGORY)));
item.setEnclosureUrl(cursor.getString(cursor.getColumnIndex(MySQLiteHelper
.COLUMN_NEWS_ENCLOSURE)));
return item;
}
public void insertNews(List<Channel.Item> items) {
for (Channel.Item item : items) {
ContentValues cv = new ContentValues();
cv.put(MySQLiteHelper.COLUMN_NEWS_GUID, item.getGuid());
cv.put(MySQLiteHelper.COLUMN_NEWS_LINK, item.getLink());
cv.put(MySQLiteHelper.COLUMN_NEWS_TITLE, item.getTitle());
cv.put(MySQLiteHelper.COLUMN_NEWS_DATE, item.getPubDate());
cv.put(MySQLiteHelper.COLUMN_NEWS_DESCRIPTION, item.getDescription());
cv.put(MySQLiteHelper.COLUMN_NEWS_CATEGORY, categoryChooser(item.getCategories()));
cv.put(MySQLiteHelper.COLUMN_NEWS_ENCLOSURE, item.getEnclosureUrl());
database.insertWithOnConflict(MySQLiteHelper.TABLE_NEWS, null, cv,
SQLiteDatabase.CONFLICT_IGNORE);
}
trimNews();
}
private void trimNews() {
int maxNews = 10;
try { // just in case
maxNews = Integer.parseInt(preferences.getString("news_keep_max", "10"));
} catch (NumberFormatException e) {
e.printStackTrace();
}
// delete the oldest rows leaving the latest maxNews rows
database.execSQL("DELETE FROM " + MySQLiteHelper.TABLE_NEWS + " WHERE ROWID IN (" +
"SELECT ROWID FROM " + MySQLiteHelper.TABLE_NEWS +
" ORDER BY ROWID DESC LIMIT -1 OFFSET " + maxNews + ");");
}
/**
* Get rid of all the strings starting with the lower case, they're just tags.
* Pick a random category then.
*/
private String categoryChooser(List<String> list) {
List<String> categories = new ArrayList<>();
for (String s : list)
if (!Character.isLowerCase(s.charAt(0)))
categories.add(s);
return categories.get(random.nextInt(categories.size()));
}
private Date convertDate(String dateString) {
DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
Date date = new Date();
try {
date = df.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public void insertSchedule(List<Schedule.Event> items) {
database.delete(MySQLiteHelper.TABLE_SCHEDULE, null, null);
for (Schedule.Event item : items) {
ContentValues cv = new ContentValues();
cv.put(MySQLiteHelper.COLUMN_SCHEDULE_ID, item.getId());
cv.put(MySQLiteHelper.COLUMN_SCHEDULE_NAME, item.getName());
cv.put(MySQLiteHelper.COLUMN_SCHEDULE_BAND, item.getBand());
cv.put(MySQLiteHelper.COLUMN_SCHEDULE_DAYS, item.getWeekdays());
cv.put(MySQLiteHelper.COLUMN_SCHEDULE_DATE, item.getStartDate());
cv.put(MySQLiteHelper.COLUMN_SCHEDULE_LENGTH, item.getEventLength());
database.insertWithOnConflict(MySQLiteHelper.TABLE_SCHEDULE, null, cv,
SQLiteDatabase.CONFLICT_ROLLBACK);
}
}
public List<Schedule.Event> getSchedule() {
List<Schedule.Event> schedule = new ArrayList<>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_SCHEDULE,
SCHEDULE_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Schedule.Event item = cursorToSchedule(cursor);
schedule.add(item);
cursor.moveToNext();
}
cursor.close();
return schedule;
}
private Schedule.Event cursorToSchedule(Cursor cursor) {
Schedule.Event item = new Schedule.Event();
item.setId(cursor.getInt(cursor.getColumnIndex(MySQLiteHelper.COLUMN_SCHEDULE_ID)));
item.setName(cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_SCHEDULE_NAME)));
item.setBand(cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_SCHEDULE_BAND)));
item.setWeekdays(cursor.getString(cursor.getColumnIndex(MySQLiteHelper
.COLUMN_SCHEDULE_DAYS)));
item.setStartDate(cursor.getString(cursor.getColumnIndex(MySQLiteHelper
.COLUMN_SCHEDULE_DATE)));
item.setEventLength(cursor.getInt(cursor.getColumnIndex(MySQLiteHelper
.COLUMN_SCHEDULE_LENGTH)));
return item;
}
}
package org.indywidualni.centrumfm.util.database;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.indywidualni.centrumfm.MyApplication;
public class MySQLiteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "centrum.db";
private static final int DATABASE_VERSION = 7;
public static final String TABLE_NEWS = "News";
public static final String COLUMN_NEWS_GUID = "guid";
public static final String COLUMN_NEWS_LINK = "link";
public static final String COLUMN_NEWS_TITLE = "title";
public static final String COLUMN_NEWS_DATE = "pubDate";
public static final String COLUMN_NEWS_DESCRIPTION = "description";
public static final String COLUMN_NEWS_CATEGORY = "category";
public static final String COLUMN_NEWS_ENCLOSURE = "enclosure";
public static final String TABLE_SCHEDULE = "Schedule";
public static final String COLUMN_SCHEDULE_ID = "id";
public static final String COLUMN_SCHEDULE_NAME = "name";
public static final String COLUMN_SCHEDULE_BAND = "band";
public static final String COLUMN_SCHEDULE_DAYS = "weekdays";
public static final String COLUMN_SCHEDULE_DATE = "start";
public static final String COLUMN_SCHEDULE_LENGTH = "length";
public MySQLiteHelper() {
super(MyApplication.getContextOfApplication(), DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
Log.v("SQLiteDatabase", "Creating database");
database.execSQL("CREATE TABLE " + TABLE_NEWS + " (" +
COLUMN_NEWS_GUID + " TEXT PRIMARY KEY, " +
COLUMN_NEWS_LINK + " TEXT, " +
COLUMN_NEWS_TITLE + " TEXT, " +
COLUMN_NEWS_DATE + " TEXT, " +
COLUMN_NEWS_DESCRIPTION + " TEXT, " +
COLUMN_NEWS_CATEGORY + " TEXT, " +
COLUMN_NEWS_ENCLOSURE + " TEXT" +
");");
database.execSQL("CREATE TABLE " + TABLE_SCHEDULE + " (" +
COLUMN_SCHEDULE_ID + " INTEGER PRIMARY KEY, " +
COLUMN_SCHEDULE_NAME + " TEXT, " +
COLUMN_SCHEDULE_BAND + " TEXT, " +
COLUMN_SCHEDULE_DAYS + " TEXT, " +
COLUMN_SCHEDULE_DATE + " TEXT, " +
COLUMN_SCHEDULE_LENGTH + " INTEGER" +
");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWS + ";");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCHEDULE + ";");
onCreate(db);
}
}
@indywidualny
Copy link
Author

Get data:
List<Schedule.Event> eventList = DataSource.getInstance().getSchedule();

Insert data:
DataSource.getInstance().insertSchedule(eventList);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment