BD dividida: maestro (asset read-only, refrescado por user_version) + user.db (frasesG/frasesFav); migración one-shot de database.db con .bak; queries parametrizadas; strings a recursos; OnBackPressedDispatcher
This commit is contained in:
1 parent
6f7bfaff9c
commit
a003a94e7a
7 files changed
+377
-236
No files matched your search
Binary file not shown.
@@ -1,217 +1,128 @@
|
||||
package com.jkanetwork.st.calendariodefrases;
|
||||
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.database.Cursor;
|
||||
import android.database.sqlite.SQLiteDatabase;
|
||||
import android.database.sqlite.SQLiteOpenHelper;
|
||||
import android.util.Log;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Locale;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
|
||||
public class DatabaseHelper extends SQLiteOpenHelper {
|
||||
private static final int DATABASE_VERSION = 12;
|
||||
private static final String DATABASE_NAME = "database.db";
|
||||
private final Context contextdb;
|
||||
/**
|
||||
* Gestor de las dos bases de datos:
|
||||
*
|
||||
* - frases.db (assets): BD maestra de frases y autores. Read-only, se
|
||||
* recopia desde el asset cuando su user_version sube (nueva versión de
|
||||
* la app con contenido nuevo). El contenido no se modifica en runtime.
|
||||
*
|
||||
* - user.db: datos del usuario (día->frase asignada y favoritos). Se crea
|
||||
* vacía y solo la app la toca. Las actualizaciones del maestro JAMÁS
|
||||
* la afectan.
|
||||
*
|
||||
* Migración one-shot: si existe la antigua database.db (todo mezclado),
|
||||
* se vuelcan frasesFav y frasesG a user.db y la vieja queda como .bak.
|
||||
*
|
||||
* El maestro se regenera con tools/build_master_db.py desde res/raw
|
||||
* (fuente editable); al cambiar el contenido se sube MASTER_DB_VERSION
|
||||
* en el script.
|
||||
*/
|
||||
public class DatabaseHelper {
|
||||
|
||||
private static final String TAG = "DatabaseHelper";
|
||||
private static final String LEGACY_DB_NAME = "database.db";
|
||||
private static final String USER_DB_NAME = "user.db";
|
||||
private static final int USER_DB_VERSION = 1;
|
||||
|
||||
private final Context context;
|
||||
private final SQLiteDatabase masterDb;
|
||||
private final SQLiteDatabase userDb;
|
||||
|
||||
/* Versión del asset leída una vez por proceso (el asset no cambia en caliente) */
|
||||
private static Integer cachedAssetVersion;
|
||||
|
||||
public DatabaseHelper(Context context) {
|
||||
super(context, DATABASE_NAME, null, DATABASE_VERSION);
|
||||
contextdb = context;
|
||||
this.context = context.getApplicationContext();
|
||||
this.masterDb = openMaster();
|
||||
this.userDb = new UserDbOpenHelper(this.context).getWritableDatabase();
|
||||
migrateLegacyIfNeeded();
|
||||
}
|
||||
|
||||
/** Return the sentence passing the ID of it */
|
||||
String getFraseFromID(int IDF){
|
||||
SQLiteDatabase db = this.getWritableDatabase();
|
||||
String sentence;
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* BD maestra (read-only, copia del asset) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
if (IDF == 0){return "No hay más frases disponibles...";}
|
||||
else if (IDF == -1){return "No puedes ver aún esta frase";}
|
||||
else if (IDF == -2){return "A ocurrido un error";}
|
||||
else { //If there is a sentence
|
||||
private SQLiteDatabase openMaster() {
|
||||
File dbFile = context.getDatabasePath("frases_master.db");
|
||||
if (!dbFile.exists() || getFileVersion(dbFile) < assetVersion()) {
|
||||
copyAsset("frases.db", dbFile);
|
||||
}
|
||||
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
|
||||
}
|
||||
|
||||
private int assetVersion() {
|
||||
if (cachedAssetVersion != null) {
|
||||
return cachedAssetVersion;
|
||||
}
|
||||
File tmp = new File(context.getCacheDir(), "frases_asset_probe.db");
|
||||
try {
|
||||
Cursor c = db.rawQuery("SELECT Frase FROM frases WHERE _id = '" + IDF + "'", null);
|
||||
c.moveToFirst();
|
||||
sentence = c.getString(0);
|
||||
c.close();
|
||||
} catch (Exception e) {
|
||||
Log.e("Database", e.toString());
|
||||
sentence = "Error al buscar la frase";
|
||||
}
|
||||
return sentence;
|
||||
copyAsset("frases.db", tmp);
|
||||
cachedAssetVersion = getFileVersion(tmp);
|
||||
} finally {
|
||||
tmp.delete();
|
||||
}
|
||||
return cachedAssetVersion;
|
||||
}
|
||||
|
||||
String getAutorFromID(int IDF){
|
||||
SQLiteDatabase db = this.getWritableDatabase();
|
||||
String sentence;
|
||||
|
||||
if (IDF <= 0){return "";}
|
||||
else { //If there is a sentence
|
||||
private static int getFileVersion(File dbFile) {
|
||||
SQLiteDatabase db = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
|
||||
try {
|
||||
Cursor c = db.rawQuery("SELECT Autor FROM autores a WHERE _id=(SELECT AutorID from frases WHERE _id='"+ IDF + "')",null);
|
||||
c.moveToFirst();
|
||||
sentence = c.getString(0);
|
||||
c.close();
|
||||
} catch (Exception e) {
|
||||
Log.e("Database", Objects.requireNonNull(e.getMessage()));
|
||||
sentence = "";
|
||||
}
|
||||
return sentence;
|
||||
return db.getVersion();
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** get fav or a IDFrase */
|
||||
Integer getFav(int IDF){
|
||||
SQLiteDatabase db = this.getWritableDatabase();
|
||||
private void copyAsset(String assetName, File dest) {
|
||||
try {
|
||||
Cursor query = db.rawQuery("SELECT IDFrase FROM frasesFav WHERE IDFrase = '"+IDF+"'", null);
|
||||
Integer ret = query.getCount(); //There is integer because getCount is
|
||||
query.close();
|
||||
return ret;
|
||||
}catch(Exception e){
|
||||
Log.e("Database",e.toString());
|
||||
return 0; //If error, better return not fav
|
||||
dest.getParentFile().mkdirs();
|
||||
try (InputStream in = context.getAssets().open(assetName);
|
||||
OutputStream out = new FileOutputStream(dest)) {
|
||||
byte[] buf = new byte[8192];
|
||||
int n;
|
||||
while ((n = in.read(buf)) > 0) {
|
||||
out.write(buf, 0, n);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "copyAsset " + assetName + ": " + e);
|
||||
throw new RuntimeException("No se pudo copiar " + assetName, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Add a sentence as favorite */
|
||||
void addFav(int IDF){
|
||||
SQLiteDatabase db = this.getWritableDatabase();
|
||||
try{
|
||||
db.execSQL("INSERT INTO frasesFav VALUES('"+IDF+"')");
|
||||
}catch(Exception e){
|
||||
Log.e("Database",e.toString());
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* BD de usuario */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
private static class UserDbOpenHelper extends SQLiteOpenHelper {
|
||||
UserDbOpenHelper(Context context) {
|
||||
super(context, USER_DB_NAME, null, USER_DB_VERSION);
|
||||
}
|
||||
}
|
||||
|
||||
/** Del a favorite sentence */
|
||||
void delFav(int IDF){
|
||||
SQLiteDatabase db = this.getWritableDatabase();
|
||||
try{
|
||||
db.execSQL("DELETE FROM frasesFav WHERE IDFrase='"+IDF+"'");
|
||||
}catch(Exception e){
|
||||
Log.e("Database",e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns ID from a day X sentence, if possible */
|
||||
int getIDFraseDay(int year,int month,int dayOfMonth){
|
||||
Calendar cal = Calendar.getInstance();
|
||||
try {
|
||||
int ret;
|
||||
SQLiteDatabase db = this.getWritableDatabase();
|
||||
|
||||
/* For ever have two digits month and day */
|
||||
String sYear = Integer.toString(year);
|
||||
String sMonth = String.format("%02d", month); /* month selected */
|
||||
String sDay = String.format("%02d", dayOfMonth);/* day selected */
|
||||
|
||||
/* Same for calendar day */
|
||||
String cYear = Integer.toString(cal.get(Calendar.YEAR));
|
||||
String cMonth; /* Calendar month */
|
||||
String cDay; /* Calendar day */
|
||||
if ((cal.get(Calendar.MONTH)+1) < 10) {
|
||||
cMonth = "0" + (cal.get(Calendar.MONTH)+1);
|
||||
}else{
|
||||
cMonth = Integer.toString(cal.get(Calendar.MONTH)+1);
|
||||
}
|
||||
if (cal.get(Calendar.DAY_OF_MONTH) < 10) {
|
||||
cDay = "0" + (cal.get(Calendar.DAY_OF_MONTH));
|
||||
}else{
|
||||
cDay = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
String diaArg = sYear+sMonth+sDay; //Dia pasado a string yyyymmdd
|
||||
String diaAct = cYear+cMonth+cDay;
|
||||
Cursor query = db.rawQuery("SELECT IDFrase FROM frasesG WHERE Tday = '"+diaArg+"'", null);
|
||||
if(query.getCount() != 0) {
|
||||
query.moveToFirst();
|
||||
ret = query.getInt(0);
|
||||
query.close();
|
||||
return ret;
|
||||
//Else for make sentence if there is today or someday before has a sentence (This is possible if app was installed but not opened)
|
||||
}else if ((Integer.decode(diaArg) < Integer.decode(diaAct) && db.rawQuery("SELECT IDFrase FROM frasesG WHERE Tday < '"+diaArg+"'", null).getCount() > 0) || ( Integer.decode(diaArg).equals(Integer.decode(diaAct)) ) ) {
|
||||
//}else{ //Make sentence all times (DEBUG)
|
||||
try {
|
||||
query = db.rawQuery("SELECT _id FROM frases WHERE _id NOT IN (SELECT IDFrase FROM frasesG) ORDER BY RANDOM() LIMIT 1", null);
|
||||
query.moveToFirst();
|
||||
db.rawQuery("INSERT INTO frasesG (Tday,IDFrase) VALUES('" + diaArg + "','" + query.getString(0) + "')", null).moveToFirst();
|
||||
ret = query.getInt(0);
|
||||
query.close();
|
||||
return ret;
|
||||
} catch (Exception e) {
|
||||
return 0; //0 its no more sentences
|
||||
}
|
||||
}else{ //Not today, do not make one
|
||||
return -1; //-1 its day not accesible now
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e("Database",e.toString());
|
||||
return -2; //BUG
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns ID of today's sentence */
|
||||
Integer getIDFraseHoy(){
|
||||
Calendar cal = Calendar.getInstance();
|
||||
//Month + 1 because Android starts with month=0
|
||||
return getIDFraseDay(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH)+1,cal.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
/** Returns an array of favorite IDs */
|
||||
Integer[] getIDFavs(){
|
||||
SQLiteDatabase db = this.getWritableDatabase();
|
||||
List<Integer> a = new ArrayList<>();
|
||||
|
||||
Cursor c = db.rawQuery("SELECT IDFrase FROM frasesFav",null);
|
||||
|
||||
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
|
||||
a.add(c.getInt(0));
|
||||
}
|
||||
|
||||
Integer[] Favorites = new Integer[a.size()];
|
||||
a.toArray(Favorites);
|
||||
c.close();
|
||||
return Favorites;
|
||||
}
|
||||
|
||||
/** Returns an array of favorite IDs */
|
||||
String[] getAllDaysYet(){
|
||||
SQLiteDatabase db = this.getWritableDatabase();
|
||||
List<String> a = new ArrayList<>();
|
||||
|
||||
Cursor c = db.rawQuery("SELECT Tday FROM frasesG",null);
|
||||
|
||||
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
|
||||
a.add(c.getString(0));
|
||||
}
|
||||
|
||||
String[] Favorites = new String[a.size()];
|
||||
a.toArray(Favorites);
|
||||
c.close();
|
||||
return Favorites;
|
||||
}
|
||||
|
||||
|
||||
/* Here Startup of database. When changes, change number up in class */
|
||||
|
||||
@Override
|
||||
public void onCreate(SQLiteDatabase db) {
|
||||
db.execSQL("CREATE TABLE frases (" +
|
||||
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
||||
"`Frase` TEXT NOT NULL UNIQUE," +
|
||||
"`AutorID` INTEGER" +
|
||||
")");
|
||||
db.execSQL("CREATE TABLE autores (" +
|
||||
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
||||
"`Autor` TEXT UNIQUE" +
|
||||
")");
|
||||
db.execSQL("CREATE TABLE frasesG (" +
|
||||
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
||||
"`Tday` TEXT NOT NULL UNIQUE," +
|
||||
@@ -220,56 +131,212 @@ public class DatabaseHelper extends SQLiteOpenHelper {
|
||||
db.execSQL("CREATE TABLE frasesFav (" +
|
||||
"`IDFrase` INTEGER NOT NULL UNIQUE" +
|
||||
")");
|
||||
|
||||
String[] queries = readSqldata("Frases").split("\\|");
|
||||
for(String query : queries){
|
||||
db.execSQL(query);
|
||||
}
|
||||
//db.execSQL(readSqldata("Frases"));
|
||||
db.execSQL(readSqldata("Autores"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
|
||||
db.execSQL("DROP TABLE frases");
|
||||
db.execSQL("DROP TABLE autores");
|
||||
db.execSQL("CREATE TABLE frases (" +
|
||||
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
||||
"`Frase` TEXT NOT NULL UNIQUE," +
|
||||
"`AutorID` INTEGER" +
|
||||
")");
|
||||
db.execSQL("CREATE TABLE autores (" +
|
||||
"`_id` INTEGER PRIMARY KEY AUTOINCREMENT," +
|
||||
"`Autor` TEXT UNIQUE" +
|
||||
")");
|
||||
String[] queries = readSqldata("Frases").split("\\|");
|
||||
for(String query : queries){
|
||||
db.execSQL(query);
|
||||
// v1: sin cambios aún
|
||||
}
|
||||
db.execSQL(readSqldata("Autores"));
|
||||
}
|
||||
|
||||
private String readSqldata(String str){
|
||||
//getting the file
|
||||
InputStream inputStream;
|
||||
if (str.equals("Frases")) {
|
||||
inputStream = contextdb.getResources().openRawResource(R.raw.sqlfrases);
|
||||
}else{
|
||||
inputStream = contextdb.getResources().openRawResource(R.raw.sqlautores);
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Migración desde la BD mezclada antigua (one-shot) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
private void migrateLegacyIfNeeded() {
|
||||
File legacy = context.getDatabasePath(LEGACY_DB_NAME);
|
||||
if (!legacy.exists()) {
|
||||
return;
|
||||
}
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
try {
|
||||
int i = inputStream.read();
|
||||
while (i != -1) {
|
||||
byteArrayOutputStream.write(i);
|
||||
i = inputStream.read();
|
||||
SQLiteDatabase old = SQLiteDatabase.openDatabase(legacy.getPath(), null, SQLiteDatabase.OPEN_READONLY);
|
||||
try {
|
||||
try (Cursor c = old.rawQuery("SELECT IDFrase FROM frasesFav", null)) {
|
||||
while (c.moveToNext()) {
|
||||
ContentValues cv = new ContentValues();
|
||||
cv.put("IDFrase", c.getInt(0));
|
||||
userDb.insertWithOnConflict("frasesFav", null, cv, SQLiteDatabase.CONFLICT_IGNORE);
|
||||
}
|
||||
inputStream.close();
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return byteArrayOutputStream.toString();
|
||||
try (Cursor c = old.rawQuery("SELECT Tday, IDFrase FROM frasesG", null)) {
|
||||
while (c.moveToNext()) {
|
||||
ContentValues cv = new ContentValues();
|
||||
cv.put("Tday", c.getString(0));
|
||||
cv.put("IDFrase", c.getInt(1));
|
||||
userDb.insertWithOnConflict("frasesG", null, cv, SQLiteDatabase.CONFLICT_IGNORE);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
old.close();
|
||||
}
|
||||
/* La vieja se conserva como .bak; si ya había un bak, gana la nueva */
|
||||
File bak = new File(legacy.getPath() + ".bak");
|
||||
if (bak.exists()) {
|
||||
bak.delete();
|
||||
}
|
||||
if (!legacy.renameTo(bak)) {
|
||||
legacy.delete();
|
||||
}
|
||||
Log.i(TAG, "Migrada " + LEGACY_DB_NAME + " -> " + USER_DB_NAME);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "migrateLegacy: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Queries públicas */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** Return the sentence passing the ID of it */
|
||||
public String getFraseFromID(int IDF) {
|
||||
if (IDF == 0) return "No hay más frases disponibles...";
|
||||
if (IDF == -1) return "No puedes ver aún esta frase";
|
||||
if (IDF == -2) return "A ocurrido un error";
|
||||
try (Cursor c = masterDb.rawQuery("SELECT Frase FROM frases WHERE _id = ?",
|
||||
new String[]{String.valueOf(IDF)})) {
|
||||
return c.moveToFirst() ? c.getString(0) : "Error al buscar la frase";
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "getFrase: " + e);
|
||||
return "Error al buscar la frase";
|
||||
}
|
||||
}
|
||||
|
||||
String getAutorFromID(int IDF) {
|
||||
if (IDF <= 0) return "";
|
||||
try (Cursor c = masterDb.rawQuery(
|
||||
"SELECT Autor FROM autores WHERE _id = (SELECT AutorID FROM frases WHERE _id = ?)",
|
||||
new String[]{String.valueOf(IDF)})) {
|
||||
return c.moveToFirst() ? c.getString(0) : "";
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "getAutor: " + e);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** get fav of a IDFrase */
|
||||
Integer getFav(int IDF) {
|
||||
try (Cursor query = userDb.rawQuery("SELECT IDFrase FROM frasesFav WHERE IDFrase = ?",
|
||||
new String[]{String.valueOf(IDF)})) {
|
||||
return query.getCount();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "getFav: " + e);
|
||||
return 0; // if error, better return not fav
|
||||
}
|
||||
}
|
||||
|
||||
/** Add a sentence as favorite */
|
||||
void addFav(int IDF) {
|
||||
ContentValues cv = new ContentValues();
|
||||
cv.put("IDFrase", IDF);
|
||||
userDb.insertWithOnConflict("frasesFav", null, cv, SQLiteDatabase.CONFLICT_IGNORE);
|
||||
}
|
||||
|
||||
/** Del a favorite sentence */
|
||||
void delFav(int IDF) {
|
||||
userDb.delete("frasesFav", "IDFrase = ?", new String[]{String.valueOf(IDF)});
|
||||
}
|
||||
|
||||
/** Returns ID from a day X sentence, if possible */
|
||||
int getIDFraseDay(int year, int month, int dayOfMonth) {
|
||||
try {
|
||||
String diaArg = String.format(Locale.US, "%04d%02d%02d", year, month, dayOfMonth);
|
||||
|
||||
/* 1) día ya asignado */
|
||||
try (Cursor c = userDb.rawQuery("SELECT IDFrase FROM frasesG WHERE Tday = ?",
|
||||
new String[]{diaArg})) {
|
||||
if (c.moveToFirst()) {
|
||||
return c.getInt(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* 2) futuro: no accesible */
|
||||
String today = todayKey();
|
||||
if (diaArg.compareTo(today) > 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* 3) día pasado sin asignar: solo si la app ya se usó antes de ese día
|
||||
(evita backfillar el calendario entero navegando hacia atrás) */
|
||||
if (diaArg.compareTo(today) < 0) {
|
||||
try (Cursor c = userDb.rawQuery("SELECT COUNT(*) FROM frasesG WHERE Tday < ?",
|
||||
new String[]{diaArg})) {
|
||||
c.moveToFirst();
|
||||
if (c.getInt(0) == 0) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 4) asignar frase sin usar */
|
||||
int nuevoId = pickUnusedID();
|
||||
if (nuevoId == 0) {
|
||||
return 0; // no more sentences
|
||||
}
|
||||
ContentValues cv = new ContentValues();
|
||||
cv.put("Tday", diaArg);
|
||||
cv.put("IDFrase", nuevoId);
|
||||
userDb.insertWithOnConflict("frasesG", null, cv, SQLiteDatabase.CONFLICT_IGNORE);
|
||||
return nuevoId;
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "getIDFraseDay: " + e);
|
||||
return -2;
|
||||
}
|
||||
}
|
||||
|
||||
/** ID aleatorio del maestro que aún no se ha asignado a ningún día. 0 si no quedan. */
|
||||
private int pickUnusedID() {
|
||||
Set<Integer> used = new HashSet<>();
|
||||
try (Cursor c = userDb.rawQuery("SELECT IDFrase FROM frasesG", null)) {
|
||||
while (c.moveToNext()) {
|
||||
used.add(c.getInt(0));
|
||||
}
|
||||
}
|
||||
List<Integer> pool = new ArrayList<>();
|
||||
try (Cursor c = masterDb.rawQuery("SELECT _id FROM frases", null)) {
|
||||
while (c.moveToNext()) {
|
||||
int id = c.getInt(0);
|
||||
if (!used.contains(id)) {
|
||||
pool.add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pool.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
return pool.get(new Random().nextInt(pool.size()));
|
||||
}
|
||||
|
||||
/** Returns ID of today's sentence */
|
||||
Integer getIDFraseHoy() {
|
||||
java.util.Calendar cal = java.util.Calendar.getInstance();
|
||||
return getIDFraseDay(cal.get(java.util.Calendar.YEAR),
|
||||
cal.get(java.util.Calendar.MONTH) + 1,
|
||||
cal.get(java.util.Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
/** Returns an array of favorite IDs */
|
||||
Integer[] getIDFavs() {
|
||||
List<Integer> a = new ArrayList<>();
|
||||
try (Cursor c = userDb.rawQuery("SELECT IDFrase FROM frasesFav", null)) {
|
||||
while (c.moveToNext()) {
|
||||
a.add(c.getInt(0));
|
||||
}
|
||||
}
|
||||
return a.toArray(new Integer[0]);
|
||||
}
|
||||
|
||||
/** Returns an array of days already assigned (yyyymmdd) */
|
||||
String[] getAllDaysYet() {
|
||||
List<String> a = new ArrayList<>();
|
||||
try (Cursor c = userDb.rawQuery("SELECT Tday FROM frasesG", null)) {
|
||||
while (c.moveToNext()) {
|
||||
a.add(c.getString(0));
|
||||
}
|
||||
}
|
||||
return a.toArray(new String[0]);
|
||||
}
|
||||
|
||||
private String todayKey() {
|
||||
return new SimpleDateFormat("yyyyMMdd", Locale.US).format(new Date());
|
||||
}
|
||||
}
|
||||
@@ -26,11 +26,12 @@ import java.util.HashMap;
|
||||
*/
|
||||
|
||||
public class FavsActivity extends AppCompatActivity {
|
||||
DatabaseHelper db = new DatabaseHelper(this);
|
||||
DatabaseHelper db;
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_favs);
|
||||
db = new DatabaseHelper(this);
|
||||
|
||||
final ListView listFavs = (ListView) findViewById(R.id.listSentences);
|
||||
|
||||
@@ -88,7 +89,7 @@ public class FavsActivity extends AppCompatActivity {
|
||||
if (id == R.id.copy) {
|
||||
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
|
||||
clipboard.setPrimaryClip(ClipData.newPlainText("Sentence", obj.get("item")+this.getString(R.string.sharefrom)));
|
||||
Toast.makeText(getApplicationContext(), "Copiado al portapapeles", Toast.LENGTH_LONG ).show();
|
||||
Toast.makeText(getApplicationContext(), R.string.copied, Toast.LENGTH_LONG ).show();
|
||||
return true;
|
||||
} else if (id == R.id.delfav) {
|
||||
Integer[] IDFavs = db.getIDFavs();
|
||||
@@ -101,7 +102,7 @@ public class FavsActivity extends AppCompatActivity {
|
||||
Intent intent = new Intent(Intent.ACTION_SEND);
|
||||
intent.setType("text/plain");
|
||||
intent.putExtra(Intent.EXTRA_TEXT,obj.get("item")+this.getString(R.string.sharefrom));
|
||||
startActivity(Intent.createChooser(intent, "Compartir con"));
|
||||
startActivity(Intent.createChooser(intent, getString(R.string.share_with)));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -33,7 +33,7 @@ import com.google.android.ump.UserMessagingPlatform;
|
||||
public class MainActivity extends AppCompatActivity implements RobotoCalendarListener {
|
||||
|
||||
private RobotoCalendarView robotoCalendarView;
|
||||
DatabaseHelper db = new DatabaseHelper(this);
|
||||
DatabaseHelper db;
|
||||
Calendar cal = Calendar.getInstance();
|
||||
Integer IDFrase;
|
||||
final Config conf = new Config(this);
|
||||
@@ -83,10 +83,10 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
||||
/* First of all,before loading, see if its the first time using the app */
|
||||
if (conf.getFirstTime()){
|
||||
new AlertDialog.Builder(MainActivity.this)
|
||||
.setTitle("Bienvenido")
|
||||
.setMessage("Bienvenidos a Calendario de Frases, donde cada día disfrutarás de una nueva cita celebre o de un nuevo refrán que podrás guardar o compartir con tus amigos.\nAdemás, podrás poner una notificación para que te avise de la frase del día a la hora que quieras, por ejemplo, al desperarte.\nRecuerda que no puedes ver frases de los días que no hayan pasado aún con la aplicación.\nEsperamos que la disfrutes.")
|
||||
.setTitle(R.string.welcome_title)
|
||||
.setMessage(R.string.welcome_text)
|
||||
.setCancelable(false)
|
||||
.setPositiveButton("Empecemos", new DialogInterface.OnClickListener() {
|
||||
.setPositiveButton(R.string.welcome_button, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
// Nothing
|
||||
@@ -96,6 +96,7 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
||||
}
|
||||
|
||||
setContentView(R.layout.activity_main);
|
||||
db = new DatabaseHelper(this);
|
||||
txtfraseTitle = findViewById(R.id.txt_frasetitle);
|
||||
txtfraseText = findViewById(R.id.txt_frasetext);
|
||||
txtfraseAutor = findViewById(R.id.txt_fraseautor);
|
||||
@@ -115,6 +116,14 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
||||
|
||||
/* Register context menu */
|
||||
registerForContextMenu(txtfraseText);
|
||||
|
||||
/* Close app on back button */
|
||||
getOnBackPressedDispatcher().addCallback(this, new androidx.activity.OnBackPressedCallback(true) {
|
||||
@Override
|
||||
public void handleOnBackPressed() {
|
||||
moveTaskToBack(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* Consentimiento UMP (obligatorio EEA) y tras él, init de AdMob + banner */
|
||||
@@ -168,7 +177,7 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
||||
public void onClick(View viewIn) {
|
||||
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
|
||||
clipboard.setPrimaryClip(ClipData.newPlainText("Sentence", txtfraseText.getText()+MainActivity.this.getString(R.string.sharefrom)));
|
||||
Toast.makeText(getApplicationContext(), "Copiado al portapapeles", Toast.LENGTH_LONG ).show();
|
||||
Toast.makeText(getApplicationContext(), R.string.copied, Toast.LENGTH_LONG ).show();
|
||||
}
|
||||
});
|
||||
changeFavImage(); //Fav image button
|
||||
@@ -193,7 +202,7 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
||||
Intent intent = new Intent(Intent.ACTION_SEND);
|
||||
intent.setType("text/plain");
|
||||
intent.putExtra(Intent.EXTRA_TEXT, sentence+MainActivity.this.getString(R.string.sharefrom));
|
||||
startActivity(Intent.createChooser(intent, "Compartir con"));
|
||||
startActivity(Intent.createChooser(intent, getString(R.string.share_with)));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -207,12 +216,7 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
||||
}
|
||||
|
||||
|
||||
/* Close app on back button */
|
||||
@Override
|
||||
public void onBackPressed()
|
||||
{
|
||||
moveTaskToBack(true);
|
||||
}
|
||||
/* Close app on back button: registrado en onCreate con OnBackPressedDispatcher */
|
||||
|
||||
|
||||
|
||||
@@ -229,7 +233,7 @@ public class MainActivity extends AppCompatActivity implements RobotoCalendarLis
|
||||
txtfraseAutor.setText(db.getAutorFromID(IDFrase));
|
||||
/* Set Title before sentence */
|
||||
if (year != cal.get(Calendar.YEAR) || month != (cal.get(Calendar.MONTH)+1) || day != cal.get(Calendar.DAY_OF_MONTH)) {
|
||||
txtfraseTitle.setText("Frase del " + day + " de " + getMonth(month)); //Change title
|
||||
txtfraseTitle.setText(getString(R.string.sentence_of_day, day, getMonth(month))); //Change title
|
||||
}else {
|
||||
txtfraseTitle.setText(R.string.txt_todaysentence); //Change title (today)
|
||||
}
|
||||
|
||||
@@ -9,5 +9,11 @@
|
||||
<string name="channel_name">Frase del día</string>
|
||||
<string name="channel_desc">Notificación diaria con la frase del día</string>
|
||||
<string name="notif_title">Frase de hoy:</string>
|
||||
<string name="welcome_title">Bienvenido</string>
|
||||
<string name="welcome_text">Bienvenidos a Calendario de Frases, donde cada día disfrutarás de una nueva cita celebre o de un nuevo refrán que podrás guardar o compartir con tus amigos.\nAdemás, podrás poner una notificación para que te avise de la frase del día a la hora que quieras, por ejemplo, al desperarte.\nRecuerda que no puedes ver frases de los días que no hayan pasado aún con la aplicación.\nEsperamos que la disfrutes.</string>
|
||||
<string name="welcome_button">Empecemos</string>
|
||||
<string name="copied">Copiado al portapapeles</string>
|
||||
<string name="share_with">Compartir con</string>
|
||||
<string name="sentence_of_day">Frase del %1$d de %2$s</string>
|
||||
|
||||
</resources>
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
#Tue Oct 20 12:49:20 UTC 2026
|
||||
VERSION_CODE=367
|
||||
#Tue Oct 20 12:57:40 UTC 2026
|
||||
VERSION_CODE=370
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Genera app/src/main/assets/frases.db (BD maestra) desde res/raw.
|
||||
|
||||
Fuente de verdad: res/raw/sqlfrases y res/raw/sqlautores (INSERTs).
|
||||
Los IDs se respetan (mismo orden de inserción), por eso los favoritos y
|
||||
días históricos de la BD de usuario sobreviven a las actualizaciones.
|
||||
|
||||
Al añadir/cambiar frases: editar los raw y subir MASTER_DB_VERSION
|
||||
(la app recopia el maestro cuando el user_version del asset es mayor).
|
||||
|
||||
Uso: python3 tools/build_master_db.py
|
||||
"""
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
RAW = ROOT / "app/src/main/res/raw"
|
||||
OUT = ROOT / "app/src/main/assets/frases.db"
|
||||
|
||||
# Subir al cambiar el contenido de frases/autores
|
||||
MASTER_DB_VERSION = 1
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE frases (
|
||||
`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
`Frase` TEXT NOT NULL UNIQUE,
|
||||
`AutorID` INTEGER
|
||||
);
|
||||
CREATE TABLE autores (
|
||||
`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
`Autor` TEXT UNIQUE
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def load_statements(path: Path) -> list[str]:
|
||||
# Los raw separan statements con '|', igual que hacía DatabaseHelper.onCreate
|
||||
return [s.strip() for s in path.read_text(encoding="utf-8").split("|") if s.strip()]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
if OUT.exists():
|
||||
OUT.unlink()
|
||||
con = sqlite3.connect(OUT)
|
||||
try:
|
||||
con.executescript(SCHEMA)
|
||||
for stmt in load_statements(RAW / "sqlfrases"):
|
||||
con.execute(stmt)
|
||||
for stmt in load_statements(RAW / "sqlautores"):
|
||||
con.execute(stmt)
|
||||
con.execute(f"PRAGMA user_version = {MASTER_DB_VERSION}")
|
||||
con.commit()
|
||||
n_frases = con.execute("SELECT COUNT(*) FROM frases").fetchone()[0]
|
||||
n_autores = con.execute("SELECT COUNT(*) FROM autores").fetchone()[0]
|
||||
finally:
|
||||
con.close()
|
||||
print(f"OK {OUT}: {n_frases} frases, {n_autores} autores, user_version={MASTER_DB_VERSION}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user