From 9fa217d587a94209530cf6043a8401ab3f1dbfc2 Mon Sep 17 00:00:00 2001 From: jacques Date: Fri, 11 Mar 2022 21:45:43 +0100 Subject: [PATCH] Use new Medic object for both presciptions (the list of medications user take, and medications, the complete database; Need a migration between version 1 an 2 of the database schema --- .../2.json | 88 +++++++++++ .../foucry/pilldroid/DrugDetailActivity.java | 39 +++-- .../foucry/pilldroid/DrugListActivity.java | 141 +++++++++--------- .../foucry/pilldroid/PilldroidDatabase.java | 2 +- .../java/net/foucry/pilldroid/UtilDate.java | 4 +- .../net/foucry/pilldroid/dao/MedicDAO.java | 11 +- .../net/foucry/pilldroid/models/Medic.java | 60 ++++++-- 7 files changed, 241 insertions(+), 104 deletions(-) create mode 100644 app/schemas/net.foucry.pilldroid.PilldroidDatabase/2.json diff --git a/app/schemas/net.foucry.pilldroid.PilldroidDatabase/2.json b/app/schemas/net.foucry.pilldroid.PilldroidDatabase/2.json new file mode 100644 index 0000000..b18c00f --- /dev/null +++ b/app/schemas/net.foucry.pilldroid.PilldroidDatabase/2.json @@ -0,0 +1,88 @@ +{ + "formatVersion": 1, + "database": { + "version": 2, + "identityHash": "ed6d0a13273d73ba9fcec1f374251efa", + "entities": [ + { + "tableName": "medics", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`cis` TEXT NOT NULL, `cip13` TEXT, `name` TEXT, `administration_mode` TEXT, `presentation` TEXT, `stock` REAL, `take` REAL, `warning` INTEGER, `alert` INTEGER, `last_update` INTEGER, PRIMARY KEY(`cis`))", + "fields": [ + { + "fieldPath": "cis", + "columnName": "cis", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "cip13", + "columnName": "cip13", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "administration_mode", + "columnName": "administration_mode", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "presentation", + "columnName": "presentation", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "stock", + "columnName": "stock", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "take", + "columnName": "take", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "warning", + "columnName": "warning", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "alert", + "columnName": "alert", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "last_update", + "columnName": "last_update", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "columnNames": [ + "cis" + ], + "autoGenerate": false + }, + "indices": [], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ed6d0a13273d73ba9fcec1f374251efa')" + ] + } +} \ No newline at end of file diff --git a/app/src/main/java/net/foucry/pilldroid/DrugDetailActivity.java b/app/src/main/java/net/foucry/pilldroid/DrugDetailActivity.java index 21061a6..bf6e138 100644 --- a/app/src/main/java/net/foucry/pilldroid/DrugDetailActivity.java +++ b/app/src/main/java/net/foucry/pilldroid/DrugDetailActivity.java @@ -17,6 +17,9 @@ import java.util.Date; import static net.foucry.pilldroid.R.id.detail_toolbar; +import net.foucry.pilldroid.dao.MedicDAO; +import net.foucry.pilldroid.models.Medic; + /** * An activity representing a single Drug detail screen. This * activity is only used narrow width devices. On tablet-size devices, @@ -27,7 +30,7 @@ public class DrugDetailActivity extends AppCompatActivity { private static final String TAG = DrugDetailActivity.class.getName(); - Drug drug; + Medic aMedic; @Override protected void onCreate(Bundle savedInstanceState) { @@ -38,10 +41,10 @@ public class DrugDetailActivity extends AppCompatActivity { /* fetching the string passed with intent using ‘extras’*/ assert bundle != null; - drug = (Drug) bundle.getSerializable("drug"); + aMedic = (Medic) bundle.getSerializable("medic"); - assert drug != null; - Log.d(TAG, "drug == " + drug); + assert aMedic != null; + Log.d(TAG, "aMedic == " + aMedic); /* fetching the string passed with intent using ‘bundle’*/ @@ -69,7 +72,7 @@ public class DrugDetailActivity extends AppCompatActivity { ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(false); - actionBar.setTitle(drug.getName()); + actionBar.setTitle(aMedic.getName()); } // savedInstanceState is non-null when there is fragment state @@ -114,9 +117,12 @@ public class DrugDetailActivity extends AppCompatActivity { private void getMDrugChanges() { Log.d(TAG, "Time to save new values"); + PilldroidDatabase prescriptions = null; DBHelper dbHelper = new DBHelper(this); + assert false; + MedicDAO medicDAO = prescriptions.getMedicDAO(); - Drug newDrug = dbHelper.getDrugByCIP13(drug.getCip13()); + Medic newMedic = medicDAO.getMedicByCIP13(aMedic.getCip13()); View stockView; View takeView; @@ -139,18 +145,19 @@ public class DrugDetailActivity extends AppCompatActivity { TextView warningTextView = warningView.findViewById(R.id.value); String warningValue = warningTextView.getText().toString(); - newDrug.setStock(Double.parseDouble(stockValue)); - newDrug.setTake(Double.parseDouble(takeValue)); - newDrug.setWarnThreshold(Integer.parseInt(warningValue)); - newDrug.setAlertThreshold(Integer.parseInt(alertValue)); - newDrug.setDateEndOfStock(); + newMedic.setStock(Double.parseDouble(stockValue)); + newMedic.setTake(Double.parseDouble(takeValue)); + newMedic.setWarning(Integer.parseInt(warningValue)); + newMedic.setAlert(Integer.parseInt(alertValue)); + newMedic.getDateEndOfStock(); - if (drug.equals(newDrug)) { - Log.d(TAG, "drug and newDrug are Equals"); + if (aMedic.equals(newMedic)) { + Log.d(TAG, "medic and newMedic are Equals"); } else { - Log.d(TAG, "drug and newDrug are NOT Equals"); - newDrug.setDateLastUpdate(new Date().getTime()); - dbHelper.updateDrug(newDrug); + Log.d(TAG, "medic and newMedic are NOT Equals"); + newMedic.setLast_update(new Date().getTime()); + medicDAO.update(newMedic); + //dbHelper.updateDrug(newDrug); } } } diff --git a/app/src/main/java/net/foucry/pilldroid/DrugListActivity.java b/app/src/main/java/net/foucry/pilldroid/DrugListActivity.java index 3285b7d..897e6e5 100644 --- a/app/src/main/java/net/foucry/pilldroid/DrugListActivity.java +++ b/app/src/main/java/net/foucry/pilldroid/DrugListActivity.java @@ -10,6 +10,7 @@ import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; +import android.os.Parcelable; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; @@ -52,12 +53,7 @@ import net.foucry.pilldroid.models.Medic; * item details side-by-side using two vertical panes. */ public class DrugListActivity extends AppCompatActivity { - /** - * Whether or not the activity is in two-pane mode, i.e. running on a tablet - * device. - */ - - // TODO: Change DEMO/DBDEMO form static to non-static. In order to create fake data at only at launch time + // Used for dev and debug final Boolean DEMO = true; final Boolean DBDEMO = false; @@ -66,24 +62,34 @@ public class DrugListActivity extends AppCompatActivity { public final String BARCODE_CONTENT = "Barcode Content"; private ActivityResultLauncher mBarcodeScannerLauncher; + private static final String TAG = DrugListActivity.class.getName(); + private DBHelper dbHelper; + private DBDrugs dbDrug; + public PilldroidDatabase prescriptions; + public PilldroidDatabase medications; - /** - * Start tutorial - */ + private List medics; // used for prescriptions + private SimpleItemRecyclerViewAdapter mAdapter; @Override public void onStart() { super.onStart(); + medications = Room + .databaseBuilder(getApplicationContext(), PilldroidDatabase.class, "medications") + .createFromAsset("drugs.db") + .build(); + + // remove old notification Log.d(TAG, "Remove old notification and old job"); NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); if (nm != null) { nm.cancelAll(); } - // tutorial + // start tutorial Log.i(TAG, "Launch tutorial"); startActivity(new Intent(this, WelcomeActivity.class)); } @@ -93,37 +99,13 @@ public class DrugListActivity extends AppCompatActivity { super.onStop(); } - private static final String TAG = DrugListActivity.class.getName(); - - private DBHelper dbHelper; - private DBDrugs dbDrug; - - private List drugs; - - private SimpleItemRecyclerViewAdapter mAdapter; - - public void constructDrugsList() { - dbHelper = new DBHelper(getApplicationContext()); - - if (!(drugs == null)) { - if (!drugs.isEmpty()) { - drugs.clear(); - } - } - drugs = dbHelper.getAllDrugs(); - - View mRecyclerView = findViewById(R.id.drug_list); - assert mRecyclerView != null; - setupRecyclerView((RecyclerView) mRecyclerView); - } - @SuppressLint("NotifyDataSetChanged") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create Room database - PilldroidDatabase prescription = Room + prescriptions = Room .databaseBuilder(getApplicationContext(), PilldroidDatabase.class, "prescriptions") .allowMainThreadQueries() .build(); @@ -147,7 +129,7 @@ public class DrugListActivity extends AppCompatActivity { } if (DEMO) { - MedicDAO medicDAO = prescription.getMedicDAO(); + MedicDAO medicDAO = prescriptions.getMedicDAO(); final int min_stock = 5; final int max_stock = 50; @@ -161,16 +143,17 @@ public class DrugListActivity extends AppCompatActivity { medic.setCis("6000001" + i); medic.setAdministration_mode("oral"); medic.setPresentation("plaquette(s) thermoformée(s) PVC PVDC aluminium de 10 comprimé(s)"); - medic.setStock((long) intRandomExclusive(min_stock, max_stock)); - medic.setTake((long) intRandomExclusive(min_take, max_take)); + medic.setStock((double) intRandomExclusive(min_stock, max_stock)); + medic.setTake((double) intRandomExclusive(min_take, max_take)); medic.setWarning(14); medic.setAlert(7); medic.setLast_update(UtilDate.dateAtNoon(new Date()).getTime()); - medicDAO.insertAll(medic); + medicDAO.insert(medic); } - List prescriptions = medicDAO.getMedics(); + List prescriptions = medicDAO.getAllMedics(); System.out.println(prescriptions); + Log.d(TAG, "prescriptions ==" + prescriptions); /* if (dbHelper.getCount() == 0) { @@ -269,10 +252,12 @@ public class DrugListActivity extends AppCompatActivity { } // Get Drug from database - final Drug scannedDrug = dbDrug.getDrugByCIP13(cip13); + //final Drug scannedDrug = dbDrug.getDrugByCIP13(cip13); + MedicDAO medicationDAO = medications.getMedicDAO(); + final Medic scannedMedication = medicationDAO.getMedicByCIP13(cip13); // add Drug to prescription database - askToAddInDB(scannedDrug); + askToAddInDB(scannedMedication); } } } @@ -281,6 +266,24 @@ public class DrugListActivity extends AppCompatActivity { constructDrugsList(); } + public void constructDrugsList() { + + MedicDAO medicDAO = prescriptions.getMedicDAO(); + medics = medicDAO.getAllMedics(); + + /*dbHelper = new DBHelper(getApplicationContext()); + + if (!(drugs == null)) { + if (!drugs.isEmpty()) { + drugs.clear(); + } + } + drugs = dbHelper.getAllDrugs();*/ + + View mRecyclerView = findViewById(R.id.drug_list); + assert mRecyclerView != null; + setupRecyclerView((RecyclerView) mRecyclerView); + } public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); @@ -369,8 +372,10 @@ public class DrugListActivity extends AppCompatActivity { .setPositiveButton("OK", (dialog, id) -> { String cip13 = editText.getText().toString(); - Drug aDrug = dbDrug.getDrugByCIP13(cip13); - askToAddInDB(aDrug); + MedicDAO medicationsDAO = medications.getMedicDAO(); + Medic aMedic = medicationsDAO.getMedicByCIP13(cip13); + //Medic aMedic = medications.getDrugByCIP13(cip13); + askToAddInDB(aMedic); }) .setNegativeButton("Cancel", (dialog, id) -> dialog.cancel()); @@ -401,14 +406,14 @@ public class DrugListActivity extends AppCompatActivity { * Ask if the drug found in the database should be include in the * user database * - * @param aDrug Drug- drug to be added + * @param aMedic Medic- medication to be added */ - private void askToAddInDB(Drug aDrug) { + private void askToAddInDB(Medic aMedic) { AlertDialog.Builder dlg = new AlertDialog.Builder(this); dlg.setTitle(getString(R.string.app_name)); - if (aDrug != null) { - String msg = aDrug.getName() + " " + getString(R.string.msgFound); + if (aMedic != null) { + String msg = aMedic.getName() + " " + getString(R.string.msgFound); dlg.setMessage(msg); dlg.setNegativeButton(getString(R.string.button_cancel), (dialog, which) -> { @@ -416,7 +421,7 @@ public class DrugListActivity extends AppCompatActivity { }); dlg.setPositiveButton(getString(R.string.button_ok), (dialog, which) -> { // Add Drug to DB then try to show it - addDrugToList(aDrug); + addDrugToList(aMedic); }); } else { dlg.setMessage(getString(R.string.msgNotFound)); @@ -444,18 +449,18 @@ public class DrugListActivity extends AppCompatActivity { /** * Add New drug to the user database * - * @param aDrug Drug - drug to be added + * @param aMedic Medic - medication to be added */ @SuppressWarnings("deprecation") - private void addDrugToList(Drug aDrug) { - aDrug.setDateEndOfStock(); - mAdapter.addItem(aDrug); + private void addDrugToList(Medic aMedic) { + aMedic.getDateEndOfStock(); + mAdapter.addItem(aMedic); Log.d(TAG, "Call DrugDetailActivity"); Context context = this; Intent intent = new Intent(context, DrugDetailActivity.class); - intent.putExtra("drug", aDrug); + intent.putExtra("medic", (Parcelable) aMedic); startActivityForResult(intent, CUSTOMIZED_REQUEST_CODE); overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left); @@ -478,27 +483,29 @@ public class DrugListActivity extends AppCompatActivity { */ private void setupRecyclerView(@NonNull RecyclerView recyclerView) { recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getApplicationContext())); - mAdapter = new SimpleItemRecyclerViewAdapter(drugs); + mAdapter = new SimpleItemRecyclerViewAdapter(medics); recyclerView.setAdapter(mAdapter); } /** * SimpleItemRecyclerViewAdapter */ - public class SimpleItemRecyclerViewAdapter extends RecyclerView.Adapter { + public class SimpleItemRecyclerViewAdapter extends + RecyclerView.Adapter { - private final List mValues; + private final List mValues; - SimpleItemRecyclerViewAdapter(List items) { + SimpleItemRecyclerViewAdapter(List items) { mValues = items; } - void addItem(Drug scannedDrug) { - if (!dbHelper.isDrugExist(scannedDrug.getCip13())) { - mValues.add(scannedDrug); + void addItem(Medic scannedMedic) { + MedicDAO medicDAO = prescriptions.getMedicDAO(); + if (medicDAO.getMedicByCIP13(scannedMedic.getCip13()) == null) { + mValues.add(scannedMedic); //notifyDataSetChanged(); notifyItemInserted(mValues.size()); - dbHelper.addDrug(scannedDrug); + medicDAO.insert(scannedMedic); } else { Toast.makeText(getApplicationContext(), "already in the database", Toast.LENGTH_LONG).show(); } @@ -539,10 +546,10 @@ public class DrugListActivity extends AppCompatActivity { holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - Drug drug = mValues.get(position); + Medic aMedic = mValues.get(position); Context context = v.getContext(); Intent intent = new Intent(context, DrugDetailActivity.class); - intent.putExtra("drug", drug); + intent.putExtra("medic", (Parcelable) aMedic); startActivityForResult(intent, CUSTOMIZED_REQUEST_CODE); overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left); @@ -565,10 +572,10 @@ public class DrugListActivity extends AppCompatActivity { holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - Drug drug = mValues.get(position); + Medic medic = mValues.get(position); Context context = v.getContext(); Intent intent = new Intent(context, DrugDetailActivity.class); - intent.putExtra("drug", drug); + intent.putExtra("medic", (Parcelable) medic); startActivityForResult(intent, CUSTOMIZED_REQUEST_CODE); overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left); @@ -588,7 +595,7 @@ public class DrugListActivity extends AppCompatActivity { final TextView mContentView; final TextView mEndOfStock; final ImageView mIconView; - public Drug mItem; + public Medic mItem; ViewHolder(View view) { super(view); diff --git a/app/src/main/java/net/foucry/pilldroid/PilldroidDatabase.java b/app/src/main/java/net/foucry/pilldroid/PilldroidDatabase.java index 9ba304a..8cb1415 100644 --- a/app/src/main/java/net/foucry/pilldroid/PilldroidDatabase.java +++ b/app/src/main/java/net/foucry/pilldroid/PilldroidDatabase.java @@ -6,7 +6,7 @@ import androidx.room.RoomDatabase; import net.foucry.pilldroid.dao.MedicDAO; import net.foucry.pilldroid.models.Medic; -@Database(entities = {Medic.class}, version = 1) +@Database(entities = {Medic.class}, version = 2) public abstract class PilldroidDatabase extends RoomDatabase { public abstract MedicDAO getMedicDAO(); diff --git a/app/src/main/java/net/foucry/pilldroid/UtilDate.java b/app/src/main/java/net/foucry/pilldroid/UtilDate.java index bafb822..4aa1c29 100644 --- a/app/src/main/java/net/foucry/pilldroid/UtilDate.java +++ b/app/src/main/java/net/foucry/pilldroid/UtilDate.java @@ -12,7 +12,7 @@ import java.util.Locale; /** * Created by jacques on 05/05/16. */ -class UtilDate { +public class UtilDate { private static final String TAG = UtilDate.class.getName(); @@ -21,7 +21,7 @@ class UtilDate { * @return date the same date as input but at noon (12:00:00 PM) * set date time at Noon */ - static Date dateAtNoon(Date aDate) { + public static Date dateAtNoon(Date aDate) { Log.d(TAG, "dateAtNoon " + aDate); diff --git a/app/src/main/java/net/foucry/pilldroid/dao/MedicDAO.java b/app/src/main/java/net/foucry/pilldroid/dao/MedicDAO.java index 147d566..5d0c9e1 100644 --- a/app/src/main/java/net/foucry/pilldroid/dao/MedicDAO.java +++ b/app/src/main/java/net/foucry/pilldroid/dao/MedicDAO.java @@ -1,5 +1,7 @@ package net.foucry.pilldroid.dao; +import static net.foucry.pilldroid.UtilDate.dateAtNoon; + import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; @@ -8,12 +10,15 @@ import androidx.room.Update; import net.foucry.pilldroid.models.Medic; +import java.util.Calendar; +import java.util.Date; import java.util.List; @Dao public interface MedicDAO { @Insert - void insertAll(Medic... medics); + void insert(Medic... medics); + @Update void update(Medic... medics); @@ -23,7 +28,7 @@ public interface MedicDAO { @Query("SELECT * FROM medics") - List getMedics(); + List getAllMedics(); /* @Query("SELECT * FROM medics WHERE id = :id") Medic getMedicBy(Long id);*/ @@ -34,3 +39,5 @@ public interface MedicDAO { @Query("SELECT count(*) FROM medics") int getMedicCount(); } + + diff --git a/app/src/main/java/net/foucry/pilldroid/models/Medic.java b/app/src/main/java/net/foucry/pilldroid/models/Medic.java index 477e699..6b344a3 100644 --- a/app/src/main/java/net/foucry/pilldroid/models/Medic.java +++ b/app/src/main/java/net/foucry/pilldroid/models/Medic.java @@ -1,8 +1,13 @@ package net.foucry.pilldroid.models; +import androidx.annotation.NonNull; import androidx.room.Entity; import androidx.room.PrimaryKey; -import androidx.annotation.NonNull; + +import net.foucry.pilldroid.UtilDate; + +import java.util.Calendar; +import java.util.Date; @Entity(tableName = "medics") public class Medic { @@ -12,8 +17,8 @@ public class Medic { private String name; private String administration_mode; private String presentation; - private Long stock; - private Long take; + private Double stock; + private Double take; private Integer warning; private Integer alert; private Long last_update; @@ -28,7 +33,6 @@ public class Medic { this.cis = cis; } - public void setCip13(String cip13) { this.cip13 = cip13; } @@ -37,31 +41,30 @@ public class Medic { this.name = name; } -public void setAdministration_mode(String administration_mode) { - + public void setAdministration_mode(String administration_mode) { this.administration_mode = administration_mode; -} + } -public void setPresentation(String presentation) { + public void setPresentation(String presentation) { this.presentation = presentation; } -public void setStock(Long stock) { + public void setStock(Double stock) { this.stock = stock; } -public void setTake(Long take) { + public void setTake(Double take) { this.take = take; } -public void setWarning(Integer warning) { + public void setWarning(Integer warning) { this.warning = warning; } -public void setAlert(Integer alert) { + public void setAlert(Integer alert) { this.alert = alert; } -public void setLast_update(Long last_update) { + public void setLast_update(Long last_update) { this.last_update = last_update; } @@ -70,7 +73,8 @@ public void setLast_update(Long last_update) { return this.id; }*/ -public String getCis() { +@NonNull + public String getCis() { return this.cis; } @@ -94,11 +98,11 @@ public String getCis() { return presentation; } - public Long getStock() { + public Double getStock() { return stock; } - public Long getTake() { + public Double getTake() { return take; } @@ -109,6 +113,30 @@ public String getCis() { public Long getLast_update() { return last_update; } + + public int getAlertThreshold() { + return this.alert; + } + + public int getWarnThreshold() { + return this.warning; + } + + public Date getDateEndOfStock() { + int numberDayOfTake; + if (this.getTake() > 0) { + numberDayOfTake = (int) Math.floor(this.getStock() / this.getTake()); + } else { + numberDayOfTake = 0; + } + + Date aDate = UtilDate.dateAtNoon(new Date()); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(aDate); + calendar.add(Calendar.DAY_OF_YEAR, numberDayOfTake); + + return calendar.getTime(); + } }