quero meter o gemini na app

This commit is contained in:
2026-02-10 16:58:11 +00:00
parent 1d5470b8a4
commit 325255e43a
77 changed files with 3466 additions and 4508 deletions

View File

@@ -43,6 +43,7 @@ dependencies {
implementation 'com.google.firebase:firebase-auth:24.0.1'
implementation 'androidx.credentials:credentials:1.5.0'
implementation 'androidx.credentials:credentials-play-services-auth:1.5.0'
//noinspection UseIdentifyId
implementation 'com.google.android.libraries.identity.googleid:googleid:1.1.1'
implementation 'com.google.firebase:firebase-storage:22.0.1'
implementation 'com.google.firebase:firebase-database:22.0.1'
@@ -60,7 +61,9 @@ dependencies {
// Location
implementation 'com.google.android.gms:play-services-location:21.0.1'
// Google AI SDK for Android (Gemini)
implementation 'com.google.ai.client.generativeai:generativeai:0.9.0'
// Biblioteca oficial do Google AI para Java/Android
implementation 'com.google.ai.client.generativeai:generativeai:+'
// Necessário para lidar com operações assíncronas (Guava)
implementation 'com.google.guava:guava:31.1-android'
}

View File

@@ -1,4 +1,4 @@
#Tue Feb 03 16:59:18 WET 2026
#Tue Feb 10 15:45:47 WET 2026
base.0=/Users/230405/Desktop/papcuida/app/build/intermediates/dex/debug/mergeExtDexDebug/classes.dex
base.1=/Users/230405/Desktop/papcuida/app/build/intermediates/dex/debug/mergeProjectDexDebug/0/classes.dex
base.10=/Users/230405/Desktop/papcuida/app/build/intermediates/dex/debug/mergeProjectDexDebug/7/classes.dex

File diff suppressed because one or more lines are too long

View File

@@ -1,250 +0,0 @@
package com.example.cuida.data;
import androidx.annotation.NonNull;
import androidx.room.DatabaseConfiguration;
import androidx.room.InvalidationTracker;
import androidx.room.RoomDatabase;
import androidx.room.RoomOpenHelper;
import androidx.room.migration.AutoMigrationSpec;
import androidx.room.migration.Migration;
import androidx.room.util.DBUtil;
import androidx.room.util.TableInfo;
import androidx.sqlite.db.SupportSQLiteDatabase;
import androidx.sqlite.db.SupportSQLiteOpenHelper;
import com.example.cuida.data.dao.AppointmentDao;
import com.example.cuida.data.dao.AppointmentDao_Impl;
import com.example.cuida.data.dao.MedicationDao;
import com.example.cuida.data.dao.MedicationDao_Impl;
import com.example.cuida.data.dao.UserDao;
import com.example.cuida.data.dao.UserDao_Impl;
import java.lang.Class;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@SuppressWarnings({"unchecked", "deprecation"})
public final class AppDatabase_Impl extends AppDatabase {
private volatile UserDao _userDao;
private volatile AppointmentDao _appointmentDao;
private volatile MedicationDao _medicationDao;
@Override
@NonNull
protected SupportSQLiteOpenHelper createOpenHelper(@NonNull final DatabaseConfiguration config) {
final SupportSQLiteOpenHelper.Callback _openCallback = new RoomOpenHelper(config, new RoomOpenHelper.Delegate(3) {
@Override
public void createAllTables(@NonNull final SupportSQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS `users` (`uid` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT, `email` TEXT, `password` TEXT, `age` INTEGER NOT NULL, `utenteNumber` TEXT, `profilePictureUri` TEXT)");
db.execSQL("CREATE TABLE IF NOT EXISTS `appointments` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `type` TEXT, `date` TEXT, `time` TEXT, `reason` TEXT, `isPast` INTEGER NOT NULL)");
db.execSQL("CREATE TABLE IF NOT EXISTS `medications` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT, `time` TEXT, `dosage` TEXT, `notes` TEXT, `isTaken` INTEGER NOT NULL)");
db.execSQL("CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)");
db.execSQL("INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2bfd7144258edb6d96f828b5b036c580')");
}
@Override
public void dropAllTables(@NonNull final SupportSQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS `users`");
db.execSQL("DROP TABLE IF EXISTS `appointments`");
db.execSQL("DROP TABLE IF EXISTS `medications`");
final List<? extends RoomDatabase.Callback> _callbacks = mCallbacks;
if (_callbacks != null) {
for (RoomDatabase.Callback _callback : _callbacks) {
_callback.onDestructiveMigration(db);
}
}
}
@Override
public void onCreate(@NonNull final SupportSQLiteDatabase db) {
final List<? extends RoomDatabase.Callback> _callbacks = mCallbacks;
if (_callbacks != null) {
for (RoomDatabase.Callback _callback : _callbacks) {
_callback.onCreate(db);
}
}
}
@Override
public void onOpen(@NonNull final SupportSQLiteDatabase db) {
mDatabase = db;
internalInitInvalidationTracker(db);
final List<? extends RoomDatabase.Callback> _callbacks = mCallbacks;
if (_callbacks != null) {
for (RoomDatabase.Callback _callback : _callbacks) {
_callback.onOpen(db);
}
}
}
@Override
public void onPreMigrate(@NonNull final SupportSQLiteDatabase db) {
DBUtil.dropFtsSyncTriggers(db);
}
@Override
public void onPostMigrate(@NonNull final SupportSQLiteDatabase db) {
}
@Override
@NonNull
public RoomOpenHelper.ValidationResult onValidateSchema(
@NonNull final SupportSQLiteDatabase db) {
final HashMap<String, TableInfo.Column> _columnsUsers = new HashMap<String, TableInfo.Column>(7);
_columnsUsers.put("uid", new TableInfo.Column("uid", "INTEGER", true, 1, null, TableInfo.CREATED_FROM_ENTITY));
_columnsUsers.put("name", new TableInfo.Column("name", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsUsers.put("email", new TableInfo.Column("email", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsUsers.put("password", new TableInfo.Column("password", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsUsers.put("age", new TableInfo.Column("age", "INTEGER", true, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsUsers.put("utenteNumber", new TableInfo.Column("utenteNumber", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsUsers.put("profilePictureUri", new TableInfo.Column("profilePictureUri", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
final HashSet<TableInfo.ForeignKey> _foreignKeysUsers = new HashSet<TableInfo.ForeignKey>(0);
final HashSet<TableInfo.Index> _indicesUsers = new HashSet<TableInfo.Index>(0);
final TableInfo _infoUsers = new TableInfo("users", _columnsUsers, _foreignKeysUsers, _indicesUsers);
final TableInfo _existingUsers = TableInfo.read(db, "users");
if (!_infoUsers.equals(_existingUsers)) {
return new RoomOpenHelper.ValidationResult(false, "users(com.example.cuida.data.model.User).\n"
+ " Expected:\n" + _infoUsers + "\n"
+ " Found:\n" + _existingUsers);
}
final HashMap<String, TableInfo.Column> _columnsAppointments = new HashMap<String, TableInfo.Column>(6);
_columnsAppointments.put("id", new TableInfo.Column("id", "INTEGER", true, 1, null, TableInfo.CREATED_FROM_ENTITY));
_columnsAppointments.put("type", new TableInfo.Column("type", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsAppointments.put("date", new TableInfo.Column("date", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsAppointments.put("time", new TableInfo.Column("time", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsAppointments.put("reason", new TableInfo.Column("reason", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsAppointments.put("isPast", new TableInfo.Column("isPast", "INTEGER", true, 0, null, TableInfo.CREATED_FROM_ENTITY));
final HashSet<TableInfo.ForeignKey> _foreignKeysAppointments = new HashSet<TableInfo.ForeignKey>(0);
final HashSet<TableInfo.Index> _indicesAppointments = new HashSet<TableInfo.Index>(0);
final TableInfo _infoAppointments = new TableInfo("appointments", _columnsAppointments, _foreignKeysAppointments, _indicesAppointments);
final TableInfo _existingAppointments = TableInfo.read(db, "appointments");
if (!_infoAppointments.equals(_existingAppointments)) {
return new RoomOpenHelper.ValidationResult(false, "appointments(com.example.cuida.data.model.Appointment).\n"
+ " Expected:\n" + _infoAppointments + "\n"
+ " Found:\n" + _existingAppointments);
}
final HashMap<String, TableInfo.Column> _columnsMedications = new HashMap<String, TableInfo.Column>(6);
_columnsMedications.put("id", new TableInfo.Column("id", "INTEGER", true, 1, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMedications.put("name", new TableInfo.Column("name", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMedications.put("time", new TableInfo.Column("time", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMedications.put("dosage", new TableInfo.Column("dosage", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMedications.put("notes", new TableInfo.Column("notes", "TEXT", false, 0, null, TableInfo.CREATED_FROM_ENTITY));
_columnsMedications.put("isTaken", new TableInfo.Column("isTaken", "INTEGER", true, 0, null, TableInfo.CREATED_FROM_ENTITY));
final HashSet<TableInfo.ForeignKey> _foreignKeysMedications = new HashSet<TableInfo.ForeignKey>(0);
final HashSet<TableInfo.Index> _indicesMedications = new HashSet<TableInfo.Index>(0);
final TableInfo _infoMedications = new TableInfo("medications", _columnsMedications, _foreignKeysMedications, _indicesMedications);
final TableInfo _existingMedications = TableInfo.read(db, "medications");
if (!_infoMedications.equals(_existingMedications)) {
return new RoomOpenHelper.ValidationResult(false, "medications(com.example.cuida.data.model.Medication).\n"
+ " Expected:\n" + _infoMedications + "\n"
+ " Found:\n" + _existingMedications);
}
return new RoomOpenHelper.ValidationResult(true, null);
}
}, "2bfd7144258edb6d96f828b5b036c580", "54396701591a8f38f350a20a4d12755d");
final SupportSQLiteOpenHelper.Configuration _sqliteConfig = SupportSQLiteOpenHelper.Configuration.builder(config.context).name(config.name).callback(_openCallback).build();
final SupportSQLiteOpenHelper _helper = config.sqliteOpenHelperFactory.create(_sqliteConfig);
return _helper;
}
@Override
@NonNull
protected InvalidationTracker createInvalidationTracker() {
final HashMap<String, String> _shadowTablesMap = new HashMap<String, String>(0);
final HashMap<String, Set<String>> _viewTables = new HashMap<String, Set<String>>(0);
return new InvalidationTracker(this, _shadowTablesMap, _viewTables, "users","appointments","medications");
}
@Override
public void clearAllTables() {
super.assertNotMainThread();
final SupportSQLiteDatabase _db = super.getOpenHelper().getWritableDatabase();
try {
super.beginTransaction();
_db.execSQL("DELETE FROM `users`");
_db.execSQL("DELETE FROM `appointments`");
_db.execSQL("DELETE FROM `medications`");
super.setTransactionSuccessful();
} finally {
super.endTransaction();
_db.query("PRAGMA wal_checkpoint(FULL)").close();
if (!_db.inTransaction()) {
_db.execSQL("VACUUM");
}
}
}
@Override
@NonNull
protected Map<Class<?>, List<Class<?>>> getRequiredTypeConverters() {
final HashMap<Class<?>, List<Class<?>>> _typeConvertersMap = new HashMap<Class<?>, List<Class<?>>>();
_typeConvertersMap.put(UserDao.class, UserDao_Impl.getRequiredConverters());
_typeConvertersMap.put(AppointmentDao.class, AppointmentDao_Impl.getRequiredConverters());
_typeConvertersMap.put(MedicationDao.class, MedicationDao_Impl.getRequiredConverters());
return _typeConvertersMap;
}
@Override
@NonNull
public Set<Class<? extends AutoMigrationSpec>> getRequiredAutoMigrationSpecs() {
final HashSet<Class<? extends AutoMigrationSpec>> _autoMigrationSpecsSet = new HashSet<Class<? extends AutoMigrationSpec>>();
return _autoMigrationSpecsSet;
}
@Override
@NonNull
public List<Migration> getAutoMigrations(
@NonNull final Map<Class<? extends AutoMigrationSpec>, AutoMigrationSpec> autoMigrationSpecs) {
final List<Migration> _autoMigrations = new ArrayList<Migration>();
return _autoMigrations;
}
@Override
public UserDao userDao() {
if (_userDao != null) {
return _userDao;
} else {
synchronized(this) {
if(_userDao == null) {
_userDao = new UserDao_Impl(this);
}
return _userDao;
}
}
}
@Override
public AppointmentDao appointmentDao() {
if (_appointmentDao != null) {
return _appointmentDao;
} else {
synchronized(this) {
if(_appointmentDao == null) {
_appointmentDao = new AppointmentDao_Impl(this);
}
return _appointmentDao;
}
}
}
@Override
public MedicationDao medicationDao() {
if (_medicationDao != null) {
return _medicationDao;
} else {
synchronized(this) {
if(_medicationDao == null) {
_medicationDao = new MedicationDao_Impl(this);
}
return _medicationDao;
}
}
}
}

View File

@@ -1,243 +0,0 @@
package com.example.cuida.data.dao;
import android.database.Cursor;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;
import androidx.room.EntityInsertionAdapter;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.room.util.CursorUtil;
import androidx.room.util.DBUtil;
import androidx.sqlite.db.SupportSQLiteStatement;
import com.example.cuida.data.model.Appointment;
import java.lang.Class;
import java.lang.Exception;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
@SuppressWarnings({"unchecked", "deprecation"})
public final class AppointmentDao_Impl implements AppointmentDao {
private final RoomDatabase __db;
private final EntityInsertionAdapter<Appointment> __insertionAdapterOfAppointment;
public AppointmentDao_Impl(@NonNull final RoomDatabase __db) {
this.__db = __db;
this.__insertionAdapterOfAppointment = new EntityInsertionAdapter<Appointment>(__db) {
@Override
@NonNull
protected String createQuery() {
return "INSERT OR ABORT INTO `appointments` (`id`,`type`,`date`,`time`,`reason`,`isPast`) VALUES (nullif(?, 0),?,?,?,?,?)";
}
@Override
protected void bind(@NonNull final SupportSQLiteStatement statement,
final Appointment entity) {
statement.bindLong(1, entity.id);
if (entity.type == null) {
statement.bindNull(2);
} else {
statement.bindString(2, entity.type);
}
if (entity.date == null) {
statement.bindNull(3);
} else {
statement.bindString(3, entity.date);
}
if (entity.time == null) {
statement.bindNull(4);
} else {
statement.bindString(4, entity.time);
}
if (entity.reason == null) {
statement.bindNull(5);
} else {
statement.bindString(5, entity.reason);
}
final int _tmp = entity.isPast ? 1 : 0;
statement.bindLong(6, _tmp);
}
};
}
@Override
public void insert(final Appointment appointment) {
__db.assertNotSuspendingTransaction();
__db.beginTransaction();
try {
__insertionAdapterOfAppointment.insert(appointment);
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
@Override
public LiveData<List<Appointment>> getFutureAppointments() {
final String _sql = "SELECT * FROM appointments WHERE isPast = 0 ORDER BY date ASC, time ASC";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
return __db.getInvalidationTracker().createLiveData(new String[] {"appointments"}, false, new Callable<List<Appointment>>() {
@Override
@Nullable
public List<Appointment> call() throws Exception {
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfId = CursorUtil.getColumnIndexOrThrow(_cursor, "id");
final int _cursorIndexOfType = CursorUtil.getColumnIndexOrThrow(_cursor, "type");
final int _cursorIndexOfDate = CursorUtil.getColumnIndexOrThrow(_cursor, "date");
final int _cursorIndexOfTime = CursorUtil.getColumnIndexOrThrow(_cursor, "time");
final int _cursorIndexOfReason = CursorUtil.getColumnIndexOrThrow(_cursor, "reason");
final int _cursorIndexOfIsPast = CursorUtil.getColumnIndexOrThrow(_cursor, "isPast");
final List<Appointment> _result = new ArrayList<Appointment>(_cursor.getCount());
while (_cursor.moveToNext()) {
final Appointment _item;
final String _tmpType;
if (_cursor.isNull(_cursorIndexOfType)) {
_tmpType = null;
} else {
_tmpType = _cursor.getString(_cursorIndexOfType);
}
final String _tmpDate;
if (_cursor.isNull(_cursorIndexOfDate)) {
_tmpDate = null;
} else {
_tmpDate = _cursor.getString(_cursorIndexOfDate);
}
final String _tmpTime;
if (_cursor.isNull(_cursorIndexOfTime)) {
_tmpTime = null;
} else {
_tmpTime = _cursor.getString(_cursorIndexOfTime);
}
final String _tmpReason;
if (_cursor.isNull(_cursorIndexOfReason)) {
_tmpReason = null;
} else {
_tmpReason = _cursor.getString(_cursorIndexOfReason);
}
final boolean _tmpIsPast;
final int _tmp;
_tmp = _cursor.getInt(_cursorIndexOfIsPast);
_tmpIsPast = _tmp != 0;
_item = new Appointment(_tmpType,_tmpDate,_tmpTime,_tmpReason,_tmpIsPast);
_item.id = _cursor.getInt(_cursorIndexOfId);
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
}
}
@Override
protected void finalize() {
_statement.release();
}
});
}
@Override
public LiveData<List<Appointment>> getPastAppointments() {
final String _sql = "SELECT * FROM appointments WHERE isPast = 1 ORDER BY date DESC, time DESC";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
return __db.getInvalidationTracker().createLiveData(new String[] {"appointments"}, false, new Callable<List<Appointment>>() {
@Override
@Nullable
public List<Appointment> call() throws Exception {
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfId = CursorUtil.getColumnIndexOrThrow(_cursor, "id");
final int _cursorIndexOfType = CursorUtil.getColumnIndexOrThrow(_cursor, "type");
final int _cursorIndexOfDate = CursorUtil.getColumnIndexOrThrow(_cursor, "date");
final int _cursorIndexOfTime = CursorUtil.getColumnIndexOrThrow(_cursor, "time");
final int _cursorIndexOfReason = CursorUtil.getColumnIndexOrThrow(_cursor, "reason");
final int _cursorIndexOfIsPast = CursorUtil.getColumnIndexOrThrow(_cursor, "isPast");
final List<Appointment> _result = new ArrayList<Appointment>(_cursor.getCount());
while (_cursor.moveToNext()) {
final Appointment _item;
final String _tmpType;
if (_cursor.isNull(_cursorIndexOfType)) {
_tmpType = null;
} else {
_tmpType = _cursor.getString(_cursorIndexOfType);
}
final String _tmpDate;
if (_cursor.isNull(_cursorIndexOfDate)) {
_tmpDate = null;
} else {
_tmpDate = _cursor.getString(_cursorIndexOfDate);
}
final String _tmpTime;
if (_cursor.isNull(_cursorIndexOfTime)) {
_tmpTime = null;
} else {
_tmpTime = _cursor.getString(_cursorIndexOfTime);
}
final String _tmpReason;
if (_cursor.isNull(_cursorIndexOfReason)) {
_tmpReason = null;
} else {
_tmpReason = _cursor.getString(_cursorIndexOfReason);
}
final boolean _tmpIsPast;
final int _tmp;
_tmp = _cursor.getInt(_cursorIndexOfIsPast);
_tmpIsPast = _tmp != 0;
_item = new Appointment(_tmpType,_tmpDate,_tmpTime,_tmpReason,_tmpIsPast);
_item.id = _cursor.getInt(_cursorIndexOfId);
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
}
}
@Override
protected void finalize() {
_statement.release();
}
});
}
@Override
public List<String> getBookedTimesForDate(final String date) {
final String _sql = "SELECT time FROM appointments WHERE date = ?";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
int _argIndex = 1;
if (date == null) {
_statement.bindNull(_argIndex);
} else {
_statement.bindString(_argIndex, date);
}
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final List<String> _result = new ArrayList<String>(_cursor.getCount());
while (_cursor.moveToNext()) {
final String _item;
if (_cursor.isNull(0)) {
_item = null;
} else {
_item = _cursor.getString(0);
}
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
@NonNull
public static List<Class<?>> getRequiredConverters() {
return Collections.emptyList();
}
}

View File

@@ -1,262 +0,0 @@
package com.example.cuida.data.dao;
import android.database.Cursor;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;
import androidx.room.EntityDeletionOrUpdateAdapter;
import androidx.room.EntityInsertionAdapter;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.room.util.CursorUtil;
import androidx.room.util.DBUtil;
import androidx.sqlite.db.SupportSQLiteStatement;
import com.example.cuida.data.model.Medication;
import java.lang.Class;
import java.lang.Exception;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
@SuppressWarnings({"unchecked", "deprecation"})
public final class MedicationDao_Impl implements MedicationDao {
private final RoomDatabase __db;
private final EntityInsertionAdapter<Medication> __insertionAdapterOfMedication;
private final EntityDeletionOrUpdateAdapter<Medication> __updateAdapterOfMedication;
public MedicationDao_Impl(@NonNull final RoomDatabase __db) {
this.__db = __db;
this.__insertionAdapterOfMedication = new EntityInsertionAdapter<Medication>(__db) {
@Override
@NonNull
protected String createQuery() {
return "INSERT OR ABORT INTO `medications` (`id`,`name`,`time`,`dosage`,`notes`,`isTaken`) VALUES (nullif(?, 0),?,?,?,?,?)";
}
@Override
protected void bind(@NonNull final SupportSQLiteStatement statement,
final Medication entity) {
statement.bindLong(1, entity.id);
if (entity.name == null) {
statement.bindNull(2);
} else {
statement.bindString(2, entity.name);
}
if (entity.time == null) {
statement.bindNull(3);
} else {
statement.bindString(3, entity.time);
}
if (entity.dosage == null) {
statement.bindNull(4);
} else {
statement.bindString(4, entity.dosage);
}
if (entity.notes == null) {
statement.bindNull(5);
} else {
statement.bindString(5, entity.notes);
}
final int _tmp = entity.isTaken ? 1 : 0;
statement.bindLong(6, _tmp);
}
};
this.__updateAdapterOfMedication = new EntityDeletionOrUpdateAdapter<Medication>(__db) {
@Override
@NonNull
protected String createQuery() {
return "UPDATE OR ABORT `medications` SET `id` = ?,`name` = ?,`time` = ?,`dosage` = ?,`notes` = ?,`isTaken` = ? WHERE `id` = ?";
}
@Override
protected void bind(@NonNull final SupportSQLiteStatement statement,
final Medication entity) {
statement.bindLong(1, entity.id);
if (entity.name == null) {
statement.bindNull(2);
} else {
statement.bindString(2, entity.name);
}
if (entity.time == null) {
statement.bindNull(3);
} else {
statement.bindString(3, entity.time);
}
if (entity.dosage == null) {
statement.bindNull(4);
} else {
statement.bindString(4, entity.dosage);
}
if (entity.notes == null) {
statement.bindNull(5);
} else {
statement.bindString(5, entity.notes);
}
final int _tmp = entity.isTaken ? 1 : 0;
statement.bindLong(6, _tmp);
statement.bindLong(7, entity.id);
}
};
}
@Override
public void insert(final Medication medication) {
__db.assertNotSuspendingTransaction();
__db.beginTransaction();
try {
__insertionAdapterOfMedication.insert(medication);
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
@Override
public void update(final Medication medication) {
__db.assertNotSuspendingTransaction();
__db.beginTransaction();
try {
__updateAdapterOfMedication.handle(medication);
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
@Override
public LiveData<List<Medication>> getAllMedications() {
final String _sql = "SELECT * FROM medications ORDER BY time ASC";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
return __db.getInvalidationTracker().createLiveData(new String[] {"medications"}, false, new Callable<List<Medication>>() {
@Override
@Nullable
public List<Medication> call() throws Exception {
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfId = CursorUtil.getColumnIndexOrThrow(_cursor, "id");
final int _cursorIndexOfName = CursorUtil.getColumnIndexOrThrow(_cursor, "name");
final int _cursorIndexOfTime = CursorUtil.getColumnIndexOrThrow(_cursor, "time");
final int _cursorIndexOfDosage = CursorUtil.getColumnIndexOrThrow(_cursor, "dosage");
final int _cursorIndexOfNotes = CursorUtil.getColumnIndexOrThrow(_cursor, "notes");
final int _cursorIndexOfIsTaken = CursorUtil.getColumnIndexOrThrow(_cursor, "isTaken");
final List<Medication> _result = new ArrayList<Medication>(_cursor.getCount());
while (_cursor.moveToNext()) {
final Medication _item;
final String _tmpName;
if (_cursor.isNull(_cursorIndexOfName)) {
_tmpName = null;
} else {
_tmpName = _cursor.getString(_cursorIndexOfName);
}
final String _tmpTime;
if (_cursor.isNull(_cursorIndexOfTime)) {
_tmpTime = null;
} else {
_tmpTime = _cursor.getString(_cursorIndexOfTime);
}
final String _tmpDosage;
if (_cursor.isNull(_cursorIndexOfDosage)) {
_tmpDosage = null;
} else {
_tmpDosage = _cursor.getString(_cursorIndexOfDosage);
}
final String _tmpNotes;
if (_cursor.isNull(_cursorIndexOfNotes)) {
_tmpNotes = null;
} else {
_tmpNotes = _cursor.getString(_cursorIndexOfNotes);
}
_item = new Medication(_tmpName,_tmpTime,_tmpDosage,_tmpNotes);
_item.id = _cursor.getInt(_cursorIndexOfId);
final int _tmp;
_tmp = _cursor.getInt(_cursorIndexOfIsTaken);
_item.isTaken = _tmp != 0;
_result.add(_item);
}
return _result;
} finally {
_cursor.close();
}
}
@Override
protected void finalize() {
_statement.release();
}
});
}
@Override
public LiveData<Medication> getNextMedication() {
final String _sql = "SELECT * FROM medications ORDER BY time ASC LIMIT 1";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 0);
return __db.getInvalidationTracker().createLiveData(new String[] {"medications"}, false, new Callable<Medication>() {
@Override
@Nullable
public Medication call() throws Exception {
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfId = CursorUtil.getColumnIndexOrThrow(_cursor, "id");
final int _cursorIndexOfName = CursorUtil.getColumnIndexOrThrow(_cursor, "name");
final int _cursorIndexOfTime = CursorUtil.getColumnIndexOrThrow(_cursor, "time");
final int _cursorIndexOfDosage = CursorUtil.getColumnIndexOrThrow(_cursor, "dosage");
final int _cursorIndexOfNotes = CursorUtil.getColumnIndexOrThrow(_cursor, "notes");
final int _cursorIndexOfIsTaken = CursorUtil.getColumnIndexOrThrow(_cursor, "isTaken");
final Medication _result;
if (_cursor.moveToFirst()) {
final String _tmpName;
if (_cursor.isNull(_cursorIndexOfName)) {
_tmpName = null;
} else {
_tmpName = _cursor.getString(_cursorIndexOfName);
}
final String _tmpTime;
if (_cursor.isNull(_cursorIndexOfTime)) {
_tmpTime = null;
} else {
_tmpTime = _cursor.getString(_cursorIndexOfTime);
}
final String _tmpDosage;
if (_cursor.isNull(_cursorIndexOfDosage)) {
_tmpDosage = null;
} else {
_tmpDosage = _cursor.getString(_cursorIndexOfDosage);
}
final String _tmpNotes;
if (_cursor.isNull(_cursorIndexOfNotes)) {
_tmpNotes = null;
} else {
_tmpNotes = _cursor.getString(_cursorIndexOfNotes);
}
_result = new Medication(_tmpName,_tmpTime,_tmpDosage,_tmpNotes);
_result.id = _cursor.getInt(_cursorIndexOfId);
final int _tmp;
_tmp = _cursor.getInt(_cursorIndexOfIsTaken);
_result.isTaken = _tmp != 0;
} else {
_result = null;
}
return _result;
} finally {
_cursor.close();
}
}
@Override
protected void finalize() {
_statement.release();
}
});
}
@NonNull
public static List<Class<?>> getRequiredConverters() {
return Collections.emptyList();
}
}

View File

@@ -1,301 +0,0 @@
package com.example.cuida.data.dao;
import android.database.Cursor;
import androidx.annotation.NonNull;
import androidx.room.EntityDeletionOrUpdateAdapter;
import androidx.room.EntityInsertionAdapter;
import androidx.room.RoomDatabase;
import androidx.room.RoomSQLiteQuery;
import androidx.room.SharedSQLiteStatement;
import androidx.room.util.CursorUtil;
import androidx.room.util.DBUtil;
import androidx.sqlite.db.SupportSQLiteStatement;
import com.example.cuida.data.model.User;
import java.lang.Class;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.Collections;
import java.util.List;
@SuppressWarnings({"unchecked", "deprecation"})
public final class UserDao_Impl implements UserDao {
private final RoomDatabase __db;
private final EntityInsertionAdapter<User> __insertionAdapterOfUser;
private final EntityDeletionOrUpdateAdapter<User> __updateAdapterOfUser;
private final SharedSQLiteStatement __preparedStmtOfDeleteAll;
public UserDao_Impl(@NonNull final RoomDatabase __db) {
this.__db = __db;
this.__insertionAdapterOfUser = new EntityInsertionAdapter<User>(__db) {
@Override
@NonNull
protected String createQuery() {
return "INSERT OR REPLACE INTO `users` (`uid`,`name`,`email`,`password`,`age`,`utenteNumber`,`profilePictureUri`) VALUES (nullif(?, 0),?,?,?,?,?,?)";
}
@Override
protected void bind(@NonNull final SupportSQLiteStatement statement, final User entity) {
statement.bindLong(1, entity.uid);
if (entity.name == null) {
statement.bindNull(2);
} else {
statement.bindString(2, entity.name);
}
if (entity.email == null) {
statement.bindNull(3);
} else {
statement.bindString(3, entity.email);
}
if (entity.password == null) {
statement.bindNull(4);
} else {
statement.bindString(4, entity.password);
}
statement.bindLong(5, entity.age);
if (entity.utenteNumber == null) {
statement.bindNull(6);
} else {
statement.bindString(6, entity.utenteNumber);
}
if (entity.profilePictureUri == null) {
statement.bindNull(7);
} else {
statement.bindString(7, entity.profilePictureUri);
}
}
};
this.__updateAdapterOfUser = new EntityDeletionOrUpdateAdapter<User>(__db) {
@Override
@NonNull
protected String createQuery() {
return "UPDATE OR ABORT `users` SET `uid` = ?,`name` = ?,`email` = ?,`password` = ?,`age` = ?,`utenteNumber` = ?,`profilePictureUri` = ? WHERE `uid` = ?";
}
@Override
protected void bind(@NonNull final SupportSQLiteStatement statement, final User entity) {
statement.bindLong(1, entity.uid);
if (entity.name == null) {
statement.bindNull(2);
} else {
statement.bindString(2, entity.name);
}
if (entity.email == null) {
statement.bindNull(3);
} else {
statement.bindString(3, entity.email);
}
if (entity.password == null) {
statement.bindNull(4);
} else {
statement.bindString(4, entity.password);
}
statement.bindLong(5, entity.age);
if (entity.utenteNumber == null) {
statement.bindNull(6);
} else {
statement.bindString(6, entity.utenteNumber);
}
if (entity.profilePictureUri == null) {
statement.bindNull(7);
} else {
statement.bindString(7, entity.profilePictureUri);
}
statement.bindLong(8, entity.uid);
}
};
this.__preparedStmtOfDeleteAll = new SharedSQLiteStatement(__db) {
@Override
@NonNull
public String createQuery() {
final String _query = "delete from users";
return _query;
}
};
}
@Override
public void insert(final User user) {
__db.assertNotSuspendingTransaction();
__db.beginTransaction();
try {
__insertionAdapterOfUser.insert(user);
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
@Override
public void update(final User user) {
__db.assertNotSuspendingTransaction();
__db.beginTransaction();
try {
__updateAdapterOfUser.handle(user);
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
}
@Override
public void deleteAll() {
__db.assertNotSuspendingTransaction();
final SupportSQLiteStatement _stmt = __preparedStmtOfDeleteAll.acquire();
try {
__db.beginTransaction();
try {
_stmt.executeUpdateDelete();
__db.setTransactionSuccessful();
} finally {
__db.endTransaction();
}
} finally {
__preparedStmtOfDeleteAll.release(_stmt);
}
}
@Override
public User login(final String email, final String password) {
final String _sql = "SELECT * FROM users WHERE email = ? AND password = ? LIMIT 1";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 2);
int _argIndex = 1;
if (email == null) {
_statement.bindNull(_argIndex);
} else {
_statement.bindString(_argIndex, email);
}
_argIndex = 2;
if (password == null) {
_statement.bindNull(_argIndex);
} else {
_statement.bindString(_argIndex, password);
}
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfUid = CursorUtil.getColumnIndexOrThrow(_cursor, "uid");
final int _cursorIndexOfName = CursorUtil.getColumnIndexOrThrow(_cursor, "name");
final int _cursorIndexOfEmail = CursorUtil.getColumnIndexOrThrow(_cursor, "email");
final int _cursorIndexOfPassword = CursorUtil.getColumnIndexOrThrow(_cursor, "password");
final int _cursorIndexOfAge = CursorUtil.getColumnIndexOrThrow(_cursor, "age");
final int _cursorIndexOfUtenteNumber = CursorUtil.getColumnIndexOrThrow(_cursor, "utenteNumber");
final int _cursorIndexOfProfilePictureUri = CursorUtil.getColumnIndexOrThrow(_cursor, "profilePictureUri");
final User _result;
if (_cursor.moveToFirst()) {
final String _tmpName;
if (_cursor.isNull(_cursorIndexOfName)) {
_tmpName = null;
} else {
_tmpName = _cursor.getString(_cursorIndexOfName);
}
final String _tmpEmail;
if (_cursor.isNull(_cursorIndexOfEmail)) {
_tmpEmail = null;
} else {
_tmpEmail = _cursor.getString(_cursorIndexOfEmail);
}
final String _tmpPassword;
if (_cursor.isNull(_cursorIndexOfPassword)) {
_tmpPassword = null;
} else {
_tmpPassword = _cursor.getString(_cursorIndexOfPassword);
}
final int _tmpAge;
_tmpAge = _cursor.getInt(_cursorIndexOfAge);
final String _tmpUtenteNumber;
if (_cursor.isNull(_cursorIndexOfUtenteNumber)) {
_tmpUtenteNumber = null;
} else {
_tmpUtenteNumber = _cursor.getString(_cursorIndexOfUtenteNumber);
}
_result = new User(_tmpName,_tmpEmail,_tmpPassword,_tmpAge,_tmpUtenteNumber);
_result.uid = _cursor.getInt(_cursorIndexOfUid);
if (_cursor.isNull(_cursorIndexOfProfilePictureUri)) {
_result.profilePictureUri = null;
} else {
_result.profilePictureUri = _cursor.getString(_cursorIndexOfProfilePictureUri);
}
} else {
_result = null;
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
@Override
public User checkUser(final String email) {
final String _sql = "SELECT * FROM users WHERE email = ? LIMIT 1";
final RoomSQLiteQuery _statement = RoomSQLiteQuery.acquire(_sql, 1);
int _argIndex = 1;
if (email == null) {
_statement.bindNull(_argIndex);
} else {
_statement.bindString(_argIndex, email);
}
__db.assertNotSuspendingTransaction();
final Cursor _cursor = DBUtil.query(__db, _statement, false, null);
try {
final int _cursorIndexOfUid = CursorUtil.getColumnIndexOrThrow(_cursor, "uid");
final int _cursorIndexOfName = CursorUtil.getColumnIndexOrThrow(_cursor, "name");
final int _cursorIndexOfEmail = CursorUtil.getColumnIndexOrThrow(_cursor, "email");
final int _cursorIndexOfPassword = CursorUtil.getColumnIndexOrThrow(_cursor, "password");
final int _cursorIndexOfAge = CursorUtil.getColumnIndexOrThrow(_cursor, "age");
final int _cursorIndexOfUtenteNumber = CursorUtil.getColumnIndexOrThrow(_cursor, "utenteNumber");
final int _cursorIndexOfProfilePictureUri = CursorUtil.getColumnIndexOrThrow(_cursor, "profilePictureUri");
final User _result;
if (_cursor.moveToFirst()) {
final String _tmpName;
if (_cursor.isNull(_cursorIndexOfName)) {
_tmpName = null;
} else {
_tmpName = _cursor.getString(_cursorIndexOfName);
}
final String _tmpEmail;
if (_cursor.isNull(_cursorIndexOfEmail)) {
_tmpEmail = null;
} else {
_tmpEmail = _cursor.getString(_cursorIndexOfEmail);
}
final String _tmpPassword;
if (_cursor.isNull(_cursorIndexOfPassword)) {
_tmpPassword = null;
} else {
_tmpPassword = _cursor.getString(_cursorIndexOfPassword);
}
final int _tmpAge;
_tmpAge = _cursor.getInt(_cursorIndexOfAge);
final String _tmpUtenteNumber;
if (_cursor.isNull(_cursorIndexOfUtenteNumber)) {
_tmpUtenteNumber = null;
} else {
_tmpUtenteNumber = _cursor.getString(_cursorIndexOfUtenteNumber);
}
_result = new User(_tmpName,_tmpEmail,_tmpPassword,_tmpAge,_tmpUtenteNumber);
_result.uid = _cursor.getInt(_cursorIndexOfUid);
if (_cursor.isNull(_cursorIndexOfProfilePictureUri)) {
_result.profilePictureUri = null;
} else {
_result.profilePictureUri = _cursor.getString(_cursorIndexOfProfilePictureUri);
}
} else {
_result = null;
}
return _result;
} finally {
_cursor.close();
_statement.release();
}
}
@NonNull
public static List<Class<?>> getRequiredConverters() {
return Collections.emptyList();
}
}

View File

@@ -40,22 +40,53 @@ public class RegisterActivity extends AppCompatActivity {
int age = Integer.parseInt(ageStr);
AppDatabase db = AppDatabase.getDatabase(getApplicationContext());
UserDao userDao = db.userDao();
binding.registerButton.setEnabled(false);
binding.registerButton.setText("A registar...");
AppDatabase.databaseWriteExecutor.execute(() -> {
User existing = userDao.checkUser(email);
if (existing != null) {
runOnUiThread(() -> Toast.makeText(this, "Email já registado", Toast.LENGTH_SHORT).show());
} else {
User newUser = new User(name, email, password, age, utenteStr);
userDao.insert(newUser);
runOnUiThread(() -> {
Toast.makeText(this, "Conta criada com sucesso!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, LoginActivity.class));
finish();
com.google.firebase.auth.FirebaseAuth mAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
com.google.firebase.firestore.FirebaseFirestore db = com.google.firebase.firestore.FirebaseFirestore
.getInstance();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
// Registration success, save additional info to Firestore
com.google.firebase.auth.FirebaseUser firebaseUser = mAuth.getCurrentUser();
if (firebaseUser != null) {
String userId = firebaseUser.getUid();
java.util.Map<String, Object> userMap = new java.util.HashMap<>();
userMap.put("uid", userId);
userMap.put("name", name);
userMap.put("email", email);
userMap.put("age", age);
userMap.put("utenteNumber", utenteStr);
userMap.put("profilePictureUri", ""); // Init empty
db.collection("users").document(userId)
.set(userMap)
.addOnSuccessListener(aVoid -> {
// Optional: Also save to local Room DB for offline cache if desired,
// but for now we focus on Firebase as requested.
Toast.makeText(RegisterActivity.this, "Conta criada com sucesso!",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
})
.addOnFailureListener(e -> {
binding.registerButton.setEnabled(true);
binding.registerButton.setText("Registar");
Toast.makeText(RegisterActivity.this, "Erro ao salvar dados: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
});
}
} else {
binding.registerButton.setEnabled(true);
binding.registerButton.setText("Registar");
Toast.makeText(RegisterActivity.this, "Falha no registo: " + task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
});
}
}

View File

@@ -1,21 +1,17 @@
package com.example.cuida.ui.sns24;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.cuida.databinding.FragmentSns24Binding;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.ai.client.generativeai.GenerativeModel;
import com.google.ai.client.generativeai.java.GenerativeModelFutures;
import com.google.ai.client.generativeai.type.Content;
@@ -23,110 +19,95 @@ import com.google.ai.client.generativeai.type.GenerateContentResponse;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import com.example.cuida.databinding.FragmentSns24Binding;
public class Sns24Fragment extends Fragment {
private FragmentSns24Binding binding;
private FusedLocationProviderClient fusedLocationClient;
private GenerativeModelFutures ai; // Equivalent to 'const ai = genkit(...)'
// API Key configurada
private GenerativeModelFutures model;
private static final String API_KEY = "AIzaSyBmLgn-SHaTDvAeDWsw2iTZRR9gahhOu7k";
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = FragmentSns24Binding.inflate(inflater, container, false);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity());
// Initialize Gemini (Android equivalent of Genkit gemini15Flash configuration)
try {
GenerativeModel gm = new GenerativeModel("gemini-1.5-flash", API_KEY);
ai = GenerativeModelFutures.from(gm);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getContext(), "Erro ao iniciar IA: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
binding.buttonCallSns.setOnClickListener(v -> {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:808242424"));
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getContext(), "Não foi possível realizar a chamada.", Toast.LENGTH_SHORT).show();
}
});
binding.buttonAiTriage.setOnClickListener(v -> performTriage());
return binding.getRoot();
}
private void performTriage() {
if (API_KEY.equals("YOUR_API_KEY")) {
Toast.makeText(getContext(), "Configure a API Key no ficheiro Sns24Fragment.java!", Toast.LENGTH_LONG)
.show();
return;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (ai == null) {
Toast.makeText(getContext(), "IA não inicializada. Verifique s Logs.", Toast.LENGTH_SHORT).show();
return;
}
// 1. Inicializar o Modelo Gemini
// NOTA: Substitua "SUA_API_KEY" pela sua chave do Google AI Studio
GenerativeModel gm = new GenerativeModel("gemini-1.5-flash", API_KEY);
model = GenerativeModelFutures.from(gm);
String symptoms = binding.inputSymptoms.getText().toString();
if (symptoms.isEmpty()) {
binding.inputSymptoms.setError("Por favor descreva o que sente");
return;
}
// 2. Botão Ligar SNS 24
binding.buttonCallSns.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:808242424"));
startActivity(intent);
});
// 3. Botão Triagem IA
binding.buttonAiTriage.setOnClickListener(v -> {
String symptoms = binding.inputSymptoms.getText().toString().trim();
if (!symptoms.isEmpty()) {
analyzeSymptomsWithGemini(symptoms);
} else {
Toast.makeText(getContext(), "Por favor, descreva os seus sintomas.", Toast.LENGTH_SHORT).show();
}
});
}
private void analyzeSymptomsWithGemini(String symptoms) {
// Feedback visual de carregamento
binding.buttonAiTriage.setEnabled(false);
binding.buttonAiTriage.setText("A analisar...");
binding.textAiResult.setVisibility(View.GONE);
binding.textAiResult.setVisibility(View.VISIBLE);
binding.textAiResult.setText("A analisar sintomas com IA...");
// This prompt structure is equivalent to the flow in Genkit
String prompt = "O utilizador está a sentir o seguinte: " + symptoms + ". " +
"Analisa a gravidade como 'gemini-1.5-flash'. Deves recomendar uma de duas opções: 'Ir ao Hospital' ou 'Ir ao Posto Médico'. "
+
"Explica brevemente o porquê. Responde em Português de Portugal.";
// Criar o prompt
Content content = new Content.Builder()
.addText("Atua como um assistente de triagem de saúde. O utilizador diz: \"" + symptoms + "\". " +
"Dá uma resposta curta (máximo 4 linhas) sobre a urgência e se deve ligar para o SNS 24 (808242424). "
+
"Aviso: Isto não substitui aconselhamento médico.")
.build();
Content content = new Content.Builder().addText(prompt).build();
Executor executor = Executors.newSingleThreadExecutor();
// Executar chamada assíncrona (usando Guava Futures para Java)
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
// Equivalent to: const { text } = await ai.generate(...)
ListenableFuture<GenerateContentResponse> response = ai.generateContent(content);
// Executor para rodar a resposta na UI Thread
// Creating a new single thread executor for the background work if needed,
// but the callback needs to run on main thread or handle UI updates on main
// thread.
// We use ContextCompat.getMainExecutor to be safe on API < 28 (minSdk is 24)
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String resultText = result.getText();
requireActivity().runOnUiThread(() -> {
if (getActivity() != null) {
binding.textAiResult.setText(result.getText());
binding.buttonAiTriage.setEnabled(true);
binding.buttonAiTriage.setText("Analisar Sintomas");
binding.textAiResult.setText(resultText);
binding.textAiResult.setVisibility(View.VISIBLE);
});
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
requireActivity().runOnUiThread(() -> {
if (getActivity() != null) {
binding.textAiResult.setText("Erro ao contactar a IA: " + t.getMessage());
binding.buttonAiTriage.setEnabled(true);
binding.buttonAiTriage.setText("Analisar Sintomas");
Toast.makeText(getContext(), "Erro na análise: " + t.getMessage(), Toast.LENGTH_LONG).show();
});
}
}
}, executor);
}, androidx.core.content.ContextCompat.getMainExecutor(requireContext()));
}
// AI Triage methods removed
// Nearest Hospital feature removed with AI Triage
@Override
public void onDestroyView() {
super.onDestroyView();