Merge branch 'bugfix/notification' into develop

This commit is contained in:
Jacques Foucry 2021-06-26 13:39:57 +02:00
commit 72fa1e5a5e
35 changed files with 615 additions and 690 deletions

View file

@ -1,116 +0,0 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<codeStyleSettings language="XML">
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
<arrangement>
<rules>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:android</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:id</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>style</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
<order>ANDROID_ATTRIBUTE_ORDER</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>.*</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
</rules>
</arrangement>
</codeStyleSettings>
</code_scheme>
</component>

View file

@ -1,7 +0,0 @@
<component name="ProjectDictionaryState">
<dictionary name="jacques">
<words>
<w>médicaments</w>
</words>
</dictionary>
</component>

View file

@ -3,9 +3,7 @@
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="org.jetbrains.plugins.gradle.execution.test.runner.AllInPackageGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer" />
<option value="org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer" />
<option value="com.android.tools.idea.compose.preview.runconfiguration.ComposePreviewRunConfigurationProducer" />
</set>
</option>
</component>

View file

@ -3,7 +3,7 @@ apply plugin: 'com.android.application'
ext.versionMajor = 0
ext.versionMinor = 0
ext.versionPatch = 20210406
ext.versionPatch = 20210513
ext.versionClassifier = null
ext.isSnapshot = false
ext.minimumSdkVersion = defaultMinSdkVersion
@ -18,6 +18,7 @@ android {
targetSdkVersion defaultTargetSdkVersion
versionCode generateVersionCode() // 190010203
versionName generateVersionName() // 1.2.3-SNAPSHOT
multiDexEnabled true
}
buildTypes {
@ -29,13 +30,14 @@ android {
productFlavors {
}
compileOptions {
coreLibraryDesugaringEnabled true
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
/*dexOptions {
incremental false
}*/
buildToolsVersion = buildToolsVersion1
allprojects {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
@ -44,7 +46,7 @@ android {
}
repositories {
jcenter()
mavenCentral()
}
sourceSets {
main {
@ -57,16 +59,19 @@ dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
testImplementation 'junit:junit:4.13.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.journeyapps:zxing-android-embedded:4.1.0'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.core:core:1.3.2'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'androidx.core:core:1.5.0'
debugImplementation 'com.amitshekhar.android:debug-db:1.0.6'
// debugImplementation 'com.amitshekhar.android:debug-db:1.0.6'
implementation 'io.sentry:sentry-android:4.3.0'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}
private Integer generateVersionCode() {

View file

@ -3,6 +3,7 @@ package net.foucry.pilldroid;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/

View file

@ -5,6 +5,7 @@
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
android:fullBackupContent="true"
@ -16,7 +17,7 @@
android:theme="@style/AppTheme"
android:allowBackup="true">
<activity
android:name=".MedicamentListActivity"
android:name=".DrugListActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
@ -25,34 +26,38 @@
</intent-filter>
</activity>
<activity
android:name=".MedicamentDetailActivity"
android:label="@string/title_medicament_detail"
android:parentActivityName=".MedicamentListActivity"
android:name=".DrugDetailActivity"
android:label="@string/title_drug_detail"
android:parentActivityName=".DrugListActivity"
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="net.foucry.pilldroid.MedicamentListActivity" />
android:value="net.foucry.pilldroid.DrugListActivity" />
</activity>
<activity
android:name=".WelcomeActivity"
android:label="Welcome"
android:parentActivityName=".MedicamentListActivity"
android:parentActivityName=".DrugListActivity"
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="net.foucry.pilldroid.MedicamentListActivity" />
android:value="net.foucry.pilldroid.DrugListActivity" />
</activity>
<activity
android:name=".About"
android:label="À propos de PillDroid"
android:parentActivityName=".MedicamentListActivity"
android:parentActivityName=".DrugListActivity"
android:theme="@style/AppTheme" />
<activity android:name=".CustomScannerActivity" />
<service
<!-- <service
android:name=".PillDroidJobService"
android:permission="android.permission.BIND_JOB_SERVICE" />
android:permission="android.permission.BIND_JOB_SERVICE" />-->
<receiver android:name="net.foucry.pilldroid.AlarmReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<meta-data android:name="io.sentry.dsn" android:value="https://ba17f240b58144e398c862bb953256ef@o755123.ingest.sentry.io/5792286" />
</application>
</manifest>

Binary file not shown.

Binary file not shown.

View file

@ -1,26 +1,29 @@
package net.foucry.pilldroid;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.icu.util.Calendar;
import android.util.Log;
import android.widget.Toast;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
public class AlarmReceiver extends BroadcastReceiver {
private static final String TAG = MedicamentDetailFragment.class.getName();
private static final String TAG = AlarmManager.class.getName();
NotificationManager nm;
NotificationManager notificationManager;
@Override
public void onReceive(Context context, Intent intent)
@ -28,32 +31,41 @@ public class AlarmReceiver extends BroadcastReceiver {
// Show the toast like in above screen shot
Log.d(TAG, "onReceive");
Toast.makeText(context, "New stock calculted", Toast.LENGTH_LONG).show();
// If BOOT_COMPLETED is received we launch an alarm in 10 second in order to
// start the alarmschedule process.
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Log.d(TAG, "StartUpBootReceiver BOOT_COMPLETED");
scheduleAlarm(context);
}
Toast.makeText(context, "New stock calculated", Toast.LENGTH_LONG).show();
createNotificationChannel(context);
DBHelper dbHelper = new DBHelper(context);
dbHelper.getAllDrugs();
List<Medicament> medicaments = dbHelper.getAllDrugs();
List<Drug> drugs = dbHelper.getAllDrugs();
Medicament firstMedicament = null;
Drug firstDrug = null;
try {
firstMedicament = medicaments.get(0);
firstDrug = drugs.get(0);
}
catch (Exception e){
Log.e(TAG, e.toString());
e.printStackTrace();
}
if (firstMedicament != null) {
if (firstMedicament.getPrise() != 0) {
if(firstMedicament.getStock() < firstMedicament.getAlertThreshold()) {
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (firstDrug != null) {
if (firstDrug.getTake() != 0) {
if(firstDrug.getStock() <= firstDrug.getAlertThreshold()) {
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
/* Notification notif = new Notification(R.drawable.ic_pill_alarm, "Crazy About Android...", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);*/
Intent notificationIntent = new Intent(context, DrugListActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "PillDroid")
.setSmallIcon(R.drawable.ic_pill_alarm)
@ -61,6 +73,7 @@ public class AlarmReceiver extends BroadcastReceiver {
.setContentText(context.getString(R.string.notification_text))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setColorized(true)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
@ -68,7 +81,7 @@ public class AlarmReceiver extends BroadcastReceiver {
notificationManager.notify(notificationId, builder.build());
} else
{
double dummy = (firstMedicament.getStock() - firstMedicament.getAlertThreshold());
double dummy = (firstDrug.getStock() - firstDrug.getAlertThreshold());
Log.d(TAG, "no notification scheduled " + dummy);
}
}
@ -83,25 +96,80 @@ public class AlarmReceiver extends BroadcastReceiver {
String description = context.getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
String CHANNEL_ID = "PillDroid";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
channel.enableLights(true);
channel.setLightColor(R.color.led);
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
try {
notificationManager.createNotificationChannel(channel);
} catch (Exception e) {
// This will catch any exception, because they are all descended from Exception
Log.e(TAG, e.toString());
//At the level Exception Class handle the error in Exception Table
// Exception Create That Error Object and throw it
//E.g: FileNotFoundException ,etc
e.printStackTrace();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
channel.enableLights(true);
channel.setLightColor(R.color.led);
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
try {
notificationManager.createNotificationChannel(channel);
} catch (Exception e) {
// This will catch any exception, because they are all descended from Exception
Log.e(TAG, e.toString());
//At the level Exception Class handle the error in Exception Table
// Exception Create That Error Object and throw it
//E.g: FileNotFoundException ,etc
e.printStackTrace();
}
}
}
public static void scheduleAlarm(Context context) {
Calendar calendar = Calendar.getInstance();
Date today;
Date tomorrow;
}
/*if (BuildConfig.DEBUG) {
calendar.add(Calendar.HOUR_OF_DAY, 12);
today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
tomorrow = calendar.getTime();
} else {*/
calendar.set(Calendar.HOUR_OF_DAY, 11);
today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
tomorrow = calendar.getTime();
// }
LocalTime todayNow = LocalTime.now();
if (todayNow.isBefore(LocalTime.NOON)) {
// schedule date = today
//calendar.setTimeInMillis(dateAtNoon(today).getTime());
calendar.setTimeInMillis(today.getTime());
} else {
// schedule date = tomorrow
calendar.setTimeInMillis(tomorrow.getTime());
}
/* if (BuildConfig.DEBUG)
{
calendar.setTimeInMillis(today.getTime());
}*/
PendingIntent alarmIntent;
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
boolean alarmUp = (PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp) {
Log.d(TAG, "Alarm already active");
}
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,(calendar.getTimeInMillis()),
AlarmManager.INTERVAL_DAY, alarmIntent);
Log.d(TAG, "Alarm scheduled for " + UtilDate.convertDate(calendar.getTimeInMillis()));
Toast.makeText(context, "Alarm scheduled for " + UtilDate.convertDate(calendar.getTimeInMillis()), Toast.LENGTH_SHORT).show();
}
}

View file

@ -16,37 +16,48 @@ import java.io.OutputStream;
/**
* Created by jfoucry on 5/25/16.
*/
class DBMedoc extends SQLiteOpenHelper {
class DBDrugs extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String dbName = "medicaments.db";
private static final String dbName = "drugs.db";
private final Context myContext;
private final SQLiteDatabase myDataBase = null;
private static final String TABLE_NAME = "medicaments";
private static final String MEDOC_CIS = "cis";
private static final String MEDOC_CIP13 = "cip13";
private static final String MEDOC_ADMIN = "mode_administration";
private static final String MEDOC_NOM = "nom";
private static final String MEDOC_PRES = "presentation";
private static final String TABLE_NAME = "drugs";
private static final String DRUG_CIS = "cis";
private static final String DRUG_CIP13 = "cip13";
private static final String DRUG_ADMIN = "administration_mode";
private static final String DRUG_NAME = "name";
private static final String DRUG_PRES = "presentation";
private static final String[] COLUMNS_NAMES = {MEDOC_CIS, MEDOC_CIP13, MEDOC_ADMIN, MEDOC_NOM, MEDOC_PRES};
private static final String[] COLUMNS_NAMES = {DRUG_CIS, DRUG_CIP13, DRUG_ADMIN, DRUG_NAME, DRUG_PRES};
private static final String TAG = DBMedoc.class.getName();
private static final String TAG = DBDrugs.class.getName();
DBMedoc(Context context) {
DBDrugs(Context context) {
super(context, dbName, null, DATABASE_VERSION);
this.myContext = context;
}
public boolean isDBFileExist(File database)
{
try {
myContext.getDatabasePath(String.valueOf(database));
} catch (final Exception exception) {
return false;
}
return true;
}
@Override
public synchronized SQLiteDatabase getWritableDatabase() {
File dbFile = myContext.getDatabasePath(dbName);
if (!dbFile.exists()) {
if (!isDBFileExist(dbFile)) {
copyDatabase(dbFile.getPath());
}
@ -57,8 +68,6 @@ class DBMedoc extends SQLiteOpenHelper {
public synchronized SQLiteDatabase getReadableDatabase() {
File dbFile = myContext.getDatabasePath(dbName);
//if (dbFile.exists()) return super.getReadableDatabase();
PrefManager prefManager = new PrefManager(myContext);
int oldVersion = prefManager.getDatabaseVersion();
@ -95,13 +104,6 @@ class DBMedoc extends SQLiteOpenHelper {
}
}
/* void openDatabase() throws SQLiteException {
Log.e(TAG, "openDatabase called");
String myPath = myContext.getDatabasePath(dbName).getPath();
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}*/
@Override
public synchronized void close() {
if (myDataBase != null) {
@ -113,10 +115,10 @@ class DBMedoc extends SQLiteOpenHelper {
* Lookup in the DB for a record corresponding to cip13
*
* @param cip13 string representing the object we're looking for
* @return return a medicament object
* @return return a drug object
*/
Medicament getMedocByCIP13(String cip13) {
Log.e(TAG, "CIP13 - " + cip13);
Drug getDrugByCIP13(String cip13) {
Log.d(TAG, "CIP13 - " + cip13);
SQLiteDatabase db = this.getReadableDatabase();
@ -134,28 +136,28 @@ class DBMedoc extends SQLiteOpenHelper {
cursor.moveToFirst();
// Build medicament object
Medicament medicament = new Medicament();
// medicament.setId(Integer.parseInt(cursor.getString(0)));
medicament.setCis(cursor.getString(0));
medicament.setCip13(cursor.getString(1));
medicament.setMode_administration(cursor.getString(2));
medicament.setNom(cursor.getString(3));
medicament.setPresentation(cursor.getString(4));
// Build drug object
Drug drug = new Drug();
// drug.setId(Integer.parseInt(cursor.getString(0)));
drug.setCis(cursor.getString(0));
drug.setCip13(cursor.getString(1));
drug.setAdministration_mode(cursor.getString(2));
drug.setNama(cursor.getString(3));
drug.setPresentation(cursor.getString(4));
// Set default values
medicament.setStock(0);
medicament.setPrise(0);
medicament.setWarnThreshold(14);
medicament.setAlertThreshold(7);
drug.setStock(0);
drug.setTake(0);
drug.setWarnThreshold(14);
drug.setAlertThreshold(7);
// Log
Log.d(TAG, "getDrug(" + cip13 + ")" + medicament.toString());
Log.d(TAG, "getDrug(" + cip13 + ")" + drug.toString());
// Return medicament
// Return drug
cursor.close();
return medicament;
return drug;
} else
return null;
}

View file

@ -6,12 +6,11 @@ import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.format.DateUtils;
import android.util.Log;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
@ -19,33 +18,34 @@ import java.util.List;
*/
class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final ThreadLocal<String> DATABASE_NAME = ThreadLocal.withInitial(() -> "ordonnance.db");
private static final String DATABASE_NAME = "prescription.db";
private static final String TABLE_DRUG = "drug";
private static final String KEY_ID = "id";
private static final String KEY_CIS = "cis";
private static final String KEY_CIP13 = "cip13";
private static final String KEY_NAME = "nom";
private static final String KEY_ADMIN = "mode_administration";
private static final String KEY_PRES = "presentation";
private static final String KEY_STOCK = "stock";
private static final String KEY_PRISE = "prise";
private static final String KEY_SEUIL_WARN = "warning";
private static final String KEY_SEUIL_ALERT = "alerte";
private static final String KEY_LAST_UPDATE = "last_update";
private static final String TABLE_DRUG = "drug";
private static final String KEY_ID = "id";
private static final String KEY_CIS = "cis";
private static final String KEY_CIP13 = "cip13";
private static final String KEY_NAME = "name";
private static final String KEY_ADMIN = "administration_mode";
private static final String KEY_PRES = "presentation";
private static final String KEY_STOCK = "stock";
private static final String KEY_TAKE = "take";
private static final String KEY_THRESHOLD_WARN = "warning";
private static final String KEY_THRESHOLD_ALERT = "alert";
private static final String KEY_LAST_UPDATE = "last_update";
final List<Medicament> medicaments = new ArrayList<>();
final List<Drug> drugs = new ArrayList<>();
private static final String TAG = DBHelper.class.getName();
private static final String[] COLUMS = {KEY_ID, KEY_CIS,KEY_CIP13, KEY_NAME, KEY_ADMIN, KEY_PRES, KEY_STOCK, KEY_PRISE,
KEY_SEUIL_WARN, KEY_SEUIL_ALERT, KEY_LAST_UPDATE};
private static final String[] COLUMS = {KEY_ID, KEY_CIS,KEY_CIP13, KEY_NAME, KEY_ADMIN, KEY_PRES, KEY_STOCK, KEY_TAKE,
KEY_THRESHOLD_WARN, KEY_THRESHOLD_ALERT, KEY_LAST_UPDATE};
DBHelper(Context context) {
super(context, DATABASE_NAME.get(), null, DATABASE_VERSION);
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
@ -54,13 +54,13 @@ class DBHelper extends SQLiteOpenHelper {
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"cis TEXT, " +
"cip13 TEXT, " +
"nom TEXT, " +
"mode_administration TEXT, " +
"name TEXT, " +
"administration_mode TEXT, " +
"presentation TEXT, " +
"stock REAL, " +
"prise REAL, " +
"take REAL, " +
"warning INT, " +
"alerte INT, " +
"alert INT, " +
"last_update LONG)";
db.execSQL(CREATE_DRUG_TABLE);
@ -87,30 +87,30 @@ class DBHelper extends SQLiteOpenHelper {
}
/**
* Split medicament values into database record and record it to the DB
* @param medicament the medicament object to be saved
* Split drug values into database record and record it to the DB
* @param drug the drug object to be saved
*/
void addDrug(Medicament medicament) {
void addDrug(Drug drug) {
// Logging
Log.d(TAG, medicament.toString());
Log.d(TAG, drug.toString());
// Get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// Create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_CIS, medicament.getCis());
values.put(KEY_CIP13, medicament.getCip13());
values.put(KEY_NAME, medicament.getNom());
values.put(KEY_ADMIN, medicament.getMode_administration());
values.put(KEY_PRES, medicament.getPresentation());
values.put(KEY_STOCK, medicament.getStock());
values.put(KEY_PRISE, medicament.getPrise());
values.put(KEY_SEUIL_WARN, medicament.getWarnThreshold());
values.put(KEY_SEUIL_ALERT, medicament.getAlertThreshold());
values.put(KEY_LAST_UPDATE, medicament.getDateLastUpdate());
values.put(KEY_CIS, drug.getCis());
values.put(KEY_CIP13, drug.getCip13());
values.put(KEY_NAME, drug.getName());
values.put(KEY_ADMIN, drug.getAdministration_mode());
values.put(KEY_PRES, drug.getPresentation());
values.put(KEY_STOCK, drug.getStock());
values.put(KEY_TAKE, drug.getTake());
values.put(KEY_THRESHOLD_WARN, drug.getWarnThreshold());
values.put(KEY_THRESHOLD_ALERT, drug.getAlertThreshold());
values.put(KEY_LAST_UPDATE, drug.getDateLastUpdate());
// Calculate some medicament's fields
// Calculate some drug's fields
// Insert
db.insert(TABLE_DRUG, // table
@ -122,61 +122,61 @@ class DBHelper extends SQLiteOpenHelper {
}
/**
* return a medicament from the DB with is id
* @param id of the medicament we looking for (not used)
* @return return the found medicament of null
* return a drug from the DB with is id
* @param id of the drug we looking for (not used)
* @return return the found drug of null
*/
public Medicament getDrug(int id) {
public Drug getDrug(int id) {
// Get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// Build query
Cursor cursor = db.query(TABLE_DRUG, // Which table
COLUMS, // column names
" id = ?", // selections
new String[] { String.valueOf(id) }, // selections args
Cursor cursor = db.query(TABLE_DRUG, // Which table
COLUMS, // column names
" id = ?", // selections
new String[] { String.valueOf(id) }, // selections args
null, // group by
null, // having
null, // having
null, // order by
null); // limits
null); // limits
Log.d(TAG, "Cursor == " + DatabaseUtils.dumpCursorToString(cursor));
// if case we got result, go to the first one
Medicament medicament = new Medicament();
Drug drug = new Drug();
if (cursor != null) {
cursor.moveToFirst();
// Build medicament object
medicament.setId(Integer.parseInt(cursor.getString(0)));
medicament.setCis(cursor.getString(1));
medicament.setCip13(cursor.getString(2));
medicament.setNom(cursor.getString(3));
medicament.setMode_administration(cursor.getString(4));
medicament.setPresentation(cursor.getString(5));
medicament.setStock(Double.parseDouble(cursor.getString(6)));
medicament.setPrise(Double.parseDouble(cursor.getString(7)));
medicament.setWarnThreshold(Integer.parseInt(cursor.getString(8)));
medicament.setAlertThreshold(Integer.parseInt(cursor.getString(9)));
medicament.setDateLastUpdate(Long.parseLong(cursor.getString(10)));
// Build drug object
drug.setId(Integer.parseInt(cursor.getString(0)));
drug.setCis(cursor.getString(1));
drug.setCip13(cursor.getString(2));
drug.setNama(cursor.getString(3));
drug.setAdministration_mode(cursor.getString(4));
drug.setPresentation(cursor.getString(5));
drug.setStock(Double.parseDouble(cursor.getString(6)));
drug.setTake(Double.parseDouble(cursor.getString(7)));
drug.setWarnThreshold(Integer.parseInt(cursor.getString(8)));
drug.setAlertThreshold(Integer.parseInt(cursor.getString(9)));
drug.setDateLastUpdate(Long.parseLong(cursor.getString(10)));
}
// Log
Log.d(TAG, "getDrug("+id+")" + medicament.toString());
Log.d(TAG, "getDrug("+id+")" + drug.toString());
assert cursor != null;
cursor.close();
db.close();
// Return medicament
// Return drug
return medicament;
return drug;
}
/**
*
* @param cip13 drug id in French nomemclature
* @return the medicament object found in DB or null
* @return the drug object found in DB or null
*/
public Medicament getDrugByCIP13(String cip13) {
public Drug getDrugByCIP13(String cip13) {
// Get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
@ -191,38 +191,38 @@ class DBHelper extends SQLiteOpenHelper {
null); // limits
// if case we got result, go to the first one
Medicament medicament = new Medicament();
Drug drug = new Drug();
if (cursor != null) {
cursor.moveToFirst();
// Build medicament object
medicament.setId(Integer.parseInt(cursor.getString(0)));
medicament.setCis(cursor.getString(1));
medicament.setCip13(cursor.getString(2));
medicament.setNom(cursor.getString(3));
medicament.setMode_administration(cursor.getString(4));
medicament.setPresentation(cursor.getString(5));
medicament.setStock(Double.parseDouble(cursor.getString(6)));
medicament.setPrise(Double.parseDouble(cursor.getString(7)));
medicament.setWarnThreshold(Integer.parseInt(cursor.getString(8)));
medicament.setAlertThreshold(Integer.parseInt(cursor.getString(9)));
medicament.setDateLastUpdate(Long.parseLong(cursor.getString(10)));
// Build drug object
drug.setId(Integer.parseInt(cursor.getString(0)));
drug.setCis(cursor.getString(1));
drug.setCip13(cursor.getString(2));
drug.setNama(cursor.getString(3));
drug.setAdministration_mode(cursor.getString(4));
drug.setPresentation(cursor.getString(5));
drug.setStock(Double.parseDouble(cursor.getString(6)));
drug.setTake(Double.parseDouble(cursor.getString(7)));
drug.setWarnThreshold(Integer.parseInt(cursor.getString(8)));
drug.setAlertThreshold(Integer.parseInt(cursor.getString(9)));
drug.setDateLastUpdate(Long.parseLong(cursor.getString(10)));
}
assert cursor != null;
cursor.close();
Log.d(TAG, "getDrug(" + cip13 + ")" + medicament.toString());
Log.d(TAG, "getDrug(" + cip13 + ")" + drug.toString());
return medicament;
return drug;
}
/**
*
* @return a Sorted and updated by dateEndOfStock List of All medicaments presents in database
* @return a Sorted and updated by dateEndOfStock List of All drugs presents in database
*/
List<Medicament> getAllDrugs() {
List<Drug> getAllDrugs() {
// Build the query
String query = "SELECT * FROM " + TABLE_DRUG;
@ -233,92 +233,102 @@ class DBHelper extends SQLiteOpenHelper {
Log.d(TAG, "Cursor == " + DatabaseUtils.dumpCursorToString(cursor));
// For Each row, build a medicament and add it to the list
Medicament medicament;
// For Each row, build a drug and add it to the list
Drug drug;
if (cursor.moveToFirst()) {
do {
medicament = new Medicament();
medicament.setId(Integer.parseInt(cursor.getString(0)));
medicament.setCis(cursor.getString(1));
medicament.setCip13(cursor.getString(2));
medicament.setNom(cursor.getString(3));
medicament.setMode_administration(cursor.getString(4));
medicament.setPresentation(cursor.getString(5));
medicament.setStock(Double.parseDouble(cursor.getString(6)));
medicament.setPrise(Double.parseDouble(cursor.getString(7)));
medicament.setWarnThreshold(Integer.parseInt(cursor.getString(8)));
medicament.setAlertThreshold(Integer.parseInt(cursor.getString(9)));
medicament.setDateLastUpdate(Long.parseLong(cursor.getString(10)));
drug = new Drug();
drug.setId(Integer.parseInt(cursor.getString(0)));
drug.setCis(cursor.getString(1));
drug.setCip13(cursor.getString(2));
drug.setNama(cursor.getString(3));
drug.setAdministration_mode(cursor.getString(4));
drug.setPresentation(cursor.getString(5));
drug.setStock(Double.parseDouble(cursor.getString(6)));
drug.setTake(Double.parseDouble(cursor.getString(7)));
drug.setWarnThreshold(Integer.parseInt(cursor.getString(8)));
drug.setAlertThreshold(Integer.parseInt(cursor.getString(9)));
drug.setDateLastUpdate(Long.parseLong(cursor.getString(10)));
// Call calcul method
medicament.setDateEndOfStock();
drug.setDateEndOfStock();
// Add medicament to medicaments
medicaments.add(medicament);
// Add drug to Drugs
drugs.add(drug);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
Medicament currentMedicament;
Drug currentDrug;
for (int position = 0 ; position < getCount() ; position++ ) {
currentMedicament = getItem(position);
currentDrug = getItem(position);
// if (!DateUtils.isToday(currentMedicament.getDateLastUpdate()))
// {
currentMedicament.newStock();
updateDrug(currentMedicament);
//}
if (!DateUtils.isToday(currentDrug.getDateLastUpdate()))
{
currentDrug.newStock();
updateDrug(currentDrug);
}
}
medicaments.sort(new Comparator<Medicament>() {
Log.d(TAG, "Before sort == " + drugs.toString());
/*drugs.sort(Comparator.comparing(Drug::getDateEndOfStock)
.thenComparing(Drug::getStock));*/
drugs.sort(new Comparator<Drug>() {
@Override
public int compare(Medicament lhs, Medicament rhs) {
return lhs.getDateEndOfStock().compareTo(rhs.getDateEndOfStock());
public int compare(Drug lhs, Drug rhs) {
if (lhs.getDateEndOfStock().compareTo(rhs.getDateEndOfStock()) != 0)
return lhs.getDateEndOfStock().compareTo(rhs.getDateEndOfStock());
else
return (int) (lhs.getStock() - rhs.getStock());
}
});
Log.d(TAG, "After sort " + drugs.toString());
// Move medicament with prise = 0 at the end of the list
// Move drug with prise = 0 at the end of the list
for (int position = 0 ; position < getCount() ; position++ ) {
currentMedicament = getItem(position);
double currentPrise = currentMedicament.getPrise();
if (currentPrise == 0)
currentDrug = getItem(position);
double currentTake = currentDrug.getTake();
if (currentTake == 0)
{
medicament = medicaments.remove(position);
medicaments.add(medicaments.size(), medicament);
drug = drugs.remove(position);
drugs.add(drugs.size(), drug);
}
}
Log.d(TAG, "getAllDrugs " + medicaments.toString());
return medicaments;
return drugs;
}
/**
*
* @param medicament object to be updated in DB
* @param drug object to be updated in DB
*/
public void updateDrug(Medicament medicament) {
public void updateDrug(Drug drug) {
Log.d(TAG, "Update Drug == " + medicament);
Log.d(TAG, "Update Drug == " + drug.toString());
// Get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// Create ContentValues to add columnm/value
ContentValues values = new ContentValues();
values.put(KEY_ID, medicament.getId());
values.put(KEY_CIS, medicament.getCis());
values.put(KEY_CIP13, medicament.getCip13());
values.put(KEY_NAME, medicament.getNom());
values.put(KEY_ADMIN, medicament.getMode_administration());
values.put(KEY_PRES, medicament.getPresentation());
values.put(KEY_STOCK, medicament.getStock());
values.put(KEY_PRISE, medicament.getPrise());
values.put(KEY_LAST_UPDATE, medicament.getDateLastUpdate());
values.put(KEY_ID, drug.getId());
values.put(KEY_CIS, drug.getCis());
values.put(KEY_CIP13, drug.getCip13());
values.put(KEY_NAME, drug.getName());
values.put(KEY_ADMIN, drug.getAdministration_mode());
values.put(KEY_PRES, drug.getPresentation());
values.put(KEY_STOCK, drug.getStock());
values.put(KEY_TAKE, drug.getTake());
values.put(KEY_THRESHOLD_WARN, drug.getWarnThreshold());
values.put(KEY_THRESHOLD_ALERT, drug.getAlertThreshold());
values.put(KEY_LAST_UPDATE, drug.getDateLastUpdate());
String[] selectionArgs = { String.valueOf(medicament.getId()) };
String[] selectionArgs = { String.valueOf(drug.getId()) };
db.update(TABLE_DRUG, // table
values, // column/value
@ -327,31 +337,32 @@ class DBHelper extends SQLiteOpenHelper {
// Close DB
db.close();
Log.d(TAG, "values == " + values.toString());
}
/**
* Delete a medicament object in database
* @param medicament object to be delete in the DB
* Delete a drug object in database
* @param drug object to be delete in the DB
*/
public void deleteDrug(Medicament medicament) {
public void deleteDrug(Drug drug) {
// Get writable database
SQLiteDatabase db = this.getWritableDatabase();
// Delete record
db.delete(TABLE_DRUG, // table
KEY_ID+ " = ?", // selections
new String[] { String.valueOf(medicament.getId()) } ); // selections args
new String[] { String.valueOf(drug.getId()) } ); // selections args
// Close DB
db.close();
// log
Log.d(TAG, "delete drug "+medicament);
Log.d(TAG, "delete drug "+ drug);
}
/**
* Get count of all medicament present in database
* @return number of medicament in DB
* Get count of all drug present in database
* @return number of drug in DB
*/
int getCount() {
@ -368,11 +379,11 @@ class DBHelper extends SQLiteOpenHelper {
return count;
}
public Medicament getItem(int position) {
return medicaments.get(position);
public Drug getItem(int position) {
return drugs.get(position);
}
boolean isMedicamentExist(String cip13) {
boolean isDrugExist(String cip13) {
boolean value = false;
try {
Cursor c = this.getReadableDatabase().rawQuery("SELECT * FROM "+ TABLE_DRUG + " where cip13 = "+cip13, null);

View file

@ -1,26 +1,29 @@
package net.foucry.pilldroid;
import android.util.Log;
import java.io.Serializable;
import java.lang.String;
import java.util.Calendar;
import java.util.Date;
import static net.foucry.pilldroid.UtilDate.*;
import static net.foucry.pilldroid.UtilDate.dateAtNoon;
import static net.foucry.pilldroid.UtilDate.nbOfDaysBetweenDateAndToday;
/**
* Created by jacques on 26/11/15.
*/
public class Medicament implements Serializable {
public class Drug implements Serializable {
private static final String TAG = Drug.class.getName();
/* part read form database */
private int id;
private String nom;
private String nama;
private String cip13;
private String cis;
private String mode_administration;
private String administration_mode;
private String presentation;
private double stock;
private double prise;
private double take;
private int warnThreshold;
private int alertThreshold;
private long dateLastUpdate;
@ -28,20 +31,20 @@ public class Medicament implements Serializable {
/* calculate part */
private Date dateEndOfStock;
Medicament() {
Drug() {
}
Medicament(final String cis, final String cip13, final String nom, final String mode_administration, final String presentation,
double stock, double prise, int warn, int alert, long dateLastUpdate) {
Drug(final String cis, final String cip13, final String nama, final String administration_mode, final String presentation,
double stock, double take, int warn, int alert, long dateLastUpdate) {
super();
this.cis = cis;
this.cip13 = cip13;
this.nom = nom;
this.mode_administration = mode_administration;
this.nama = nama;
this.administration_mode = administration_mode;
this.presentation = presentation;
this.stock = stock;
this.prise = prise;
this.take = take;
this.warnThreshold = warn;
this.alertThreshold = alert;
this.dateLastUpdate = dateLastUpdate;
@ -52,8 +55,8 @@ public class Medicament implements Serializable {
return id;
}
String getNom() {
return nom;
String getName() {
return nama;
}
String getCip13() {
@ -64,8 +67,8 @@ public class Medicament implements Serializable {
return cis;
}
String getMode_administration() {
return mode_administration;
String getAdministration_mode() {
return administration_mode;
}
String getPresentation() {
@ -76,8 +79,8 @@ public class Medicament implements Serializable {
return stock;
}
double getPrise() {
return prise;
double getTake() {
return take;
}
int getAlertThreshold() {
@ -100,8 +103,8 @@ public class Medicament implements Serializable {
this.id = id;
}
void setNom(String nom) {
this.nom = nom;
void setNama(String nama) {
this.nama = nama;
}
void setCip13(String cip13) {
@ -112,8 +115,8 @@ public class Medicament implements Serializable {
this.cis = cis;
}
void setMode_administration(String mode_administration) {
this.mode_administration = mode_administration;
void setAdministration_mode(String administration_mode) {
this.administration_mode = administration_mode;
}
void setPresentation(String presentation) {
@ -124,8 +127,8 @@ public class Medicament implements Serializable {
this.stock = stock;
}
void setPrise(double prise) {
this.prise = prise;
void setTake(double take) {
this.take = take;
}
void setWarnThreshold(int warn) {
@ -146,8 +149,8 @@ public class Medicament implements Serializable {
void setDateEndOfStock() {
int numberDayOfPrise;
if (this.prise > 0) {
numberDayOfPrise = (int) Math.floor(this.stock / this.prise);
if (this.take > 0) {
numberDayOfPrise = (int) Math.floor(this.stock / this.take);
} else {
numberDayOfPrise = 0;
}
@ -161,10 +164,13 @@ public class Medicament implements Serializable {
}
void newStock() {
Log.d(TAG, "current drug = " + this.toString());
Date lastUpdate = new Date(getDateLastUpdate());
int numberOfDays = nbOfDaysBetweenDateAndToday(lastUpdate);
if (numberOfDays > 0) {
double takeDuringPeriod = this.prise * numberOfDays;
double takeDuringPeriod = this.take * numberOfDays;
setStock(getStock() - takeDuringPeriod);
setDateLastUpdate(new Date().getTime());
}

View file

@ -2,10 +2,6 @@ package net.foucry.pilldroid;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
@ -13,21 +9,25 @@ import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.Date;
import static net.foucry.pilldroid.R.id.detail_toolbar;
/**
* An activity representing a single Medicament detail screen. This
* An activity representing a single Drug detail screen. This
* activity is only used narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {@link MedicamentListActivity}.
* in a {@link DrugListActivity}.
*/
public class MedicamentDetailActivity extends AppCompatActivity {
public class DrugDetailActivity extends AppCompatActivity {
private static final String TAG = MedicamentDetailActivity.class.getName();
private static final String TAG = DrugDetailActivity.class.getName();
Medicament medicament;
Drug drug;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -37,12 +37,12 @@ public class MedicamentDetailActivity extends AppCompatActivity {
/* fetching the string passed with intent using extras*/
assert extras != null;
medicament = (Medicament) extras.getSerializable("medicament");
drug = (Drug) extras.getSerializable("drug");
assert medicament != null;
Log.d(TAG, "medicament == " + medicament.toString());
assert drug != null;
Log.d(TAG, "drug == " + drug.toString());
setContentView(R.layout.activity_medicament_detail);
setContentView(R.layout.activity_durg_detail);
Toolbar toolbar = findViewById(detail_toolbar);
@ -56,7 +56,7 @@ public class MedicamentDetailActivity extends AppCompatActivity {
public void onClick(View view) {
Log.d(TAG, "Click on save icon");
getMedicamentChanges();
getMDrugChanges();
setResult(1);
finish();
overridePendingTransition(R.anim.slide_from_left, R.anim.slide_to_right);
@ -67,7 +67,7 @@ public class MedicamentDetailActivity extends AppCompatActivity {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(medicament.getNom());
actionBar.setTitle(drug.getName());
}
// savedInstanceState is non-null when there is fragment state
@ -83,12 +83,12 @@ public class MedicamentDetailActivity extends AppCompatActivity {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putSerializable("medicament",
getIntent().getSerializableExtra("medicament"));
MedicamentDetailFragment fragment = new MedicamentDetailFragment();
arguments.putSerializable("drug",
getIntent().getSerializableExtra("drug"));
DrugDetailFragment fragment = new DrugDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.medicament_detail_container, fragment)
.add(R.id.drug_detail_container, fragment)
.commit();
}
}
@ -103,57 +103,57 @@ public class MedicamentDetailActivity extends AppCompatActivity {
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, MedicamentListActivity.class));
navigateUpTo(new Intent(this, DrugListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
private void getMedicamentChanges()
private void getMDrugChanges()
{
Log.d(TAG, "Time to save new values");
DBHelper dbHelper = new DBHelper(this);
Medicament newMedicament = dbHelper.getDrugByCIP13(medicament.getCip13());
Drug newDrug = dbHelper.getDrugByCIP13(drug.getCip13());
View stockView;
View priseView;
View takeView;
View warningView;
View alertView;
stockView = findViewById(R.id.stock_cell);
EditText stockTextView = stockView.findViewById(R.id.valeur);
EditText stockTextView = stockView.findViewById(R.id.value);
String stockValue = stockTextView.getText().toString();
priseView = findViewById(R.id.prise_cell);
TextView priseTextView = priseView.findViewById(R.id.valeur);
String priseValue = priseTextView.getText().toString();
takeView = findViewById(R.id.take_cell);
TextView takeTextView = takeView.findViewById(R.id.value);
String takeValue = takeTextView.getText().toString();
alertView = findViewById(R.id.alert_cell);
TextView alertTextView = alertView.findViewById(R.id.valeur);
TextView alertTextView = alertView.findViewById(R.id.value);
String alertValue = alertTextView.getText().toString();
warningView = findViewById(R.id.warning_cell);
TextView warningTextView = warningView.findViewById(R.id.valeur);
TextView warningTextView = warningView.findViewById(R.id.value);
String warningValue = warningTextView.getText().toString();
Log.d(TAG, "StockValue == "+ stockValue);
Log.d(TAG, "PriseValue == "+ priseValue);
/* Log.d(TAG, "StockValue == "+ stockValue);
Log.d(TAG, "TakeValue == "+ takeValue);
Log.d(TAG, "AlertValue == "+ alertValue);
Log.d(TAG, "WarningValue == "+ warningValue);
Log.d(TAG, "medicamentID == "+ medicament.getId());
Log.d(TAG, "medicament == "+ medicament.toString());
Log.d(TAG, "medicamentID == "+ drug.getId());
Log.d(TAG, "drug == "+ drug.toString());*/
newMedicament.setStock(Double.parseDouble(stockValue));
newMedicament.setPrise(Double.parseDouble(priseValue));
newMedicament.setWarnThreshold(Integer.parseInt(warningValue));
newMedicament.setAlertThreshold(Integer.parseInt(alertValue));
// newMedicament.setDateLastUpdate(UtilDate.dateAtNoon(new Date()).getTime());
newMedicament.setDateLastUpdate(new Date().getTime());
newMedicament.setDateEndOfStock();
newDrug.setStock(Double.parseDouble(stockValue));
newDrug.setTake(Double.parseDouble(takeValue));
newDrug.setWarnThreshold(Integer.parseInt(warningValue));
newDrug.setAlertThreshold(Integer.parseInt(alertValue));
// newDrug.setDateLastUpdate(UtilDate.dateAtNoon(new Date()).getTime());
newDrug.setDateLastUpdate(new Date().getTime());
newDrug.setDateEndOfStock();
dbHelper.updateDrug(newMedicament);
dbHelper.updateDrug(newDrug);
}
}

View file

@ -12,29 +12,29 @@ import android.view.ViewGroup;
import android.widget.TextView;
/**
* A fragment representing a single Medicament detail screen.
* This fragment is either contained in a {@link MedicamentListActivity}
* in two-pane mode (on tablets) or a {@link MedicamentDetailActivity}
* A fragment representing a single Drug detail screen.
* This fragment is either contained in a {@link DrugListActivity}
* in two-pane mode (on tablets) or a {@link DrugDetailActivity}
* on handsets.
*/
public class MedicamentDetailFragment extends Fragment {
public class DrugDetailFragment extends Fragment {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
public static final String ARG_ITEM_ID = "medicament";
public static final String ARG_ITEM_ID = "drug";
/**
* The dummy content this fragment is presenting.
*/
private Medicament medicament;
private Drug drug;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public MedicamentDetailFragment() {
public DrugDetailFragment() {
}
@Override
@ -46,79 +46,79 @@ public class MedicamentDetailFragment extends Fragment {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
medicament = (Medicament) getArguments().getSerializable(ARG_ITEM_ID);
drug = (Drug) getArguments().getSerializable(ARG_ITEM_ID);
Activity activity = this.getActivity();
assert activity != null;
CollapsingToolbarLayout appBarLayout = activity.findViewById(R.id.toolbar_layout);
if (appBarLayout != null) {
appBarLayout.setTitle(medicament.getNom());
appBarLayout.setTitle(drug.getName());
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View detailView = inflater.inflate(R.layout.medicament_detail, container, false);
View detailView = inflater.inflate(R.layout.drug_detail, container, false);
View nameView;
View adminModeView;
View presentationView;
View stockView;
View priseView;
View takeView;
View warningView;
View alertView;
// Show the dummy content as text in a TextView.
if (medicament != null) {
if (drug != null) {
// Find each conponment of rootView
nameView = detailView.findViewById(R.id.name_cell);
TextView nameLabel = nameView.findViewById(R.id.label);
TextView nameValeur = nameView.findViewById(R.id.valeur);
nameLabel.setText(R.string.med_name_label);
nameValeur.setText(medicament.getNom());
TextView nameValue = nameView.findViewById(R.id.value);
nameLabel.setText(R.string.drug_name_label);
nameValue.setText(drug.getName());
presentationView = detailView.findViewById(R.id.presentation_cell);
TextView presentationLabel = presentationView.findViewById(R.id.label);
TextView presentationValeur = presentationView.findViewById(R.id.valeur);
presentationLabel.setText(R.string.med_presention_labal);
presentationValeur.setText(medicament.getPresentation());
TextView presentationValue = presentationView.findViewById(R.id.value);
presentationLabel.setText(R.string.drug_presention_labal);
presentationValue.setText(drug.getPresentation());
adminModeView = detailView.findViewById(R.id.administration_cell);
TextView adminModeLabel = adminModeView.findViewById(R.id.label);
TextView adminModeValeur = adminModeView.findViewById(R.id.valeur);
adminModeLabel.setText(R.string.med_administationMode_label);
adminModeValeur.setText(medicament.getMode_administration());
TextView adminModeValue = adminModeView.findViewById(R.id.value);
adminModeLabel.setText(R.string.drug_administationMode_label);
adminModeValue.setText(drug.getAdministration_mode());
stockView = detailView.findViewById(R.id.stock_cell);
TextView stockLibelle = (stockView.findViewById(R.id.libelle));
TextView stockValue = stockView.findViewById(R.id.valeur);
stockLibelle.setText(R.string.med_current_stock_label);
stockValue.setText(Double.toString(medicament.getStock()));
stockValue.setHint(R.string.med_current_stock_label);
TextView stockLibelle = (stockView.findViewById(R.id.label));
TextView stockValue = stockView.findViewById(R.id.value);
stockLibelle.setText(R.string.drug_current_stock_label);
stockValue.setText(Double.toString(drug.getStock()));
stockValue.setHint(R.string.drug_current_stock_label);
stockValue.setSelectAllOnFocus(true);
priseView = detailView.findViewById(R.id.prise_cell);
TextView priseLibelle = priseView.findViewById(R.id.libelle);
TextView priseValue = (priseView.findViewById(R.id.valeur));
priseLibelle.setText(R.string.med_take_label);
priseValue.setText(Double.toString(medicament.getPrise()));
priseValue.setHint(R.string.med_take_label);
takeView = detailView.findViewById(R.id.take_cell);
TextView priseLabel = takeView.findViewById(R.id.label);
TextView priseValue = (takeView.findViewById(R.id.value));
priseLabel.setText(R.string.drug_take_label);
priseValue.setText(Double.toString(drug.getTake()));
priseValue.setHint(R.string.drug_take_label);
priseValue.setSelectAllOnFocus(true);
warningView = detailView.findViewById(R.id.warning_cell);
TextView warningLibelle = warningView.findViewById(R.id.libelle);
TextView warningValue = warningView.findViewById(R.id.valeur);
warningLibelle.setText(R.string.med_warningTherehold_label);
warningValue.setText(Integer.toString(medicament.getWarnThreshold()));
warningValue.setHint(R.string.med_warningTherehold_label);
TextView warningLibelle = warningView.findViewById(R.id.label);
TextView warningValue = warningView.findViewById(R.id.value);
warningLibelle.setText(R.string.drug_warningTherehold_label);
warningValue.setText(Integer.toString(drug.getWarnThreshold()));
warningValue.setHint(R.string.drug_warningTherehold_label);
warningValue.setSelectAllOnFocus(true);
alertView = detailView.findViewById(R.id.alert_cell);
TextView alertLibelle = alertView.findViewById(R.id.libelle);
TextView alertValue = alertView.findViewById(R.id.valeur);
alertLibelle.setText(R.string.med_alertTherehold_label);
alertValue.setText(Integer.toString(medicament.getAlertThreshold()));
alertValue.setHint(R.string.med_alertTherehold_label);
TextView alertLibelle = alertView.findViewById(R.id.label);
TextView alertValue = alertView.findViewById(R.id.value);
alertLibelle.setText(R.string.drug_alertTherehold_label);
alertValue.setText(Integer.toString(drug.getAlertThreshold()));
alertValue.setHint(R.string.drug_alertTherehold_label);
alertValue.setSelectAllOnFocus(true);
}

View file

@ -1,13 +1,11 @@
package net.foucry.pilldroid;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.icu.util.Calendar;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
@ -34,23 +32,24 @@ import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import io.sentry.Sentry;
import static net.foucry.pilldroid.UtilDate.date2String;
import static net.foucry.pilldroid.Utils.intRandomExclusive;
/**
* An activity representing a list of Medicaments. This activity
* An activity representing a list of Drugs is activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {@link MedicamentDetailActivity} representing
* lead to a {@link DrugDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
public class MedicamentListActivity extends AppCompatActivity {
public class DrugListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
@ -59,6 +58,7 @@ public class MedicamentListActivity extends AppCompatActivity {
// TODO: Change DEMO/DBDEMO form static to non-static. In order to create fake data at only at launchtime
final Boolean DEMO = false;
final Boolean DBDEMO = false;
public final int CUSTOMIZED_REQUEST_CODE = 0x0000ffff;
/**
@ -86,35 +86,35 @@ public class MedicamentListActivity extends AppCompatActivity {
super.onStop();
}
private static final String TAG = MedicamentListActivity.class.getName();
private static final String TAG = DrugListActivity.class.getName();
private DBHelper dbHelper;
private DBMedoc dbMedoc;
private DBDrugs dbDrug;
private List<Medicament> medicaments;
private List<Drug> drugs;
private SimpleItemRecyclerViewAdapter mAdapter;
public int getCount() {
return medicaments.size();
return drugs.size();
}
public Medicament getItem(int position) {
return medicaments.get(position);
public Drug getItem(int position) {
return drugs.get(position);
}
public void constructMedsList()
public void constructDrugsList()
{
dbHelper = new DBHelper(getApplicationContext());
if (!(medicaments == null)) {
if (!medicaments.isEmpty()) {
medicaments.clear();
if (!(drugs == null)) {
if (!drugs.isEmpty()) {
drugs.clear();
}
}
medicaments = dbHelper.getAllDrugs();
drugs = dbHelper.getAllDrugs();
View mRecyclerView = findViewById(R.id.medicament_list);
View mRecyclerView = findViewById(R.id.drug_list);
assert mRecyclerView != null;
setupRecyclerView((RecyclerView) mRecyclerView);
}
@ -123,10 +123,12 @@ public class MedicamentListActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicament_list);
setContentView(R.layout.activity_drug_list);
dbHelper = new DBHelper(this);
dbMedoc = new DBMedoc(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
dbHelper = new DBHelper(this);
}
dbDrug = new DBDrugs(this);
Toolbar toolbar = findViewById(R.id.toolbar);
@ -152,40 +154,40 @@ public class MedicamentListActivity extends AppCompatActivity {
final int min_prise=0;
final int max_prise=3;
dbHelper.addDrug(new Medicament("60000011", "3400930000011", "Médicament test 01", "orale",
dbHelper.addDrug(new Drug("60000011", "3400930000011", "Médicament test 01", "orale",
"plaquette(s) thermoformée(s) PVC PVDC aluminium de 10 comprimé(s)",
intRandomExclusive(min_stock, max_stock), intRandomExclusive(min_prise, max_prise), 14, 7, UtilDate.dateAtNoon(new Date()).getTime()));
dbHelper.addDrug(new Medicament("60000012", "3400930000012", "Médicament test 02", "orale",
dbHelper.addDrug(new Drug("60000012", "3400930000012", "Médicament test 02", "orale",
"plaquette(s) thermoformée(s) PVC PVDC aluminium de 10 comprimé(s)",
intRandomExclusive(min_stock, max_stock), intRandomExclusive(min_prise, max_prise), 14, 7, UtilDate.dateAtNoon(new Date()).getTime()));
dbHelper.addDrug(new Medicament("60000013", "3400930000013", "Médicament test 03", "orale",
dbHelper.addDrug(new Drug("60000013", "3400930000013", "Médicament test 03", "orale",
"plaquette(s) thermoformée(s) PVC PVDC aluminium de 10 comprimé(s)",
intRandomExclusive(min_stock, max_stock), intRandomExclusive(min_prise, max_prise), 14, 7, UtilDate.dateAtNoon(new Date()).getTime()));
dbHelper.addDrug(new Medicament("60000014", "3400930000014", "Médicament test 04", "orale",
dbHelper.addDrug(new Drug("60000014", "3400930000014", "Médicament test 04", "orale",
"plaquette(s) thermoformée(s) PVC PVDC aluminium de 10 comprimé(s)",
intRandomExclusive(min_stock, max_stock), intRandomExclusive(min_prise, max_prise), 14, 7, UtilDate.dateAtNoon(new Date()).getTime()));
dbHelper.addDrug(new Medicament("60000015", "3400930000015", "Médicament test 05", "orale",
dbHelper.addDrug(new Drug("60000015", "3400930000015", "Médicament test 05", "orale",
"plaquette(s) thermoformée(s) PVC PVDC aluminium de 10 comprimé(s)",
intRandomExclusive(min_stock, max_stock), intRandomExclusive(min_prise, max_prise), 14, 7, UtilDate.dateAtNoon(new Date()).getTime()));
dbHelper.addDrug(new Medicament("60000016", "3400930000016", "Médicament test 06", "orale",
dbHelper.addDrug(new Drug("60000016", "3400930000016", "Médicament test 06", "orale",
"plaquette(s) thermoformée(s) PVC PVDC aluminium de 10 comprimé(s)",
intRandomExclusive(min_stock, max_stock), intRandomExclusive(min_prise, max_prise), 14, 7, UtilDate.dateAtNoon(new Date()).getTime()));
dbHelper.addDrug(new Medicament("60000017", "3400930000017", "Médicament test 07", "orale",
dbHelper.addDrug(new Drug("60000017", "3400930000017", "Médicament test 07", "orale",
"plaquette(s) thermoformée(s) PVC PVDC aluminium de 10 comprimé(s)",
intRandomExclusive(min_stock, max_stock), intRandomExclusive(min_prise, max_prise), 14, 7, UtilDate.dateAtNoon(new Date()).getTime()));
dbHelper.addDrug(new Medicament("60000018", "3400930000018", "Médicament test 08", "orale",
dbHelper.addDrug(new Drug("60000018", "3400930000018", "Médicament test 08", "orale",
"plaquette(s) thermoformée(s) PVC PVDC aluminium de 10 comprimé(s)",
intRandomExclusive(min_stock, max_stock), intRandomExclusive(min_prise, max_prise), 14, 7, UtilDate.dateAtNoon(new Date()).getTime()));
dbHelper.addDrug(new Medicament("60000019", "3400930000019", "Médicament test 09", "orale",
dbHelper.addDrug(new Drug("60000019", "3400930000019", "Médicament test 09", "orale",
"plaquette(s) thermoformée(s) PVC PVDC aluminium de 10 comprimé(s)",
intRandomExclusive(min_stock, max_stock), intRandomExclusive(min_prise, max_prise), 14, 7, UtilDate.dateAtNoon(new Date()).getTime()));
dbHelper.addDrug(new Medicament("60000010", "3400930000010", "Médicament test 10", "orale",
dbHelper.addDrug(new Drug("60000010", "3400930000010", "Médicament test 10", "orale",
"plaquette(s) thermoformée(s) PVC PVDC aluminium de 10 comprimé(s)",
intRandomExclusive(min_stock, max_stock), intRandomExclusive(min_prise, max_prise), 14, 7, UtilDate.dateAtNoon(new Date()).getTime()));
}
}
constructMedsList();
constructDrugsList();
}
@ -212,7 +214,8 @@ public class MedicamentListActivity extends AppCompatActivity {
public void onPause() {
super.onPause();
scheduleAlarm();
Log.d(TAG, "onPause really!");
AlarmReceiver.scheduleAlarm(this);
}
public void onResume() {
@ -238,12 +241,7 @@ public class MedicamentListActivity extends AppCompatActivity {
if (requestCode == CUSTOMIZED_REQUEST_CODE) {
Toast.makeText(this, "REQUEST_CODE = " + requestCode + "RESULT_CODE = " + resultCode, Toast.LENGTH_LONG).show();
Log.d(TAG, "REQUEST_CODE = " + requestCode + " RESULT_CODE = " + resultCode);
if (resultCode == 1) {
constructMedsList();
} else {
Toast.makeText(this, "What are you doing here?", Toast.LENGTH_SHORT).show();
Log.d(TAG, "What are you doing here?");
}
constructDrugsList();
} else {
IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);
@ -283,9 +281,9 @@ public class MedicamentListActivity extends AppCompatActivity {
cip13 = result.getContents().substring(4, 17);
}
// Get Medoc from database
final Medicament scannedMedoc = dbMedoc.getMedocByCIP13(cip13);
askToAddInDB(scannedMedoc);
// Get Drug from database
final Drug scannedDrug = dbDrug.getDrugByCIP13(cip13);
askToAddInDB(scannedDrug);
}
}
}
@ -295,9 +293,9 @@ public class MedicamentListActivity extends AppCompatActivity {
*/
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MedicamentListActivity.this);
LayoutInflater layoutInflater = LayoutInflater.from(DrugListActivity.this);
View promptView = layoutInflater.inflate(R.layout.input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MedicamentListActivity.this);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(DrugListActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = promptView.findViewById(R.id.edittext);
@ -308,8 +306,8 @@ public class MedicamentListActivity extends AppCompatActivity {
.setPositiveButton("OK", (dialog, id) -> {
String cip13 = editText.getText().toString();
Medicament med = dbMedoc.getMedocByCIP13(cip13);
askToAddInDB(med);
Drug aDrug = dbDrug.getDrugByCIP13(cip13);
askToAddInDB(aDrug);
})
.setNegativeButton("Cancel",
(dialog, id) -> dialog.cancel());
@ -330,35 +328,31 @@ public class MedicamentListActivity extends AppCompatActivity {
@Override
public void afterTextChanged(Editable s) {
if (s.length() != 13 ) {
alert.getButton(alert.BUTTON_POSITIVE).setEnabled(false);
} else {
alert.getButton(alert.BUTTON_POSITIVE).setEnabled(true);
}
alert.getButton(alert.BUTTON_POSITIVE).setEnabled(s.length() == 13);
}
});
alert.show();
}
/**
* Ask if the medicament found in the database should be include in the
* Ask if the drug found in the database should be include in the
* user database
* @param med Medicament- medicament to be added
* @param aDrug Drug- drug to be added
*/
private void askToAddInDB(Medicament med) {
private void askToAddInDB(Drug aDrug) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this);
dlg.setTitle(getString(R.string.app_name));
if (med != null) {
String msg = med.getNom() + " " + getString(R.string.msgFound);
if (aDrug != null) {
String msg = aDrug.getName() + " " + getString(R.string.msgFound);
dlg.setMessage(msg);
dlg.setNegativeButton(getString(R.string.button_cancel), (dialog, which) -> {
// Nothing to do in case of cancel
});
dlg.setPositiveButton(getString(R.string.button_ok), (dialog, which) -> {
// Add Medicament to DB then try to show it
addMedToList(med);
// Add Drug to DB then try to show it
addDrugToList(aDrug);
});
} else {
dlg.setMessage(getString(R.string.msgNotFound));
@ -370,63 +364,29 @@ public class MedicamentListActivity extends AppCompatActivity {
}
/**
* Add New medicament to the user database
* @param med Medicament - medicament to be added
* Add New drug to the user database
* @param aDrug Drug - drug to be added
*/
private void addMedToList(Medicament med)
private void addDrugToList(Drug aDrug)
{
med.setDateEndOfStock();
mAdapter.addItem(med);
aDrug.setDateEndOfStock();
mAdapter.addItem(aDrug);
Log.d(TAG, "Call MedicamentDetailActivity");
Log.d(TAG, "Call DrugDetailActivity");
Context context = this;
Intent intent = new Intent(context, MedicamentDetailActivity.class);
intent.putExtra("medicament", med);
Intent intent = new Intent(context, DrugDetailActivity.class);
intent.putExtra("drug", aDrug);
startActivityForResult(intent, CUSTOMIZED_REQUEST_CODE);
overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
}
/**
* scheduleAlarm()
*/
public void scheduleAlarm() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,12);
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
LocalTime todayNow = LocalTime.now();
if (todayNow.isBefore(LocalTime.NOON)) {
// schedule date = today
//calendar.setTimeInMillis(dateAtNoon(today).getTime());
calendar.setTimeInMillis(today.getTime());
} else {
// schedule date = tomorrow
calendar.setTimeInMillis(tomorrow.getTime());
}
PendingIntent alarmIntent;
Intent intent = new Intent(this, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
Log.d(TAG, "Alarm scheduled for " + UtilDate.convertDate(calendar.getTimeInMillis()));
}
/**
* setupRecyclerView (list of medicaments
* setupRecyclerView (list of drugs
* @param recyclerView RecyclerView
*/
private void setupRecyclerView(@NonNull RecyclerView recyclerView) {
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getApplicationContext()));
mAdapter = new SimpleItemRecyclerViewAdapter(medicaments);
mAdapter = new SimpleItemRecyclerViewAdapter(drugs);
recyclerView.setAdapter(mAdapter);
}
@ -446,19 +406,19 @@ public class MedicamentListActivity extends AppCompatActivity {
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<Medicament> mValues;
private final List<Drug> mValues;
SimpleItemRecyclerViewAdapter(List<Medicament> items) {
SimpleItemRecyclerViewAdapter(List<Drug> items) {
mValues = items;
}
void addItem(Medicament scannedMedoc) {
if (!dbHelper.isMedicamentExist(scannedMedoc.getCip13())) {
mValues.add(scannedMedoc);
void addItem(Drug scannedDrug) {
if (!dbHelper.isDrugExist(scannedDrug.getCip13())) {
mValues.add(scannedDrug);
notifyDataSetChanged();
dbHelper.addDrug(scannedMedoc);
dbHelper.addDrug(scannedDrug);
} else {
Toast.makeText(getApplicationContext(), "aleready in the database", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "already in the database", Toast.LENGTH_SHORT).show();
}
}
@ -466,7 +426,7 @@ public class MedicamentListActivity extends AppCompatActivity {
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.medicament_list_content, parent, false);
.inflate(R.layout.drug_list_content, parent, false);
return new ViewHolder(view);
}
@ -475,23 +435,24 @@ public class MedicamentListActivity extends AppCompatActivity {
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE d MMMM yyyy", Locale.getDefault());
String dateEndOfStock = date2String(mValues.get(position).getDateEndOfStock(), dateFormat);
Log.d(TAG, "Drug name == " + mValues.get(position).getName());
Log.d(TAG, "dateEndOfStock == " + dateEndOfStock);
Log.d(TAG, "stock == " + mValues.get(position).getStock());
Log.d(TAG, "prise == " + mValues.get(position).getPrise());
Log.d(TAG, "take == " + mValues.get(position).getTake());
Log.d(TAG, "warn == " + mValues.get(position).getWarnThreshold());
Log.d(TAG, "alert == " + mValues.get(position).getAlertThreshold());
holder.mItem = mValues.get(position);
holder.mIDView.setText(mValues.get(position).getCip13());
holder.mContentView.setText(mValues.get(position).getNom());
holder.mContentView.setText(mValues.get(position).getName());
holder.mEndOfStock.setText(dateEndOfStock);
// Test to change background programmatically
if (mValues.get(position).getPrise() == 0) {
if (mValues.get(position).getTake() == 0) {
holder.mView.setBackgroundResource(R.drawable.gradient_bg);
holder.mIconView.setImageResource(R.drawable.ic_suspended_pill);
} else {
int remainingStock = (int) Math.floor(mValues.get(position).getStock() / mValues.get(position).getPrise());
int remainingStock = (int) Math.floor(mValues.get(position).getStock() / mValues.get(position).getTake());
if (remainingStock <= mValues.get(position).getAlertThreshold()) {
holder.mView.setBackgroundResource(R.drawable.gradient_bg_alert);
holder.mIconView.setImageResource(R.drawable.lower_stock_vect);
@ -508,10 +469,10 @@ public class MedicamentListActivity extends AppCompatActivity {
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Medicament medicamentCourant = mValues.get(position);
Drug drugCourant = mValues.get(position);
Context context = v.getContext();
Intent intent = new Intent(context, MedicamentDetailActivity.class);
intent.putExtra("medicament", medicamentCourant);
Intent intent = new Intent(context, DrugDetailActivity.class);
intent.putExtra("drug", drugCourant);
startActivityForResult(intent, CUSTOMIZED_REQUEST_CODE);
overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left);
}
@ -530,13 +491,13 @@ public class MedicamentListActivity extends AppCompatActivity {
final TextView mEndOfStock;
final ImageView mIconView;
Medicament mItem;
Drug mItem;
ViewHolder(View view) {
super(view);
mView = view;
mIDView = view.findViewById(R.id.cip13);
mContentView = view.findViewById(R.id.valeur);
mContentView = view.findViewById(R.id.value);
mEndOfStock = view.findViewById(R.id.endOfStock);
mIconView = view.findViewById(R.id.list_image);
}

View file

@ -46,25 +46,25 @@ public class PillDroidJobService extends JobService {
if (jobCancelled) {
return;
}
List<Medicament> medicaments = dbHelper.getAllDrugs();
List<Drug> drugs = dbHelper.getAllDrugs();
Medicament firstMedicament = null;
Drug firstDrug = null;
try {
firstMedicament = medicaments.get(0);
firstDrug = drugs.get(0);
}
catch (Exception e){
Log.e(TAG, e.toString());
e.printStackTrace();
}
if (firstMedicament != null) {
if (firstMedicament.getPrise() != 0) {
if(firstMedicament.getStock() < firstMedicament.getAlertThreshold()) {
if (firstDrug != null) {
if (firstDrug.getTake() != 0) {
if(firstDrug.getStock() < firstDrug.getAlertThreshold()) {
scheduleNotification();
} else
{
double dummy = (firstMedicament.getStock() - firstMedicament.getAlertThreshold());
double dummy = (firstDrug.getStock() - firstDrug.getAlertThreshold());
Log.d(TAG, "no notification scheduled " + dummy);
}
}
@ -88,7 +88,7 @@ public class PillDroidJobService extends JobService {
void scheduleNotification() {
Log.d(TAG, "schedule notification");
createNotificationChannel();
Intent intent = new Intent(this, MedicamentListActivity.class);
Intent intent = new Intent(this, DrugListActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "PillDroid")
.setSmallIcon(R.drawable.ic_pill_alarm)
@ -113,20 +113,24 @@ public class PillDroidJobService extends JobService {
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
String CHANNEL_ID = "PillDroid";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
try {
notificationManager.createNotificationChannel(channel);
} catch (Exception e) {
// This will catch any exception, because they are all descended from Exception
Log.e(TAG, e.toString());
//At the level Exception Class handle the error in Exception Table
// Exception Create That Error Object and throw it
//E.g: FileNotFoundException ,etc
e.printStackTrace();
NotificationChannel channel;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
try {
notificationManager.createNotificationChannel(channel);
} catch (Exception e) {
// This will catch any exception, because they are all descended from Exception
Log.e(TAG, e.toString());
//At the level Exception Class handle the error in Exception Table
// Exception Create That Error Object and throw it
//E.g: FileNotFoundException ,etc
e.printStackTrace();
}
}
}
}

View file

@ -2,10 +2,11 @@ package net.foucry.pilldroid;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;
public class Utils {
private static final String TAG = UtilDate.class.getName();
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
@ -33,4 +34,5 @@ public class Utils {
Random r = new Random();
return r.nextInt(max - min) +max;
}
}

View file

@ -124,7 +124,7 @@ public class WelcomeActivity extends AppCompatActivity {
void launchHomeScreen() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(WelcomeActivity.this, MedicamentListActivity.class));
startActivity(new Intent(WelcomeActivity.this, DrugListActivity.class));
finish();
}

View file

@ -2,7 +2,7 @@
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<!-- Gradient Bg for listrow -->
<gradient
android:startColor="#FFD4666E"
android:endColor="#FFBD1421"
android:startColor="#FFBD1421"
android:endColor="#FFD4666E"
android:angle="270" />
</shape>

View file

@ -4,5 +4,5 @@
<gradient
android:startColor="#FF048F01"
android:endColor="#FF5CB65A"
android:angle="90" />
android:angle="270" />
</shape>

View file

@ -4,5 +4,5 @@
<gradient
android:startColor="#FFF8A253"
android:endColor="#FFF7C01E"
android:angle="90" />
android:angle="270" />
</shape>

View file

@ -9,7 +9,7 @@
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
android:showDividers="middle"
tools:context="net.foucry.pilldroid.MedicamentListActivity">
tools:context="net.foucry.pilldroid.DrugListActivity">
<!--
This layout is a two-pane layout for the Medicaments
@ -19,18 +19,18 @@
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/medicament_list"
android:id="@+id/drug_list"
android:name="net.foucry.pilldroid.MedicamentListFragment"
android:layout_width="@dimen/item_width"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context="net.foucry.pilldroid.MedicamentListActivity"
tools:listitem="@layout/medicament_list_content" />
tools:context="net.foucry.pilldroid.DrugListActivity"
tools:listitem="@layout/drug_list_content" />
<FrameLayout
android:id="@+id/medicament_detail_container"
android:id="@+id/drug_detail_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />

View file

@ -5,7 +5,7 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MedicamentListActivity">
tools:context=".DrugListActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/app_bar"
@ -28,7 +28,7 @@
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<include
layout="@layout/medicament_list"
layout="@layout/drug_list"
android:layout_height="match_parent"
android:layout_width="match_parent"/>

View file

@ -6,7 +6,7 @@
android:background="@drawable/list_selector"
android:backgroundTint="@android:color/transparent"
android:fitsSystemWindows="true"
tools:context="net.foucry.pilldroid.MedicamentDetailActivity"
tools:context="net.foucry.pilldroid.DrugDetailActivity"
tools:ignore="MergeRootFrame">
<com.google.android.material.appbar.AppBarLayout
@ -35,7 +35,7 @@
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="@+id/medicament_detail_container"
android:id="@+id/drug_detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
@ -51,7 +51,7 @@
android:contentDescription="@string/save_button"
android:src="@drawable/ic_save_black_24dp"
app:backgroundTint="@android:color/transparent"
app:layout_anchor="@+id/medicament_detail_container"
app:layout_anchor="@+id/drug_detail_container"
app:layout_anchorGravity="top|end" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

View file

@ -1,10 +1,10 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/medicament_detail"
android:id="@+id/drug_detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="net.foucry.pilldroid.MedicamentDetailFragment">
tools:context="net.foucry.pilldroid.DrugDetailFragment">
<include
android:id="@+id/name_cell"
@ -35,7 +35,7 @@
android:layout_marginTop="30sp" />
<include
android:id="@+id/prise_cell"
android:id="@+id/take_cell"
layout="@layout/value_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

View file

@ -2,11 +2,11 @@
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/medicament_list"
android:id="@+id/drug_list"
android:name="net.foucry.pilldroid.MedicamentListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="LinearLayoutManager"
android:background="@drawable/list_selector"
tools:context="net.foucry.pilldroid.MedicamentListActivity"
tools:listitem="@layout/medicament_list_content" />
tools:context="net.foucry.pilldroid.DrugListActivity"
tools:listitem="@layout/drug_list_content" />

View file

@ -15,15 +15,15 @@
android:layout_height="50sp"
android:layout_marginStart="5dp"
android:src="@drawable/ok_stock_vect"
android:contentDescription="@string/icone_de_stock"
android:contentDescription="@string/stockIcon"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
<TextView
android:id="@+id/valeur"
android:id="@+id/value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/nom_m_dicament"
android:text="@string/drugName"
android:textColor="#040404"
android:typeface="sans"
android:textSize="16sp"
@ -39,7 +39,7 @@
android:textColor="#343434"
android:textSize="14sp"
android:text="@string/cip13_goes_here"
android:layout_below="@+id/valeur"
android:layout_below="@+id/value"
android:layout_toEndOf="@+id/list_image"
android:layout_marginStart="5dp" />

View file

@ -5,7 +5,7 @@
android:background="@drawable/list_selector">
<TextView
android:id="@+id/valeur"
android:id="@+id/value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="10sp"
@ -19,7 +19,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/label"
android:layout_below="@+id/valeur"
android:layout_below="@+id/value"
android:layout_alignParentStart="true"
android:textStyle="italic"
android:textColor="#0c4758"

View file

@ -8,13 +8,13 @@
android:background="@drawable/list_selector"
android:weightSum="1">
<TextView
android:id="@+id/libelle"
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/valeur"
android:layout_alignBottom="@+id/value"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_toStartOf="@id/valeur"
android:layout_toStartOf="@id/value"
android:gravity="center_vertical"
android:paddingStart="5dp"
android:paddingEnd="25dp"
@ -24,7 +24,7 @@
android:textStyle="bold" />
<EditText
android:id="@+id/valeur"
android:id="@+id/value"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentTop="true"
@ -33,7 +33,7 @@
android:ems="10"
android:gravity="end|fill_vertical"
android:inputType="numberDecimal"
android:labelFor="@id/valeur"
android:labelFor="@id/value"
android:paddingEnd="25dp"
android:paddingStart="5dp"
android:hint="@string/zero"

View file

@ -14,7 +14,7 @@
<ImageView
android:layout_width="@dimen/screen_shot_height"
android:layout_height="@dimen/screen_shot_height"
android:contentDescription="@string/medicament_info"
android:contentDescription="@string/drug_info"
android:src="@drawable/info" />
<TextView

View file

@ -1,20 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">PillDroid</string>
<string name="title_medicament_detail">Détail Médicament</string>
<string name="title_drug_detail">Détail Médicament</string>
<string name="button_cancel">Annuler</string>
<string name="button_ok">OK</string>
<string name="med_presention_labal">Présentation</string>
<string name="med_name_label">Nom</string>
<string name="med_administationMode_label">Mode d\'adminitration</string>
<string name="drug_presention_labal">Présentation</string>
<string name="drug_name_label">Nom</string>
<string name="drug_administationMode_label">Mode d\'adminitration</string>
<string name="msgNotFound">Médicament introuvable dans la base de données</string>
<string name="about">À propos</string>
<string name="help">Aide</string>
<string name="med_take_label">Prise</string>
<string name="med_alertTherehold_label">Seuil critique</string>
<string name="med_warningTherehold_label">Seuil d\'alerte</string>
<string name="drug_take_label">Prise</string>
<string name="drug_alertTherehold_label">Seuil critique</string>
<string name="drug_warningTherehold_label">Seuil d\'alerte</string>
<string name="msgFound">Médicament trouvé dans la base de données</string>
<string name="med_current_stock_label">Stock courant</string>
<string name="drug_current_stock_label">Stock courant</string>
<string name="turn_off_flashlight">Éteindre le flash</string>
<string name="turn_on_flashlight">Allumer le flash</string>
<string name="notification_text">Vous devez passer à la pharmacie</string>
@ -55,7 +55,7 @@
<string name="neutral_face">Visage neutre</string>
<string name="unhappy_face">Visage grincheux</string>
<string name="slide8_desc">Informations sur le médicament</string>
<string name="medicament_info">Capture d\'écran sur la partie information du médicament</string>
<string name="drug_info">Capture d\'écran sur la partie information du médicament</string>
<string name="slide9_desc">Réglages du stock courant, prise et valeurs d\'attention et d\'alerte</string>
<string name="tunables">Réglages</string>
<string name="slide10_desc">Mettre la prise à zéro suspend le traitement et les calculs de stock</string>
@ -67,8 +67,8 @@
<string name="next">Suivant</string>
<string name="start">Démarrer</string>
<string name="add_button">Ajout d\'un médicament à votre liste</string>
<string name="nom_m_dicament">Nom Médicament</string>
<string name="icone_de_stock">Icône de stock</string>
<string name="drugName">Nom Médicament</string>
<string name="stockIcon">Icône de stock</string>
<string name="cip13_goes_here">Ici le cip13</string>
<string name="Date">lundi 1 janvier 2001</string>
<string name="Value">Valeur</string>

View file

@ -1,6 +1,6 @@
<resources>
<string name="app_name">PillDroid</string>
<string name="title_medicament_detail">Medicament Detail</string>
<string name="title_drug_detail">Drug Detail</string>
<string name="button_cancel">Cancel</string>
<string name="button_ok">OK</string>
<string name="msgNotFound">Drug not found in the database</string>
@ -10,13 +10,13 @@
<string name="notification_text">You have to go to the pharmacy</string>
<string name="turn_on_flashlight">Turn Flash On</string>
<string name="turn_off_flashlight">Turn Flash Off</string>
<string name="med_name_label">Name</string>
<string name="med_presention_labal">Presentation</string>
<string name="med_administationMode_label">Administration mode</string>
<string name="med_current_stock_label">Current stock</string>
<string name="med_take_label">Take</string>
<string name="med_warningTherehold_label">Alert therehold</string>
<string name="med_alertTherehold_label">Critical threhold</string>
<string name="drug_name_label">Name</string>
<string name="drug_presention_labal">Presentation</string>
<string name="drug_administationMode_label">Administration mode</string>
<string name="drug_current_stock_label">Current stock</string>
<string name="drug_take_label">Take</string>
<string name="drug_warningTherehold_label">Alert therehold</string>
<string name="drug_alertTherehold_label">Critical therehold</string>
<string name="button_keyboard">"Use the keyboard"</string>
<string name="detail_view">Detail view</string>
<string name="scan_action">Scan a drug barcode</string>
@ -47,7 +47,7 @@
<string name="pilldroid_icon">PillDroid Icon</string>
<string name="the_plus_icon">The plus icon</string>
<string name="slide4_desc">In order to find the CIP13</string>
<string name="slide5_desc">Stock is ok</string>
<string name="slide5_desc">Stock is OK</string>
<string name="slide6_desc">Warning stock in rising down</string>
<string name="slide7_desc">Alert stock too low</string>
<string name="happy_face">Happy face</string>
@ -56,23 +56,23 @@
<string name="neutral_face">neutral face</string>
<string name="unhappy_face">unhappy face</string>
<string name="slide8_desc">Drug info</string>
<string name="medicament_info">Drug info screenshot</string>
<string name="drug_info">Drug info screenshot</string>
<string name="slide9_desc">Tunables informations</string>
<string name="tunables">Tunables</string>
<string name="slide10_desc">Take to 0 to suspend treatment</string>
<string name="suspended_treatment_icon">Treatment suspended icon</string>
<string name="slide11_desc">To save changes</string>
<string name="save_icon">The save icon</string>
<string name="slide12_desc">Thansk for using PillDroid</string>
<string name="slide12_desc">Thanks for using PillDroid</string>
<string name="skip">Skip</string>
<string name="next">Next</string>
<string name="start">Start</string>
<string name="zero" translatable="false">0</string>
<string name="add_button">Add new medicament in list</string>
<string name="nom_m_dicament">Drug Name</string>
<string name="icone_de_stock">Stock Icon</string>
<string name="add_button">Add new drug in list</string>
<string name="drugName">Drug Name</string>
<string name="stockIcon">Stock Icon</string>
<string name="cip13_goes_here">cip13 goes here</string>
<string name="Date">lundi 1 janvier 2001</string>
<string name="Date">Monday January 1st 2001</string>
<string name="Value">Value</string>
<string name="label">Label</string>
</resources>

View file

@ -1,15 +0,0 @@
package net.foucry.pilldroid;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}

View file

@ -9,7 +9,7 @@ buildscript {
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.3'
classpath 'com.android.tools.build:gradle:4.2.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files

View file

@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip