diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..39b273cf --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,20 @@ +## Description +As a [USER], +I need [TO DO THIS], +so that I can [ACCOMPLISH THAT]. + +## Mocks +[INSERT RELEVANT PNG FILE] + +## Acceptance Criteria +### Update [Required] +- [ ] [LIST ITEMS] +### Enhancement to Update [Optional] +- [ ] [LIST ITEMS] + +## Definition of Done +- [ ] All of the required items are completed. +- [ ] Approval by 1 mentor. + +## Estimation +[INSERT NUMBER HERE] hours diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..c72f7c77 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,40 @@ +### Description +Include a summary of the change and relevant motivation/context. List any dependencies that are required for this change. + +Fixes # [ISSUE] + +### Type of Change: +**Delete irrelevant options.** + +- Code +- Quality Assurance +- User Interface +- Outreach +- Documentation + +**Code/Quality Assurance Only** +- Bug fix (non-breaking change which fixes an issue) +- This change requires a documentation update (software upgrade on readme file) +- New feature (non-breaking change which adds functionality pre-approved by mentors) + + + +### How Has This Been Tested? +Describe the tests you ran to verify your changes. Provide instructions or GIFs so we can reproduce. List any relevant details for your test. + + +### Checklist: +**Delete irrelevant options.** + +- [ ] My PR follows the style guidelines of this project +- [ ] I have performed a self-review of my own code or materials +- [ ] I have commented my code or provided relevant documentation, particularly in hard-to-understand areas +- [ ] I have made corresponding changes to the documentation +- [ ] Any dependent changes have been merged + +**Code/Quality Assurance Only** +- [ ] My changes generate no new warnings +- [ ] My PR currently breaks something (fix or feature that would cause existing functionality to not work as expected) +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] New and existing unit tests pass locally with my changes +- [ ] Any dependent changes have been published in downstream modules diff --git a/.gitignore b/.gitignore index 648a292a..c3fa6c95 100644 --- a/.gitignore +++ b/.gitignore @@ -1,29 +1,48 @@ -# built application files +# Built application files *.apk *.ap_ -# files for the dex VM +# Files for the ART/Dalvik VM *.dex # Java class files *.class -# generated files +# Generated files bin/ gen/ +out/ + +# Gradle files +.gradle/ +build/ # Local configuration file (sdk path, etc) local.properties -# Eclipse project files -.classpath -.project - # Proguard folder generated by Eclipse proguard/ -# Intellij project files +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ + +# Intellij *.iml -*.ipr -*.iws -.idea/ +.idea/workspace.xml +.idea/tasks.xml +.idea/libraries +**/.idea/** +**/*.iml + +# Keystore files +*.jks + +# External native build folder generated in Android Studio 2.2 and later +.externalNativeBuild + diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..4651d7d5 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,17 @@ +sudo: required +language: android +jdk: oraclejdk8 +android: + components: + - platform-tools + - tools + - build-tools-26.0.2 + - android-26 + - extra-android-m2repository +before_script: + - chmod +x gradlew + - chmod +x generate-apk.sh +script: + - ./gradlew assembleDebug --stacktrace # Change 'assembleDebug' to 'build' when lint issues are fixed. Update generate-apk.sh accordingly +after_success: + - ./generate-apk.sh diff --git a/AndroidManifest.xml b/AndroidManifest.xml deleted file mode 100644 index 87e9182c..00000000 --- a/AndroidManifest.xml +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..11638f78 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,11 @@ +# Contributing Guidelines +* You can join our [slack channel](http://systers.io/slack-systers-opensource/). Each active repo has its own channel to direct questions to (for example #powerup or #portal). +* Remember that this is an inclusive community, committed to creating a safe, positive environment. See the full [Code of Conduct](http://www.systers.io/code-of-conduct.html). +## General Guidelines +* If you’re just getting started work on an issue labeled “First Timers Only” in any project. Additional resources are available on our [website](http://www.systers.io). +* In an active repository (not an archived one), choose an open issue from the issue list, claim it in the comments, and a maintainer will assign it to you. +* After approval you must make continuous notes on your progress in the issue while working. If there is not at least one comment every 3 days, the maintainer can reassign the issue. +* When sending a PR have an appropriate title referencing the issue which it solves. Add “fixes #” in the commit body, so that when the PR gets merged, the issue gets closed automatically. Do not do this if the PR solves only a part of the issue. See more information on commit guidelines [here](https://udacity.github.io/git-styleguide/). +* If you’d like to create a new issue, please go through our issue list first (open as well as closed) and make sure the issues you are reporting do not replicate the existing issues. +* Have a short description on what has gone wrong (like a root cause analysis and description of the fix), if that information is not already present in the issue. +* If you have issues on multiple pages, report them separately. Do not combine them into a single issue. diff --git a/Malaria_Prevention_Documentation.PDF b/Malaria_Prevention_Documentation.PDF new file mode 100644 index 00000000..c8069692 Binary files /dev/null and b/Malaria_Prevention_Documentation.PDF differ diff --git a/README.md b/README.md index 8a5f7c06..977f3b94 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +[![Build Status](https://travis-ci.org/systers/malaria-app-android.svg?branch=master)](https://travis-ci.org/systers/malaria-app-android) + Malaria App for Android ==== @@ -31,7 +33,32 @@ Included in this repository are files to help you get started: This project uses Jack Wharton's Android-ViewPagerIndicator for the Viewpager Swipe view. Jake Wharton ViewPager Indicator project dependecy -

Download Current Malaria APK File here

+

Download Current Malaria APK File here

+ +## Current Status +

GSOC 2016 Malaria App Demo

+

GSOC 2015 Malaria App Demo

+ + +## Guidelines for contributors +To contribute to malaria-app-android pick an open issue from the [issue list](https://github.com/systers/malaria-app-android/issues) tagged as "free", claim it in the comments, fix the issue and send us a pull request. +If you find an issue yourself you can report it, a community member will get back to you and approve the issue. Then you can fix it and submit a PR. Please go through our issue list first and make sure the issues you are reporting do not replicate the issues already reported. If you have multiple issues, report them separately. Do not combine them into a single issue. + +### Best Practise +1. Try to do a root cause analysis for the issue, if applicable. +2. Reference the issue being fixed in the corresponding PR. +3. Use meaningful commit messages in a PR. +4. Use one commit per task. Do not over commit (add unnecessary commits for a single task) or under commit (merge 2 or more tasks in one commit). +5. Add screenshot/short video in case the changes made in the PR, are being reflected in the UI of the application. +6. Close the issue as soon as the corresponding PR is accepted/closed. + +### Some Don'ts +1. Send a PR without an existing issue. +2. Fix an issue assigned to somebody else and submit a PR before the assignee does. +3. Report issues which are previously reported by others. (Please check both the open and closed issues). +4. Suggest unnecessary or completely new features in the issue list. +5. Add unnecessary spacing or indentation to the code. +

Contact Information:

diff --git a/Test Results - malaria-app-androidtest.html b/Test Results - malaria-app-androidtest.html new file mode 100644 index 00000000..844580d8 --- /dev/null +++ b/Test Results - malaria-app-androidtest.html @@ -0,0 +1,636 @@ + + + + +Test Results — malaria-app-androidtest + + + + + + + + + +
+ +
+
    +
  • + +
    1.19 s
    +
    com.peacecorps.malariatest.MalariaDatabaseTest
    +
      +
    • + +
      212 ms
      +
      passedtestAddEntryinIOMMEmethod
      +
    • +
    • + +
      25 ms
      +
      passedtestAndroidTestCaseSetupProperly
      +
    • +
    • + +
      175 ms
      +
      passedtestDosesInaRowWithASingleEntry
      +
    • +
    • + +
      375 ms
      +
      passedtestDosesInaRowWithDiscontinuedYesEntry
      +
    • +
    • + +
      300 ms
      +
      passedtestDosesInaRowWithDoubleEntry
      +
    • +
    • + +
      100 ms
      +
      passedtestDosesInaRowWithNoEntry
      +
    • +
    +
  • +
+
+
+ + + diff --git a/androidTest/java/com/peacecorps/malariatest/MalariaDatabaseTest.java b/androidTest/java/com/peacecorps/malariatest/MalariaDatabaseTest.java deleted file mode 100644 index 39e6fb28..00000000 --- a/androidTest/java/com/peacecorps/malariatest/MalariaDatabaseTest.java +++ /dev/null @@ -1,690 +0,0 @@ -package com.peacecorps.malariatest; - -import android.test.AndroidTestCase; -import android.test.RenamingDelegatingContext; -import android.util.Log; -import android.widget.Toast; - -import com.peacecorps.malaria.DatabaseSQLiteHelper; -import com.peacecorps.malaria.FirstAnalyticFragment; -import com.peacecorps.malaria.SharedPreferenceStore; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; - -/** - * Created by Ankita on 7/7/2015. - */ -public class MalariaDatabaseTest extends AndroidTestCase { - - private DatabaseSQLiteHelper db; - private FirstAnalyticFragment faf; - - public void setUp() - { - RenamingDelegatingContext context =new RenamingDelegatingContext(getContext(),"test_"); - db=new DatabaseSQLiteHelper(context); - faf=new FirstAnalyticFragment(); - } - - public void testAddEntryinIOMMEmethod() - { - int date=30; - int month=5; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date,month,year,percentage); - long x=db.getFirstTime(); - - String date_header=""+date+"/"+month+"/"+year; - SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy"); - Date d = Calendar.getInstance().getTime(); - - try{ - d=sdf.parse(date_header); - } - catch (ParseException e) - { - e.printStackTrace(); - } - - Calendar c=Calendar.getInstance(); - - c.setTime(d); - - long y = c.getTimeInMillis(); - assertEquals(x,y); - } - - public void testDosesInaRowWithNoEntry(){ - - - int x = db.getDosesInaRowDaily(); - - assertEquals(0,x); - - - } - - public void testDosesInaRowWithASingleEntry(){ - - int date=30; - int month=5; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - int x = db.getDosesInaRowDaily(); - - assertEquals(1,x); - - - } - - public void testDosesInaRowWithDoubleEntry(){ - - int date=30; - int month=5; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=29;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - int x = db.getDosesInaRowDaily(); - - assertEquals(2,x); - - } - - public void testDosesInaRowWithDiscontinuedYesEntry(){ - int date=30; - int month=5; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=29;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=28;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"no",percentage); - - date=27;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - int x = db.getDosesInaRowDaily(); - - assertEquals(2, x); - - - - } - - public void testDosesInaRowWithDiscontiuedDateYesEntry(){ - - int date=30; - int month=5; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=29;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=27;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=26;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - int x = db.getDosesInaRowDaily(); - - long a=db.getFirstTime(); - - assertEquals(2, x); - } - - public void testDosesInaRowWithDiscontinuedBoundaryDateYesEntry(){ - - int date=30; - int month=5; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=1;month=6;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=2;month=6;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=3;month=6;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - int x = db.getDosesInaRowDaily(); - - assertEquals(4,x); - - } - - public void testDosesInaRowWeeklyIrregular(){ - - int date=24; - int month=5; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=17;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=9;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=3;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - int x = db.getDosesInaRowWeekly(); - - assertEquals(4,x); - - - } - - public void testDosesInaRowWeeklyDiscontinued(){ - - int date=30; - int month=5; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=23;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=16;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=3;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - int x = db.getDosesInaRowWeekly(); - - assertEquals(3,x); - - - } - - public void testDosesInaRowWeeklyNoEntry(){ - - int x = db.getDosesInaRowWeekly(); - - assertEquals(0,x); - - - } - - public void testDosesInaRowWeeklyIrregularDifferentMonths(){ - - int date=24; - int month=5; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=17;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=9;month=5;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=31;month=4;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=28;month=4;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - int x = db.getDosesInaRowWeekly(); - - assertEquals(5,x); - - - } - - - public void testAdherence() - { - - - int date=30; - int month=7; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=29;month=7;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=27;month=7;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=26;month=7;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - - long a=db.getFirstTime(); - - date=30;month=7;year=2015; - - String date_header=""+date+"/"+month+"/"+year; - SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy"); - Date d = Calendar.getInstance().getTime(); - - try{ - d=sdf.parse(date_header); - } - catch (ParseException e) - { - e.printStackTrace(); - } - - Calendar c=Calendar.getInstance(); - - c.setTime(d); - - long y = c.getTimeInMillis(); - - - long today= Calendar.getInstance().getTimeInMillis(); - - SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); - String formattedDate = df.format(Calendar.getInstance().getTime()); - // formattedDate have current date/time - //Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show(); - - long oneDay = 1000 * 60 * 60 * 24; - - long interval=(y-a)/oneDay+1; - - long takenCount=db.countTaken(); - - double ar=(double)takenCount/(double)interval*100; - - //double arm= faf.updateAdherence(); - - assertEquals(80.0,ar); - - /*int date=22; - int month=6; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date,month,year,percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=23; - month=6; - year=2015; - - percentage=45.00; - - db.insertOrUpdateMissedMedicationEntry(date,month,year,percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=27;month=6;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date,month,year,percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - long x=0; - db.getFirstTime(); - - Log.d("TestRunner","first run time->"+x); - - Date d = Calendar.getInstance().getTime(); - - Calendar c=Calendar.getInstance(); - - c.setTime(d); - - long y = c.getTimeInMillis(); - - long oneDay = 1000 * 60 * 60 * 24; - - double chk=(double)(y-x)/(double)oneDay; - - double ar=faf.updateAdherence(); - - assertEquals(ar,chk); - - /*int date=22; - int month=6; - int year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=23;month=6;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=27;month=6;year=2015;percentage=28.00; - - long x=db.getFirstTime(); - - String date_header=""+date+"/"+month+"/"+year; - SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy"); - Date d = Calendar.getInstance().getTime(); - - try{ - d=sdf.parse(date_header); - } - catch (ParseException e) - { - e.printStackTrace(); - } - - Calendar c=Calendar.getInstance(); - - c.setTime(d); - - long y = c.getTimeInMillis(); - assertEquals(x,y); - */ - - } - - - public void testCountTaken() - { - int date=28; - int month=6; - int year=2015; - - double percentage=00.00; - - db.insertOrUpdateMissedMedicationEntry(date,month,year,percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=7; - month=6; - year=2015; - - percentage=00.00; - - db.insertOrUpdateMissedMedicationEntry(date,month,year,percentage); - - db.updateMedicationEntry(date, month,year,"yes",percentage); - - int x= db.countTaken(); - - - assertEquals(2,x); - - } - - - public void testWeekdays() - { - int date=30; - int month=12; - int year=2014; - - Date s=db.getDateObject(""+year+"-"+month+"-"+date); - - date=6; - month=1; - year=2015; - - Date e = db.getDateObject(""+year+"-"+month+"-"+date); - - int x= db.getIntervalWeekly(s, e, 3); - - assertEquals(2,x); - - } - - public void testDailyDays() - { - int date=30; - int month=12; - int year=2014; - - Date s=db.getDateObject(""+year+"-"+month+"-"+date); - - date=6; - month=1; - year=2015; - - Date e = db.getDateObject(""+year+"-"+month+"-"+date); - - int x= db.getIntervalDaily(s, e); - - assertEquals(8,x); - - } - - - public void testgetCountTakenBetween() - { - int date=1; - int month=8; - int year=2015; - - Date s=db.getDateObject(""+year+"-"+month+"-"+date); - - date=15; - month=8; - year=2015; - - Date e = db.getDateObject(""+year+"-"+month+"-"+date); - - date=2; - month=8; - year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=3;month=8;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=4;month=8;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=6;month=8;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - - int cnt=db.getCountTakenBetween(s,e); - - assertEquals(4,cnt); - - } - - public void testgetCountTakenBetweenBoundary() - { - int date=1; - int month=8; - int year=2015; - - Date s=db.getDateObject(""+year+"-"+month+"-"+date); - - date=15; - month=8; - year=2015; - - Date e = db.getDateObject(""+year+"-"+month+"-"+date); - - date=1; - month=8; - year=2015; - - double percentage=23.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - date=3;month=8;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=4;month=8;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date,month,year,"yes",percentage); - - date=15;month=8;year=2015;percentage=28.00; - - db.insertOrUpdateMissedMedicationEntry(date, month, year, percentage); - - db.updateMedicationEntry(date, month, year, "yes", percentage); - - - int cnt=db.getCountTakenBetween(s,e); - - assertEquals(4,cnt); - - } - - - - - -} diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..348a2e75 --- /dev/null +++ b/build.gradle @@ -0,0 +1,33 @@ +buildscript { + repositories { + jcenter() + google() + } + dependencies { + classpath 'com.android.tools.build:gradle:3.0.0' + } +} + +allprojects { + repositories { + maven { url "http://dl.bintray.com/populov/maven" } + google() + jcenter() + } +} + +// Define versions in a single place +ext { + // Sdk and tools + minSdkVersion = 16 + targetSdkVersion = 26 + compileSdkVersion = 26 + buildToolsVersion = '26.0.2' + + // App dependencies + supportLibraryVersion = '27.1.1' + viewPagerIndicatorVersion = '2.4.1@aar' + constraintLayoutVersion= '1.1.2' + lifecycle_version = '1.1.1' + room_version = '1.1.1' +} \ No newline at end of file diff --git a/code_of_conduct.md b/code_of_conduct.md new file mode 100644 index 00000000..e0dfd11d --- /dev/null +++ b/code_of_conduct.md @@ -0,0 +1,82 @@ +# Code of Conduct + +## 1. Purpose + +A primary goal of Systers is to be inclusive to the largest number of contributors, with the most varied and diverse backgrounds possible. As such, we are committed to providing a friendly, safe and welcoming environment for all, regardless of gender, sexual orientation, ability, ethnicity, socioeconomic status, and religion (or lack thereof). + +This code of conduct outlines our expectations for all those who participate in our community, as well as the consequences for unacceptable behavior. + +We invite all those who participate in Systers to help us create safe and positive experiences for everyone. + +## 2. Open Source Citizenship + +A supplemental goal of this Code of Conduct is to increase open source citizenship by encouraging participants to recognize and strengthen the relationships between our actions and their effects on our community. + +Communities mirror the societies in which they exist and positive action is essential to counteract the many forms of inequality and abuses of power that exist in society. + +If you see someone who is making an extra effort to ensure our community is welcoming, friendly, and encourages all participants to contribute to the fullest extent, we want to know. + +## 3. Expected Behavior + +The following behaviors are expected and requested of all community members: + +* Participate in an authentic and active way. In doing so, you contribute to the health and longevity of this community. +* Exercise consideration and respect in your speech and actions. +* Attempt collaboration before conflict. +* Refrain from demeaning, discriminatory, or harassing behavior and speech. +* Be mindful of your surroundings and of your fellow participants. Alert community leaders if you notice a dangerous situation, someone in distress, or violations of this Code of Conduct, even if they seem inconsequential. +* Remember that community event venues may be shared with members of the public; please be respectful to all patrons of these locations. + +## 4. Unacceptable Behavior + +The following behaviors are considered harassment and are unacceptable within our community: + +* Violence, threats of violence or violent language directed against another person. +* Sexist, racist, homophobic, transphobic, ableist or otherwise discriminatory jokes and language. +* Posting or displaying sexually explicit or violent material. +* Posting or threatening to post other people’s personally identifying information ("doxing"). +* Personal insults, particularly those related to gender, sexual orientation, race, religion, or disability. +* Inappropriate photography or recording. +* Inappropriate physical contact. You should have someone’s consent before touching them. +* Unwelcome sexual attention. This includes, sexualized comments or jokes; inappropriate touching, groping, and unwelcomed sexual advances. +* Deliberate intimidation, stalking or following (online or in person). +* Advocating for, or encouraging, any of the above behavior. +* Sustained disruption of community events, including talks and presentations. + +## 5. Consequences of Unacceptable Behavior + +Unacceptable behavior from any community member, including sponsors and those with decision-making authority, will not be tolerated. + +Anyone asked to stop unacceptable behavior is expected to comply immediately. + +If a community member engages in unacceptable behavior, the community organizers may take any action they deem appropriate, up to and including a temporary ban or permanent expulsion from the community without warning (and without refund in the case of a paid event). + +## 6. Reporting Guidelines +If you are subject to or witness unacceptable behavior, or have any other concerns, please notify a community organizer as soon as possible by emailing systers.keeper@gmail.com. Please read [Reporting Guidelines](reporting_guidelines.md) for details. + + + +Additionally, community organizers are available to help community members engage with local law enforcement or to otherwise help those experiencing unacceptable behavior feel safe. In the context of in-person events, organizers will also provide escorts as desired by the person experiencing distress. + +## 7. Addressing Grievances + +Only permanent resolutions (such as bans) may be appealed. To appeal a decision of the working group, contact the Systers' Open Source Board at os-board@anitab.org with your appeal and the board will review the case. + + +## 8. Scope + +We expect all community participants (contributors, paid or otherwise; sponsors; and other guests) to abide by this Code of Conduct in all community venues–online and in-person–as well as in all one-on-one communications pertaining to community business. + +This code of conduct and its related procedures also applies to unacceptable behavior occurring outside the scope of community activities when such behavior has the potential to adversely affect the safety and well-being of community members. + +## 9. Contact info + +systers.keeper@gmail.com + +## 10. License and attribution + +This Code of Conduct is distributed under a [Creative Commons Attribution-ShareAlike license](http://creativecommons.org/licenses/by-sa/3.0/). + +Portions of text derived from the [Django Code of Conduct](https://www.djangoproject.com/conduct/) and the [Geek Feminism Anti-Harassment Policy](http://geekfeminism.wikia.com/wiki/Conference_anti-harassment/Policy). + +Retrieved on November 22, 2016 from [http://citizencodeofconduct.org/](http://citizencodeofconduct.org/) diff --git a/config/quality/checkstyle/checkstyle-config.xml b/config/quality/checkstyle/checkstyle-config.xml new file mode 100644 index 00000000..63b4fe84 --- /dev/null +++ b/config/quality/checkstyle/checkstyle-config.xml @@ -0,0 +1,163 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config/quality/findbugs/android-exclude-filter.xml b/config/quality/findbugs/android-exclude-filter.xml new file mode 100644 index 00000000..b724212b --- /dev/null +++ b/config/quality/findbugs/android-exclude-filter.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config/quality/pmd/pmd-ruleset.xml b/config/quality/pmd/pmd-ruleset.xml new file mode 100644 index 00000000..2c8f6a25 --- /dev/null +++ b/config/quality/pmd/pmd-ruleset.xml @@ -0,0 +1,40 @@ + + + + Custom rules for Systers Android applications + + .*/R.java + .*/gen/.* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config/quality/quality.gradle b/config/quality/quality.gradle new file mode 100644 index 00000000..b9986d9f --- /dev/null +++ b/config/quality/quality.gradle @@ -0,0 +1,89 @@ +/** + * Set up plugins to perform extensive code analysis. + * + * Gradle tasks added: + * - checkstyle + * - findbugs + * - pmd + * + * The three tasks above are added as dependencies of the check task so running check will + * run all of them. + */ + +apply plugin: 'checkstyle' +apply plugin: 'findbugs' +apply plugin: 'pmd' + +dependencies { + checkstyle 'com.puppycrawl.tools:checkstyle:8.7' +} + +def qualityConfigDir = "$project.rootDir/config/quality"; +def reportsDir = "$project.buildDir/reports" + +check.dependsOn 'checkstyle', 'findbugs', 'pmd' + +task checkstyle(type: Checkstyle, group: 'Verification', description: 'Runs code style checks') { + configFile file("$qualityConfigDir/checkstyle/checkstyle-config.xml") + source 'src' + include '**/*.java' + + reports { + xml.enabled = true + xml { + destination "$reportsDir/checkstyle/checkstyle.xml" + } + } + + classpath = files( ) +} + +task findbugs(type: FindBugs, + group: 'Verification', + description: 'Inspect java bytecode for bugs', + dependsOn: ['compileDebugSources','compileReleaseSources']) { + + ignoreFailures = false + effort = "max" + reportLevel = "high" + excludeFilter = new File("$qualityConfigDir/findbugs/android-exclude-filter.xml") + classes = files("$project.rootDir/app/build/intermediates/classes") + + source 'src' + include '**/*.java' + exclude '**/gen/**' + + reports { + xml.enabled = true + html.enabled = false + xml { + destination "$reportsDir/findbugs/findbugs.xml" + } + html { + destination "$reportsDir/findbugs/findbugs.html" + } + } + + classpath = files() +} + +task pmd(type: Pmd, group: 'Verification', description: 'Inspect sourcecode for bugs') { + ruleSetFiles = files("$qualityConfigDir/pmd/pmd-ruleset.xml") + ignoreFailures = false + ruleSets = [] + + source 'src' + include '**/*.java' + exclude '**/gen/**' + + reports { + xml.enabled = true + html.enabled = true + xml { + destination "$reportsDir/pmd/pmd.xml" + } + html { + destination "$reportsDir/pmd/pmd.html" + } + } +} diff --git a/generate-apk.sh b/generate-apk.sh new file mode 100644 index 00000000..9ba1f815 --- /dev/null +++ b/generate-apk.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash + +# Travis build triggered on a forked repository +if [ "$TRAVIS_REPO_SLUG" != "systers/malaria-app-android" ]; then + echo "Not the original repo." + exit 0 +fi + +# Travis build triggered by a PR +if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then + echo "Just a PR." + exit 0 +fi + +# Get commit author name +COMMITTER_NAME=$(git log -1 --pretty=format:'%an') + +# Code pushed to develop branch +if [ "$TRAVIS_BRANCH" == "master" ]; then + echo "Code pushed to master branch. Updating apk." + # Set username and email + git config --global user.name "m-murad" + git config --global user.email "murad.kuka@gmail.com" + + # Create a new git repo to save apk + cd $HOME + mkdir apk + cd apk + git init + + # Copy generated apk into the new repo + cp $HOME/build/systers/malaria-app-android/malaria-app-android/build/outputs/apk/debug/malaria-app-android-debug.apk $HOME/apk/ + + # Add and commit the new apk + git add malaria-app-android-debug.apk + git commit -m "Apk update: Travis build $TRAVIS_BUILD_NUMBER by $COMMITTER_NAME" + + # Rename the current branch + git branch -m apk + + # Pushing the apk branch to the original repo + git push https://m-murad:$GITHUB_API_KEY@github.com/systers/malaria-app-android apk -fq > /dev/null + if [ $? -eq 0 ]; then + echo "Apk push successful." + else + echo "Apk push failed." + fi +fi \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..8c0fb64a Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..30c82236 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Oct 31 03:15:37 IST 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..91a7e269 --- /dev/null +++ b/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..aec99730 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/libs/GraphView-4.0.1.jar b/libs/GraphView-4.0.1.jar deleted file mode 100644 index 693245bf..00000000 Binary files a/libs/GraphView-4.0.1.jar and /dev/null differ diff --git a/.settings/org.eclipse.jdt.core.prefs b/malaria-app-android/.settings/org.eclipse.jdt.core.prefs similarity index 97% rename from .settings/org.eclipse.jdt.core.prefs rename to malaria-app-android/.settings/org.eclipse.jdt.core.prefs index b080d2dd..48ab4c6b 100644 --- a/.settings/org.eclipse.jdt.core.prefs +++ b/malaria-app-android/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 -org.eclipse.jdt.core.compiler.compliance=1.6 -org.eclipse.jdt.core.compiler.source=1.6 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/malaria-app-android/ASB Resources.html b/malaria-app-android/ASB Resources.html new file mode 100644 index 00000000..2690e222 --- /dev/null +++ b/malaria-app-android/ASB Resources.html @@ -0,0 +1,10 @@ + + + + + + +/8430$aDehxeBPY4K + +

ASB Resources

CDC Report Survey

https://drive.google.com/file/d/0B3_92O4iu-M3TlJOYmdUYjJMdkwwcHc1VzBjQ2lEeHBoRFEw/edit?usp=sharing

Malaria Meds Focus Group Audio

https://drive.google.com/file/d/0B3_92O4iu-M3VDM0Ulp4aFUyeHdSak1BOUFFNUhKNTVHZHM4/edit?usp=sharing

Location of Volunteers

http://www.peacecorps.gov/volunteer/learn/wherepc/?noflash=yes

CDC Malaria

http://www.cdc.gov/malaria/

CDC Malaria Location Table

http://www.cdc.gov/malaria/travelers/country_table/a.html

CDC Malaria Location App

http://www.cdc.gov/malaria/map/index.html

Patrick Malaria Medication Presentation App

http://prezi.com/nw4b5winj4_c/malaria-meds-app/

Cool UCSF Mosquito Zapper

http://globalhealthsciences.ucsf.edu/education-training/blogs/masters-corner/ucsf-masters-candidate-comes-in-first-place-at-the-uc-berkel

Peace Corps Statement on Malaria and Volunteer Safety

http://www.peacecorps.gov/volunteer/learn/safety/support/ensuring/

Box Warning on Mefloquine

http://www.fda.gov/Drugs/DrugSafety/ucm362227.htm

Stomp Out Malaria

stompoutmalaria.org

+ diff --git a/malaria-app-android/Malaria Project Description.html b/malaria-app-android/Malaria Project Description.html new file mode 100644 index 00000000..07e503b2 --- /dev/null +++ b/malaria-app-android/Malaria Project Description.html @@ -0,0 +1,10 @@ + + + + + + +/8430$vsCKFnqBItq + +

Malaria Project Description

Peace Corps is looking to design a mobile app that will aid the Volunteer in sustaining life-saving malaria prevention tactics over their 2+ years of service. This includes sustained use of preventive meds, wearing of protective clothing and sleeping under a bed net. 

 

The hope is to use the latest thinking in using technology to influence behavior to provide assistance to the 1,000’s of Peace Corps Volunteers serving in Malaria endemic regions of the world. We are interested in experimenting with all possible options including gamification, social sharing, and tracking within a mobile application. 

 

Participants will be presented with two recent studies conducted by the CDC pertaining to use of preventative tactics by volunteers and their reasons for compliance or non-compliance. Participants will also be given access to experts at Peace Corps, State Dept. and the CDC to help understand the science of Malaria prevention and the findings of the recent research. 

 

The goal of this particular project is to create multiple prototypes for testing with volunteers. These prototypes will be presented to Volunteers in the field for their feedback during the week of the project and iterations of the prototypes will be created and tested again. Learnings from this rapid prototyping cycle will then be transferred to Peace Corps developers who will develop the most promising prototypes for a larger pilot. 

+ diff --git a/malaria-app-android/Malaria_Prevention_Documentation.PDF b/malaria-app-android/Malaria_Prevention_Documentation.PDF new file mode 100644 index 00000000..c8069692 Binary files /dev/null and b/malaria-app-android/Malaria_Prevention_Documentation.PDF differ diff --git a/malaria-app-android/Research Materials/CDC Malaria Map.pdf b/malaria-app-android/Research Materials/CDC Malaria Map.pdf new file mode 100644 index 00000000..0763bad0 Binary files /dev/null and b/malaria-app-android/Research Materials/CDC Malaria Map.pdf differ diff --git a/malaria-app-android/Research Materials/CDC Malaria Table.xlsx b/malaria-app-android/Research Materials/CDC Malaria Table.xlsx new file mode 100644 index 00000000..6108bda8 Binary files /dev/null and b/malaria-app-android/Research Materials/CDC Malaria Table.xlsx differ diff --git a/Screenshot_of_progress/Paper Draft .jpg b/malaria-app-android/Screenshot_of_progress/Paper Draft .jpg similarity index 100% rename from Screenshot_of_progress/Paper Draft .jpg rename to malaria-app-android/Screenshot_of_progress/Paper Draft .jpg diff --git a/Screenshot_of_progress/Screenshot testing.jpg b/malaria-app-android/Screenshot_of_progress/Screenshot testing.jpg similarity index 100% rename from Screenshot_of_progress/Screenshot testing.jpg rename to malaria-app-android/Screenshot_of_progress/Screenshot testing.jpg diff --git a/Screenshot_of_progress/Timeline Hacking Period.jpg b/malaria-app-android/Screenshot_of_progress/Timeline Hacking Period.jpg similarity index 100% rename from Screenshot_of_progress/Timeline Hacking Period.jpg rename to malaria-app-android/Screenshot_of_progress/Timeline Hacking Period.jpg diff --git a/Screenshot_of_progress/device-2014-05-29-155432.png b/malaria-app-android/Screenshot_of_progress/device-2014-05-29-155432.png similarity index 100% rename from Screenshot_of_progress/device-2014-05-29-155432.png rename to malaria-app-android/Screenshot_of_progress/device-2014-05-29-155432.png diff --git a/Screenshot_of_progress/device-2014-05-29-160442.png b/malaria-app-android/Screenshot_of_progress/device-2014-05-29-160442.png similarity index 100% rename from Screenshot_of_progress/device-2014-05-29-160442.png rename to malaria-app-android/Screenshot_of_progress/device-2014-05-29-160442.png diff --git a/Screenshot_of_progress/device-2014-05-29-160512.png b/malaria-app-android/Screenshot_of_progress/device-2014-05-29-160512.png similarity index 100% rename from Screenshot_of_progress/device-2014-05-29-160512.png rename to malaria-app-android/Screenshot_of_progress/device-2014-05-29-160512.png diff --git a/Screenshot_of_progress/device-2014-05-29-161250.png b/malaria-app-android/Screenshot_of_progress/device-2014-05-29-161250.png similarity index 100% rename from Screenshot_of_progress/device-2014-05-29-161250.png rename to malaria-app-android/Screenshot_of_progress/device-2014-05-29-161250.png diff --git a/Screenshot_of_progress/device-2014-05-29-161811.png b/malaria-app-android/Screenshot_of_progress/device-2014-05-29-161811.png similarity index 100% rename from Screenshot_of_progress/device-2014-05-29-161811.png rename to malaria-app-android/Screenshot_of_progress/device-2014-05-29-161811.png diff --git a/Screenshot_of_progress/device-2014-05-29-162315.png b/malaria-app-android/Screenshot_of_progress/device-2014-05-29-162315.png similarity index 100% rename from Screenshot_of_progress/device-2014-05-29-162315.png rename to malaria-app-android/Screenshot_of_progress/device-2014-05-29-162315.png diff --git a/Screenshot_of_progress/device-2014-05-29-162351.png b/malaria-app-android/Screenshot_of_progress/device-2014-05-29-162351.png similarity index 100% rename from Screenshot_of_progress/device-2014-05-29-162351.png rename to malaria-app-android/Screenshot_of_progress/device-2014-05-29-162351.png diff --git a/Screenshot_of_progress/device-2014-05-29-162408.png b/malaria-app-android/Screenshot_of_progress/device-2014-05-29-162408.png similarity index 100% rename from Screenshot_of_progress/device-2014-05-29-162408.png rename to malaria-app-android/Screenshot_of_progress/device-2014-05-29-162408.png diff --git a/Screenshot_of_progress/layout-2014-05-29-160514.png b/malaria-app-android/Screenshot_of_progress/layout-2014-05-29-160514.png similarity index 100% rename from Screenshot_of_progress/layout-2014-05-29-160514.png rename to malaria-app-android/Screenshot_of_progress/layout-2014-05-29-160514.png diff --git a/Screenshot_of_progress/layout-2014-05-29-160656.png b/malaria-app-android/Screenshot_of_progress/layout-2014-05-29-160656.png similarity index 100% rename from Screenshot_of_progress/layout-2014-05-29-160656.png rename to malaria-app-android/Screenshot_of_progress/layout-2014-05-29-160656.png diff --git a/Screenshot_of_progress/layout-2014-05-29-160854.png b/malaria-app-android/Screenshot_of_progress/layout-2014-05-29-160854.png similarity index 100% rename from Screenshot_of_progress/layout-2014-05-29-160854.png rename to malaria-app-android/Screenshot_of_progress/layout-2014-05-29-160854.png diff --git a/Screenshot_of_progress/layout-2014-05-29-161006.png b/malaria-app-android/Screenshot_of_progress/layout-2014-05-29-161006.png similarity index 100% rename from Screenshot_of_progress/layout-2014-05-29-161006.png rename to malaria-app-android/Screenshot_of_progress/layout-2014-05-29-161006.png diff --git a/Screenshot_of_progress/layout-2014-05-29-161745.png b/malaria-app-android/Screenshot_of_progress/layout-2014-05-29-161745.png similarity index 100% rename from Screenshot_of_progress/layout-2014-05-29-161745.png rename to malaria-app-android/Screenshot_of_progress/layout-2014-05-29-161745.png diff --git a/Screenshot_of_progress/layout-2014-05-29-162210.png b/malaria-app-android/Screenshot_of_progress/layout-2014-05-29-162210.png similarity index 100% rename from Screenshot_of_progress/layout-2014-05-29-162210.png rename to malaria-app-android/Screenshot_of_progress/layout-2014-05-29-162210.png diff --git a/Screenshot_of_progress/layout-2014-05-29-165054.png b/malaria-app-android/Screenshot_of_progress/layout-2014-05-29-165054.png similarity index 100% rename from Screenshot_of_progress/layout-2014-05-29-165054.png rename to malaria-app-android/Screenshot_of_progress/layout-2014-05-29-165054.png diff --git a/Screenshot_of_progress/paper Draft 2.jpg b/malaria-app-android/Screenshot_of_progress/paper Draft 2.jpg similarity index 100% rename from Screenshot_of_progress/paper Draft 2.jpg rename to malaria-app-android/Screenshot_of_progress/paper Draft 2.jpg diff --git a/Screenshot_of_progress/paper Draft 1.jpg b/malaria-app-android/Screenshot_of_progress/paper Draft 1.jpg similarity index 100% rename from Screenshot_of_progress/paper Draft 1.jpg rename to malaria-app-android/Screenshot_of_progress/paper Draft 1.jpg diff --git a/Screenshot_of_progress/screenshot.jpg b/malaria-app-android/Screenshot_of_progress/screenshot.jpg similarity index 100% rename from Screenshot_of_progress/screenshot.jpg rename to malaria-app-android/Screenshot_of_progress/screenshot.jpg diff --git a/ant.properties b/malaria-app-android/ant.properties similarity index 97% rename from ant.properties rename to malaria-app-android/ant.properties index b0971e89..a51e6a08 100644 --- a/ant.properties +++ b/malaria-app-android/ant.properties @@ -1,17 +1,17 @@ -# This file is used to override default values used by the Ant build system. -# -# This file must be checked into Version Control Systems, as it is -# integral to the build system of your project. - -# This file is only used by the Ant script. - -# You can use this to override default values such as -# 'source.dir' for the location of your java source folder and -# 'out.dir' for the location of your output folder. - -# You can also use it define how the release builds are signed by declaring -# the following properties: -# 'key.store' for the location of your keystore and -# 'key.alias' for the name of the key to use. -# The password will be asked during the build when you use the 'release' target. - +# This file is used to override default values used by the Ant build system. +# +# This file must be checked into Version Control Systems, as it is +# integral to the build system of your project. + +# This file is only used by the Ant script. + +# You can use this to override default values such as +# 'source.dir' for the location of your java source folder and +# 'out.dir' for the location of your output folder. + +# You can also use it define how the release builds are signed by declaring +# the following properties: +# 'key.store' for the location of your keystore and +# 'key.alias' for the name of the key to use. +# The password will be asked during the build when you use the 'release' target. + diff --git a/malaria-app-android/build.gradle b/malaria-app-android/build.gradle new file mode 100644 index 00000000..c881da32 --- /dev/null +++ b/malaria-app-android/build.gradle @@ -0,0 +1,54 @@ +apply plugin: 'com.android.application' +apply from: '../config/quality/quality.gradle' + +android { + compileSdkVersion rootProject.ext.compileSdkVersion + buildToolsVersion rootProject.ext.buildToolsVersion + + defaultConfig { + minSdkVersion rootProject.ext.minSdkVersion + targetSdkVersion rootProject.ext.targetSdkVersion + versionCode 1 + versionName "1.0" + } + + lintOptions { + abortOnError false + } + + buildTypes { + release { + minifyEnabled false + debuggable false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' + } + + debug { + debuggable true + } + } + +} + +dependencies { + implementation "com.android.support:support-v4:$rootProject.ext.supportLibraryVersion" + // v4 + implementation "com.viewpagerindicator:library:$rootProject.ext.viewPagerIndicatorVersion" + implementation "com.android.support:design:$rootProject.ext.supportLibraryVersion" + implementation "com.android.support:appcompat-v7:$rootProject.ext.supportLibraryVersion" + implementation "com.android.support.constraint:constraint-layout:$rootProject.ext.constraintLayoutVersion" + implementation files('libs/volleylib.jar') + implementation files('libs/GraphView-3.1.2.jar') + implementation 'com.android.support:support-v4:26.1.0' + testImplementation 'junit:junit:4.12' + compile 'com.github.vipulasri:timelineview:1.0.6' + implementation 'com.getkeepsafe.taptargetview:taptargetview:1.12.0' + //Room + implementation "android.arch.persistence.room:runtime:$room_version" + annotationProcessor "android.arch.persistence.room:compiler:$room_version" + //Butterknife + implementation 'com.jakewharton:butterknife:8.8.1' + annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' + implementation 'com.android.support:recyclerview-v7:27.1.1' + implementation 'com.android.support:cardview-v7:27.1.1' +} diff --git a/build.xml b/malaria-app-android/build.xml similarity index 97% rename from build.xml rename to malaria-app-android/build.xml index f11ead55..dcd26fb7 100644 --- a/build.xml +++ b/malaria-app-android/build.xml @@ -1,92 +1,92 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ic_launcher-web.png b/malaria-app-android/ic_launcher-web.png similarity index 100% rename from ic_launcher-web.png rename to malaria-app-android/ic_launcher-web.png diff --git a/libs/GraphView-3.1.2.jar b/malaria-app-android/libs/GraphView-3.1.2.jar similarity index 100% rename from libs/GraphView-3.1.2.jar rename to malaria-app-android/libs/GraphView-3.1.2.jar diff --git a/libs/volleylib.jar b/malaria-app-android/libs/volleylib.jar similarity index 100% rename from libs/volleylib.jar rename to malaria-app-android/libs/volleylib.jar diff --git a/lint.xml b/malaria-app-android/lint.xml similarity index 96% rename from lint.xml rename to malaria-app-android/lint.xml index ee0eead5..694ca087 100644 --- a/lint.xml +++ b/malaria-app-android/lint.xml @@ -1,3 +1,3 @@ - - + + \ No newline at end of file diff --git a/proguard-project.txt b/malaria-app-android/proguard-project.txt similarity index 85% rename from proguard-project.txt rename to malaria-app-android/proguard-project.txt index f2fe1559..c3ed044d 100644 --- a/proguard-project.txt +++ b/malaria-app-android/proguard-project.txt @@ -1,20 +1,23 @@ -# To enable ProGuard in your project, edit project.properties -# to define the proguard.config property as described in that file. -# -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in ${sdk.dir}/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the ProGuard -# include property in project.properties. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} +# To enable ProGuard in your project, edit project.properties +# to define the proguard.config property as described in that file. +# +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in ${sdk.dir}/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the ProGuard +# include property in project.properties. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} +-keepclassmembers class android.support.design.internal.BottomNavigationMenuView { + boolean mShiftingMode; +} diff --git a/project.properties b/malaria-app-android/project.properties similarity index 97% rename from project.properties rename to malaria-app-android/project.properties index ed6ad538..68d0cd37 100644 --- a/project.properties +++ b/malaria-app-android/project.properties @@ -1,15 +1,15 @@ -# This file is automatically generated by Android Tools. -# Do not modify this file -- YOUR CHANGES WILL BE ERASED! -# -# This file must be checked in Version Control Systems. -# -# To customize properties used by the Ant build system edit -# "ant.properties", and override values to adapt the script to your -# project structure. -# -# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): -#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt - -# Project target. -target=android-19 - +# This file is automatically generated by Android Tools. +# Do not modify this file -- YOUR CHANGES WILL BE ERASED! +# +# This file must be checked in Version Control Systems. +# +# To customize properties used by the Ant build system edit +# "ant.properties", and override values to adapt the script to your +# project structure. +# +# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): +#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt + +# Project target. +target=android-19 + diff --git a/malaria-app-android/src/main/AndroidManifest.xml b/malaria-app-android/src/main/AndroidManifest.xml new file mode 100644 index 00000000..09bc2b48 --- /dev/null +++ b/malaria-app-android/src/main/AndroidManifest.xml @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/fonts/garbold.ttf b/malaria-app-android/src/main/assets/fonts/garbold.ttf similarity index 100% rename from assets/fonts/garbold.ttf rename to malaria-app-android/src/main/assets/fonts/garbold.ttf diff --git a/assets/fonts/garreg.ttf b/malaria-app-android/src/main/assets/fonts/garreg.ttf similarity index 100% rename from assets/fonts/garreg.ttf rename to malaria-app-android/src/main/assets/fonts/garreg.ttf diff --git a/malaria-app-android/src/main/ic_launcher-web.png b/malaria-app-android/src/main/ic_launcher-web.png new file mode 100644 index 00000000..b4726185 Binary files /dev/null and b/malaria-app-android/src/main/ic_launcher-web.png differ diff --git a/src/com/peacecorps/malaria/DayFragmentActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/DayFragmentActivity.java similarity index 84% rename from src/com/peacecorps/malaria/DayFragmentActivity.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/DayFragmentActivity.java index 832a166f..7d361ba3 100644 --- a/src/com/peacecorps/malaria/DayFragmentActivity.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/DayFragmentActivity.java @@ -1,29 +1,31 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.activities; import android.app.Dialog; import android.content.Context; import android.content.Intent; -import android.database.sqlite.SQLiteDatabase; -import android.media.Image; +import android.content.SharedPreferences; import android.os.Bundle; +import android.preference.PreferenceManager; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.View; -import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; -import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; -import java.text.ParseException; +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.code.fragment.ThirdAnalyticFragment; +import com.peacecorps.malaria.code.model.SharedPreferenceStore; +import com.peacecorps.malaria.db.DatabaseSQLiteHelper; +import com.peacecorps.malaria.utils.CalendarFunction; + import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; -import java.util.Locale; /** * Created by Ankita on 6/13/2015. @@ -47,6 +49,9 @@ public class DayFragmentActivity extends FragmentActivity { private int flag=0; private long curr_time=0; private static DatabaseSQLiteHelper sqLite; + //yatna + private SharedPreferences sharedPreferences; + private SharedPreferences.Editor editor; @Override public void onCreate(Bundle savedInstanceState) { @@ -63,6 +68,9 @@ public void onCreate(Bundle savedInstanceState) { /*defining variables for accessing Database*/ sqLite= new DatabaseSQLiteHelper(this); + ImageButton btnChangeData = (ImageButton)findViewById(R.id.btnChangeData); + final ImageView indicator = (ImageView)findViewById(R.id.medi_indicator); + /*displaying clicked date on the Day Fragment*/ Intent intent = getIntent(); String selected_date = intent.getStringExtra(ThirdAnalyticFragment.DATE_TAG); @@ -106,73 +114,11 @@ public void onCreate(Bundle savedInstanceState) { /*Querying the database whether drug was taken on that specific day or not*/ Log.d(TAGD,"querying "+day+" "+month+" "+year+" "); - String data=sqLite.getMedicationData(day, month, year); + final String data=sqLite.getMedicationData(day, month, year); Log.d(TAGD, "++++++" + data + "++++++"); - /*Setting the Indicator according to the Result*/ - final ImageView indicator = (ImageView)findViewById(R.id.medi_indicator); - if(data.compareTo("yes")==0) - { - Toast.makeText(getApplicationContext(),"I took medicine!",Toast.LENGTH_LONG).show(); - indicator.setBackgroundResource(R.drawable.accept_medi_checked_); - } - else if(data.compareTo("no")==0) { - indicator.setBackgroundResource(R.drawable.reject_medi_checked); - Toast.makeText(getApplicationContext(), "I didn't take medicine!", Toast.LENGTH_LONG).show(); - } - else - { Log.d(TAGD,"Inside Missed Drug Entry"); - - selected_date=SharedPreferenceStore.mPrefsStore.getString("com.peacecorps.malaria.checkMediLastTakenTime",""); - SimpleDateFormat dateF = new SimpleDateFormat("dd/MM"); - Date cd=Calendar.getInstance().getTime(); - try { - cd = dateF.parse(selected_date); - } catch (Exception e) { - e.printStackTrace(); - } - cal.setTime(cd); - - Log.d(TAGD,"Medication Last Taken Time"); - Log.d(TAGD, "" + cal.get(Calendar.DATE)); - Log.d(TAGD, "" + cal.get(Calendar.MONTH)); - Log.d(TAGD, "" + cal.get(Calendar.YEAR)); - - long queried_date=comp_date.getTime(); - long last_medication_date = cd.getTime(); - - Calendar c= Calendar.getInstance(); - long current_date= c.getTimeInMillis(); - - - if(queried_date>=firstTime) - { - if(queried_date<=current_date) - { - Toast.makeText(getApplicationContext(), "I missed entering medicine!", Toast.LENGTH_LONG).show(); - sqLite.insertOrUpdateMissedMedicationEntry(day, month, year, 0); - } - else - { - Toast.makeText(getApplicationContext(), "This is a future date, you cannot edit it!", Toast.LENGTH_LONG).show(); - flag=1; - } - } - else { - //Toast.makeText(getApplicationContext(), "This is a date before medication even started, you can't edit it!", Toast.LENGTH_LONG).show(); - Toast.makeText(getApplicationContext(), "I missed entering medicine!", Toast.LENGTH_LONG).show(); - sqLite.insertOrUpdateMissedMedicationEntry(day, month, year, 0); - - } - - - - - - } /*Implementing Editing Data Button for a Day Page*/ - ImageButton btnChangeData = (ImageButton)findViewById(R.id.btnChangeData); btnChangeData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -187,7 +133,7 @@ public void onClick(View v) { TextView tv = (TextView) dialog.findViewById(R.id.text); tv.setText("Added inaccurate data? Don't worry, you can change here."); tv.setTextSize(17); - tv.setTextColor(getResources().getColor(R.color.golden_brown)); + tv.setTextColor(getResources().getColor(R.color.text_color_primary)); btnRadGroup = (RadioGroup) dialog.findViewById(R.id.radioGroup); @@ -230,10 +176,23 @@ public void onClick(View v) { } else { dosesInaRow = sqLite.getDosesInaRowDaily(); } - Log.d(TAGD,"Doses in a Row:"+dosesInaRow); + Log.d(TAGD, "Doses in a Row:" + dosesInaRow); SharedPreferenceStore.mEditor.putInt("com.peacecorps.malaria.dailyDose", dosesInaRow).apply(); indicator.setBackgroundResource(R.drawable.accept_medi_checked_); + sharedPreferences= PreferenceManager.getDefaultSharedPreferences(con); + editor=sharedPreferences.edit(); + int score=sharedPreferences.getInt("userScore",0); + int medicineStore=sharedPreferences.getInt("medicineStore",0); + if(data.compareTo("yes")==0){; + //do nothing as medicine has already been taken + }else{ + score=score+1; + editor.putInt("userScore",score); + editor.putInt("medicineStore",medicineStore-1); + editor.commit(); + } + } else if (ch.equalsIgnoreCase("no")) { Toast.makeText(con, btnRadButton.getText(), Toast.LENGTH_SHORT).show(); @@ -260,6 +219,19 @@ public void onClick(View v) { Log.d(TAGD, "Doses in a Row:" + dosesInaRow); SharedPreferenceStore.mEditor.putInt("com.peacecorps.malaria.dailyDose", dosesInaRow).apply(); indicator.setBackgroundResource(R.drawable.reject_medi_checked); + //yatna + sharedPreferences= PreferenceManager.getDefaultSharedPreferences(con); + editor=sharedPreferences.edit(); + int score=sharedPreferences.getInt("userScore",0); + int medicineStore=sharedPreferences.getInt("medicineStore",0); + if(data.compareTo("no")==0){; + //do nothing as medicine has already been taken + }else{ + score=score-1; + editor.putInt("userScore",score); + editor.putInt("medicineStore",medicineStore+1); + editor.commit(); + } } else dialog.dismiss(); } else { @@ -281,6 +253,73 @@ public void onClick(View v) { } }); + + /*Setting the Indicator according to the Result*/ + + if(data.compareTo("yes")==0) + { + Toast.makeText(getApplicationContext(),"I took medicine!",Toast.LENGTH_LONG).show(); + indicator.setBackgroundResource(R.drawable.accept_medi_checked_); + } + else if(data.compareTo("no")==0) { + indicator.setBackgroundResource(R.drawable.reject_medi_checked); + Toast.makeText(getApplicationContext(), "I didn't take medicine!", Toast.LENGTH_LONG).show(); + } + else + { Log.d(TAGD,"Inside Missed Drug Entry"); + + selected_date=SharedPreferenceStore.mPrefsStore.getString("com.peacecorps.malaria.checkMediLastTakenTime",""); + SimpleDateFormat dateF = new SimpleDateFormat("dd/MM"); + Date cd=Calendar.getInstance().getTime(); + try { + cd = dateF.parse(selected_date); + } catch (Exception e) { + e.printStackTrace(); + } + cal.setTime(cd); + + Log.d(TAGD,"Medication Last Taken Time"); + Log.d(TAGD, "" + cal.get(Calendar.DATE)); + Log.d(TAGD, "" + cal.get(Calendar.MONTH)); + Log.d(TAGD, "" + cal.get(Calendar.YEAR)); + + long queried_date=comp_date.getTime(); + long last_medication_date = cd.getTime(); + + Calendar c= Calendar.getInstance(); + long current_date= c.getTimeInMillis(); + + + if(queried_date>=firstTime) + { + if(queried_date<=current_date) + { + Toast.makeText(getApplicationContext(), "I missed entering medicine!", Toast.LENGTH_LONG).show(); + sqLite.insertOrUpdateMissedMedicationEntry(day, month, year, 0); + } + else + { + Toast.makeText(getApplicationContext(), "This is a future date, you cannot edit it!", Toast.LENGTH_LONG).show(); + btnChangeData.setBackgroundResource(R.drawable.roundedbutton_grey); + btnChangeData.setClickable(false); + flag=1; + } + } + else { + //Toast.makeText(getApplicationContext(), "This is a date before medication even started, you can't edit it!", Toast.LENGTH_LONG).show(); + Toast.makeText(getApplicationContext(), "I missed entering medicine!", Toast.LENGTH_LONG).show(); + sqLite.insertOrUpdateMissedMedicationEntry(day, month, year, 0); + + } + + + + + + } + + + } /**Computing the Adherence Rate for selected Date**/ @@ -318,9 +357,9 @@ public long checkDrugTakenTimeInterval(String time,long day_time) { SharedPreferenceStore.mEditor.putLong("com.peacecorps.malaria." + time, takenDate).apply(); if (SharedPreferenceStore.mPrefsStore.getBoolean("com.peacecorps.malaria.isWeekly", false)) { - interval = sqLite.getIntervalWeekly(start, end, SharedPreferenceStore.mPrefsStore.getInt("com.peacecorps.malaria.weeklyDay", 1)); + interval = CalendarFunction.getIntervalWeekly(start, end, SharedPreferenceStore.mPrefsStore.getInt("com.peacecorps.malaria.weeklyDay", 1)); } else { - interval = sqLite.getIntervalDaily(start, end); + interval = CalendarFunction.getIntervalDaily(start, end); } Log.d(TAGD,"First Date :"+ calt.get(Calendar.DATE)); Log.d(TAGD, "Current Date :" + cal.get(Calendar.DATE)); diff --git a/src/com/peacecorps/malaria/EffectivenessFragmentActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/EffectivenessFragmentActivity.java similarity index 81% rename from src/com/peacecorps/malaria/EffectivenessFragmentActivity.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/EffectivenessFragmentActivity.java index b8afdf6f..70a9c215 100644 --- a/src/com/peacecorps/malaria/EffectivenessFragmentActivity.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/EffectivenessFragmentActivity.java @@ -1,10 +1,12 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.activities; import android.app.ProgressDialog; +import android.graphics.Bitmap; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; +import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; @@ -12,6 +14,10 @@ import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; +import com.android.volley.toolbox.ImageRequest; +import com.peacecorps.malaria.utils.AuthJSONObjectRequest; +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.utils.VolleyApplication; import org.json.JSONException; import org.json.JSONObject; @@ -22,8 +28,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; -import java.net.Authenticator; -import java.net.PasswordAuthentication; /** * Created by Ankita on 6/8/2015. @@ -31,6 +35,7 @@ public class EffectivenessFragmentActivity extends FragmentActivity{ private TextView mEffectivenessLabel,mETitle; + private ImageView effectivenessImage ; private static String TAGE = EffectivenessFragmentActivity.class.getSimpleName(); @@ -38,6 +43,7 @@ public class EffectivenessFragmentActivity extends FragmentActivity{ //json object response url private String urlJsonObj = "http://pc-web-dev.systers.org/api/posts/6/?format=json"; + String urlImage = "https://cloud.githubusercontent.com/assets/8321130/17277500/1048dd3c-5762-11e6-928e-10c95eeca98f.jpg"; // temporary string to show the parsed response private String jsonResponse; @@ -50,6 +56,7 @@ public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.effectiveness_fragment); mEffectivenessLabel = (TextView) findViewById(R.id.effectivenessLabel); + effectivenessImage= (ImageView)findViewById(R.id.effectiveness_image); mETitle = (TextView)findViewById(R.id.eam); //"Please Wait..." Progress Dialog progressDialog = new ProgressDialog(this); @@ -66,6 +73,21 @@ private void makeJsonObjectRequest(){ Log.i(TAGE, "INSIDE JSON OBJECT REQUEST"); showpDialog(); //progress dialog shows loading...while the data is being fetched + //making a request to load and cache image + ImageRequest myrequest = new ImageRequest(urlImage, + new Response.Listener() { + @Override + public void onResponse(Bitmap bitmap) { + effectivenessImage.setImageBitmap(bitmap); + } + }, 0, 0, null, + new Response.ErrorListener() { + public void onErrorResponse(VolleyError error) { + Log.d(TAGE,"Error in loading Image"); + } + }); + + //making a authenticated JSON Object Request below AuthJSONObjectRequest jsonObjReq = new AuthJSONObjectRequest(Request.Method.GET, urlJsonObj, null , new Response.Listener() { @@ -121,6 +143,7 @@ public void onErrorResponse(VolleyError error) { StringBuffer buffer = new StringBuffer(); while ((line = input.readLine()) != null) { buffer.append(line); + buffer.append("\n"); } mEffectivenessLabel.setText(buffer.toString()); Log.d(TAGE, buffer.toString()); @@ -134,6 +157,7 @@ public void onErrorResponse(VolleyError error) { //Adding Request to request queue VolleyApplication.getInstance().addToRequestQueue(jsonObjReq); + VolleyApplication.getInstance().addToRequestQueue(myrequest); } private void showpDialog(){ diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/InfoHubFragmentActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/InfoHubFragmentActivity.java new file mode 100644 index 00000000..2662cab6 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/InfoHubFragmentActivity.java @@ -0,0 +1,87 @@ +package com.peacecorps.malaria.code.activities; + +import android.content.Intent; +import android.graphics.Typeface; +import android.os.Bundle; +import android.support.v4.app.FragmentActivity; +import android.view.View; +import android.widget.Button; +import android.widget.TextView; + +import com.peacecorps.malaria.R; + +/** + * Created by Chimdi on 7/18/14. + */ +public class InfoHubFragmentActivity extends FragmentActivity { + + Button btnPeaceCorpsPolicy, btnPercentSideEffects, btnSideEffectsPCV, + btnSideEffectsNPCV, btnVolunteerAdherence, btnEffectiveness; + TextView ihLabel; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.info_hub_screen); + + btnPeaceCorpsPolicy = (Button) findViewById(R.id.btn_peace_corps_policy); + btnPercentSideEffects = (Button) findViewById(R.id.btn_percent_side_effects); + btnSideEffectsPCV = (Button) findViewById(R.id.btn_side_effects_pcv); + btnSideEffectsNPCV = (Button) findViewById(R.id.btn_side_effects_non_pcv); + btnVolunteerAdherence = (Button) findViewById(R.id.btn_volunteer_adherence); + btnEffectiveness = (Button) findViewById(R.id.btn_effectiveness); + + + /**Setting fonts**/ + Typeface cf = Typeface.createFromAsset(getAssets(), "fonts/garreg.ttf"); + ihLabel.setTypeface(cf); + + addListeners(); + + } + + public void addListeners() { + + btnPeaceCorpsPolicy.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + startActivity(new Intent(getApplication().getApplicationContext(), PeaceCorpsPolicyFragmentActivity.class)); + } + }); + + btnPercentSideEffects.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + startActivity(new Intent(getApplication().getApplicationContext(), PercentSideEffectsFragmentActivity.class)); + } + }); + + btnSideEffectsPCV.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + startActivity(new Intent(getApplication().getApplicationContext(), SideEffectsPCVFragmentActivity.class)); + } + }); + + btnSideEffectsNPCV.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + startActivity(new Intent(getApplication().getApplicationContext(), SideEffectsNPCVFragmentActivity.class)); + } + }); + + btnVolunteerAdherence.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + startActivity(new Intent(getApplication().getApplicationContext(), VolunteerAdherenceFragmentActivity.class)); + } + }); + + btnEffectiveness.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + startActivity(new Intent(getApplication().getApplicationContext(), EffectivenessFragmentActivity.class)); + } + }); + } +} diff --git a/src/com/peacecorps/malaria/PeaceCorpsPolicyFragmentActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/PeaceCorpsPolicyFragmentActivity.java similarity index 74% rename from src/com/peacecorps/malaria/PeaceCorpsPolicyFragmentActivity.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/PeaceCorpsPolicyFragmentActivity.java index 0c191702..a37163c4 100644 --- a/src/com/peacecorps/malaria/PeaceCorpsPolicyFragmentActivity.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/PeaceCorpsPolicyFragmentActivity.java @@ -1,21 +1,24 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.activities; import android.app.ProgressDialog; import android.graphics.Typeface; import android.os.Bundle; +import android.speech.tts.TextToSpeech; import android.support.v4.app.FragmentActivity; import android.util.Log; +import android.view.View; +import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.android.volley.DefaultRetryPolicy; -import com.android.volley.NoConnectionError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; -import com.android.volley.VolleyLog; +import com.peacecorps.malaria.utils.AuthJSONObjectRequest; import com.peacecorps.malaria.R; +import com.peacecorps.malaria.utils.VolleyApplication; import org.json.JSONException; import org.json.JSONObject; @@ -26,9 +29,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; -import java.net.Authenticator; -import java.net.FileNameMap; -import java.net.PasswordAuthentication; +import java.util.Locale; /** * Created by Chimdi on 7/18/14. @@ -39,7 +40,9 @@ */ public class PeaceCorpsPolicyFragmentActivity extends FragmentActivity { - private TextView mPeaceCorpsPolicyLabel,pcp; + private TextView mPeaceCorpsPolicyLabel, pcp; + private Button ttsButton; + private TextToSpeech tts; private static String TAGPCP = PeaceCorpsPolicyFragmentActivity.class.getSimpleName(); @@ -52,7 +55,6 @@ public class PeaceCorpsPolicyFragmentActivity extends FragmentActivity { private String jsonResponse; - @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -61,6 +63,7 @@ public void onCreate(Bundle savedInstanceState) { mPeaceCorpsPolicyLabel = (TextView) findViewById(R.id.peaceCorpsPolicyLabel); pcp = (TextView) findViewById(R.id.pcp); + ttsButton = (Button) findViewById(R.id.ttsButton); //"Please Wait" progress dialog progressDialog = new ProgressDialog(this); progressDialog.setMessage("Please wait..."); @@ -73,14 +76,53 @@ public void onCreate(Bundle savedInstanceState) { mPeaceCorpsPolicyLabel.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/garreg.ttf")); pcp.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/garreg.ttf")); - /*HTTPAsyncTask conTask =new HTTPAsyncTask(this); - conTask.execute("http://pc-web-dev.systers.org");*/ - + //get the data makeJsonObjectRequest(); + } + + @Override + protected void onResume() { + //setup the tts language + tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { + @Override + public void onInit(int status) { + if (status != TextToSpeech.ERROR) { + tts.setLanguage(Locale.UK); + } + } + }); + //Implement the speak button + ttsButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + String toSpeak = mPeaceCorpsPolicyLabel.getText().toString(); + tts.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); + } + }); + + super.onResume(); + } + + //shutdown text to speech when the back button is pressed + public void onBackPressed() { + if (tts != null) { + tts.stop(); + tts.shutdown(); + } + finish(); + } + + @Override + protected void onPause() { + if (tts != null) { + tts.stop(); + tts.shutdown(); + } + super.onPause(); } - private void makeJsonObjectRequest(){ + private void makeJsonObjectRequest() { Log.i(TAGPCP, "INSIDE JSON OBJECT REQUEST"); showpDialog(); //progress dialog shows loading...while the data is being fetched @@ -92,7 +134,7 @@ public void onResponse(JSONObject response) { Log.d(TAGPCP, response.toString()); try { - Log.i(TAGPCP,"INSIDE JSON RESPONSE"); + Log.i(TAGPCP, "INSIDE JSON RESPONSE"); //parsing json object response String name = response.getString("title_post"); String desc = response.getString("description_post"); @@ -120,7 +162,7 @@ public void onResponse(JSONObject response) { } catch (JSONException e) { e.printStackTrace(); - Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); + Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } hidepDialog(); } @@ -160,14 +202,14 @@ public void onErrorResponse(VolleyError verror) { VolleyApplication.getInstance().addToRequestQueue(jsonObjReq); } - private void showpDialog(){ - if(!progressDialog.isShowing()) + private void showpDialog() { + if (!progressDialog.isShowing()) progressDialog.show(); //for showing the loading animation in Activity } - private void hidepDialog(){ - if(progressDialog.isShowing()) + private void hidepDialog() { + if (progressDialog.isShowing()) progressDialog.dismiss(); //for dismissing the loading animation in Activity } diff --git a/src/com/peacecorps/malaria/PercentSideEffectsFragmentActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/PercentSideEffectsFragmentActivity.java similarity index 82% rename from src/com/peacecorps/malaria/PercentSideEffectsFragmentActivity.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/PercentSideEffectsFragmentActivity.java index 63ae0d39..51818faa 100644 --- a/src/com/peacecorps/malaria/PercentSideEffectsFragmentActivity.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/PercentSideEffectsFragmentActivity.java @@ -1,10 +1,12 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.activities; import android.app.ProgressDialog; +import android.graphics.Bitmap; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; +import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; @@ -12,6 +14,10 @@ import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; +import com.android.volley.toolbox.ImageRequest; +import com.peacecorps.malaria.utils.AuthJSONObjectRequest; +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.utils.VolleyApplication; import org.json.JSONException; import org.json.JSONObject; @@ -22,8 +28,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; -import java.net.Authenticator; -import java.net.PasswordAuthentication; /** * Created by Ankita on 6/8/2015. @@ -32,6 +36,7 @@ public class PercentSideEffectsFragmentActivity extends FragmentActivity { //views and dialogs private TextView mPercentSideEffectsLabel,pse; + private ImageView sideEffectImage; private static String TAGPSE = PercentSideEffectsFragmentActivity.class.getSimpleName(); @@ -39,6 +44,7 @@ public class PercentSideEffectsFragmentActivity extends FragmentActivity { //json object response url private String urlJsonObj = "http://pc-web-dev.systers.org/api/posts/2/?format=json"; + private String urlImage ="https://cloud.githubusercontent.com/assets/8321130/17277636/4af66d7a-5765-11e6-9030-ddabe7d040cf.jpg"; // temporary string to show the parsed response private String jsonResponse; @@ -50,6 +56,7 @@ public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.side_effects_percentage_fragment); mPercentSideEffectsLabel = (TextView) findViewById(R.id.percentSideEffectsLabel); + sideEffectImage =(ImageView)findViewById(R.id.percent_side_effect_image); pse=(TextView)findViewById(R.id.pse); //"Please Wait" progress Dialog @@ -72,6 +79,20 @@ private void makeJsonObjectRequest(){ Log.i(TAGPSE, "INSIDE JSON OBJECT REQUEST"); showpDialog(); //progress dialog shows loading...while the data is being fetched + //Request to fetch and cache image + ImageRequest myrequest = new ImageRequest(urlImage, + new Response.Listener() { + @Override + public void onResponse(Bitmap bitmap) { + sideEffectImage.setImageBitmap(bitmap); + } + }, 0, 0, null, + new Response.ErrorListener() { + public void onErrorResponse(VolleyError error) { + Log.d(TAGPSE, "Error in loading Image"); + } + }); + //making a JSON Object Request below AuthJSONObjectRequest jsonObjReq = new AuthJSONObjectRequest(Request.Method.GET, urlJsonObj, null , new Response.Listener() { @@ -126,6 +147,7 @@ public void onErrorResponse(VolleyError error) { StringBuffer buffer = new StringBuffer(); while ((line = input.readLine()) != null) { buffer.append(line); + buffer.append("\n"); } mPercentSideEffectsLabel.setText(buffer.toString()); Log.d(TAGPSE, buffer.toString()); @@ -139,6 +161,7 @@ public void onErrorResponse(VolleyError error) { //Adding Request to request queue VolleyApplication.getInstance().addToRequestQueue(jsonObjReq); + VolleyApplication.getInstance().addToRequestQueue(myrequest); } private void showpDialog(){ @@ -153,4 +176,4 @@ private void hidepDialog(){ //for dismissing the loading animation in Activity } -} \ No newline at end of file +} diff --git a/src/com/peacecorps/malaria/SideEffectsNPCVFragmentActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/SideEffectsNPCVFragmentActivity.java similarity index 94% rename from src/com/peacecorps/malaria/SideEffectsNPCVFragmentActivity.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/SideEffectsNPCVFragmentActivity.java index 8aa7a782..6a280d70 100644 --- a/src/com/peacecorps/malaria/SideEffectsNPCVFragmentActivity.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/SideEffectsNPCVFragmentActivity.java @@ -1,4 +1,4 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.activities; import android.app.ProgressDialog; import android.graphics.Typeface; @@ -12,6 +12,9 @@ import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; +import com.peacecorps.malaria.utils.AuthJSONObjectRequest; +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.utils.VolleyApplication; import org.json.JSONException; import org.json.JSONObject; @@ -22,8 +25,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; -import java.net.Authenticator; -import java.net.PasswordAuthentication; /** * Created by Ankita on 6/8/2015. @@ -38,6 +39,7 @@ public class SideEffectsNPCVFragmentActivity extends FragmentActivity { //json object response url private String urlJsonObj = "http://pc-web-dev.systers.org/api/posts/4/?format=json"; + //private String urlJsonObj = "http://pc-web-dev.systers.org/api/malaria_posts"; // temporary string to show the parsed response private String jsonResponse; @@ -124,6 +126,7 @@ public void onErrorResponse(VolleyError error) { StringBuffer buffer = new StringBuffer(); while ((line = input.readLine()) != null) { buffer.append(line); + buffer.append("\n"); } mSideEffectsNPCVLabel.setText(buffer.toString()); Log.d(TAGSEN, buffer.toString()); diff --git a/src/com/peacecorps/malaria/SideEffectsPCVFragmentActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/SideEffectsPCVFragmentActivity.java similarity index 96% rename from src/com/peacecorps/malaria/SideEffectsPCVFragmentActivity.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/SideEffectsPCVFragmentActivity.java index 9a177fbf..72864512 100644 --- a/src/com/peacecorps/malaria/SideEffectsPCVFragmentActivity.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/SideEffectsPCVFragmentActivity.java @@ -1,4 +1,4 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.activities; import android.app.ProgressDialog; import android.graphics.Typeface; @@ -12,6 +12,9 @@ import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; +import com.peacecorps.malaria.utils.AuthJSONObjectRequest; +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.utils.VolleyApplication; import org.json.JSONException; import org.json.JSONObject; @@ -22,8 +25,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; -import java.net.Authenticator; -import java.net.PasswordAuthentication; /** * Created by Ankita on 6/8/2015. @@ -125,6 +126,7 @@ public void onErrorResponse(VolleyError error) { StringBuffer buffer = new StringBuffer(); while ((line = input.readLine()) != null) { buffer.append(line); + buffer.append("\n"); } mSideEffectsPCVLabel.setText(buffer.toString()); Log.d(TAGSEP, buffer.toString()); diff --git a/src/com/peacecorps/malaria/TripAlarmActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/TripAlarmActivity.java similarity index 65% rename from src/com/peacecorps/malaria/TripAlarmActivity.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/TripAlarmActivity.java index fc6f9d13..d7885c4c 100644 --- a/src/com/peacecorps/malaria/TripAlarmActivity.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/TripAlarmActivity.java @@ -1,20 +1,27 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.activities; import android.app.Activity; import android.app.AlarmManager; +import android.app.NotificationManager; import android.app.PendingIntent; +import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Typeface; +import android.media.Ringtone; import android.os.Bundle; import android.util.Log; import android.view.View; +import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; -import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.code.reciever.TripAlarmReceiver; +import com.peacecorps.malaria.db.DatabaseSQLiteHelper; + import java.util.Calendar; import java.util.Date; @@ -23,8 +30,6 @@ */ public class TripAlarmActivity extends Activity { - private SimpleCursorAdapter dataAdapter; - @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -33,6 +38,8 @@ public void onCreate(Bundle savedInstanceState) { TextView textView = (TextView)findViewById(R.id.tripRemindingItems); Button btnOK = (Button)findViewById(R.id.reminderOK); Button btnCancel = (Button)findViewById(R.id.reminderCancel); + NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); + mgr.cancel(1); //intent to get the Alarm ID Intent intent=this.getIntent(); @@ -40,7 +47,11 @@ public void onCreate(Bundle savedInstanceState) { Log.d("TAA", "AlarmID: " + intent.getIntExtra("AlarmID", 0)); - String msg= "Your Luggage should contain following items:-"; + String return_date = getApplication() + .getSharedPreferences("com.peacecorps.malaria.storeTimePicked", Context.MODE_PRIVATE) + .getString("com.peacecorps.malaria.trip_date", null); + + String msg= "Trip return date is : " + return_date + ".\n\n" + "Your Luggage should contain following items:-"; //setting fonts textView.setText(msg); @@ -51,22 +62,25 @@ public void onCreate(Bundle savedInstanceState) { Cursor cursor= sqlite.getPackingItemChecked(); - /** Columns to be Shown in The ListView **/ - String[] columns = {sqlite.KEY_ROW_ID,sqlite.PACKING_ITEM}; + /** Create the adapter using the cursor going through each row, + * and concatenating the item name to the quantity **/ + + String[] items_with_quantities = new String[cursor.getCount()]; + + int current_index = 0; - /**XML Bound Views according to the Column**/ - int[] to = new int[] { - R.id.reminderListItemNumber,R.id.reminderListItem - }; + while (cursor.moveToNext()) + { + String item = cursor.getString(cursor.getColumnIndex("PackingItem")); + String quantity = cursor.getString(cursor.getColumnIndex("Quantity")); + items_with_quantities[current_index] = item + "-" + quantity; + current_index++; + } - /** Create the adapter using the cursor pointing to the desired row in query - * made to database ,as well as the layout information**/ - dataAdapter = new SimpleCursorAdapter( - this, R.layout.trip_reminder_list_item, - cursor, - columns, - to, - 1); + ArrayAdapter dataAdapter = new ArrayAdapter( + this, + R.layout.trip_reminder_list_item, + items_with_quantities); ListView listView = (ListView) findViewById(android.R.id.list); /** Assign adapter to ListView **/ @@ -85,7 +99,7 @@ public void onCreate(Bundle savedInstanceState) { final Calendar calender = Calendar.getInstance(); Date date = new Date(); calender.setTime(date); - calender.add(Calendar.MINUTE, 5); + calender.add(Calendar.MINUTE, 1); /**Ok Listener **/ @@ -113,7 +127,9 @@ public void onClick(View v) { if(id==103) { alarmManager.set(AlarmManager.RTC_WAKEUP, calender.getTimeInMillis(), pendingSnooze); - Toast.makeText(getApplicationContext(),"Alarm Snoozed",Toast.LENGTH_LONG); + Ringtone ringtone= TripAlarmReceiver.ringtone; + ringtone.stop(); + Toast.makeText(getApplicationContext(),"Alarm Snoozed",Toast.LENGTH_LONG).show(); } finish(); diff --git a/src/com/peacecorps/malaria/VolunteerAdherenceFragmentActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/VolunteerAdherenceFragmentActivity.java similarity index 95% rename from src/com/peacecorps/malaria/VolunteerAdherenceFragmentActivity.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/VolunteerAdherenceFragmentActivity.java index 18962320..329a0a99 100644 --- a/src/com/peacecorps/malaria/VolunteerAdherenceFragmentActivity.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/activities/VolunteerAdherenceFragmentActivity.java @@ -1,4 +1,4 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.activities; import android.app.ProgressDialog; import android.graphics.Typeface; @@ -12,6 +12,9 @@ import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; +import com.peacecorps.malaria.utils.AuthJSONObjectRequest; +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.utils.VolleyApplication; import org.json.JSONException; import org.json.JSONObject; @@ -22,8 +25,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; -import java.net.Authenticator; -import java.net.PasswordAuthentication; /** * Created by Ankita on 6/8/2015. @@ -55,7 +56,7 @@ public void onCreate(Bundle savedInstanceState) { progressDialog.setMessage("Please wait..."); progressDialog.setCancelable(false); -//mking authenticated json object Request + //making authenticated json object Request Log.i(TAGVA, "INSIDE VOLUNTEER ADHERENCE"); mVolunteerAdherenceLabel.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/garreg.ttf")); @@ -125,6 +126,7 @@ public void onErrorResponse(VolleyError error) { StringBuffer buffer = new StringBuffer(); while ((line = input.readLine()) != null) { buffer.append(line); + buffer.append("\n"); } mVolunteerAdherenceLabel.setText(buffer.toString()); Log.d(TAGVA, buffer.toString()); diff --git a/src/com/peacecorps/malaria/ThirdAnalyticFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/fragment/ThirdAnalyticFragment.java similarity index 97% rename from src/com/peacecorps/malaria/ThirdAnalyticFragment.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/fragment/ThirdAnalyticFragment.java index 9ee3ec81..2911b142 100644 --- a/src/com/peacecorps/malaria/ThirdAnalyticFragment.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/fragment/ThirdAnalyticFragment.java @@ -1,4 +1,4 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.fragment; /** * Created by Ankita on 6/12/2015. @@ -11,10 +11,8 @@ import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; -import java.util.Locale; import android.annotation.SuppressLint; -import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; @@ -32,6 +30,9 @@ import android.widget.ImageView; import android.widget.TextView; +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.code.activities.DayFragmentActivity; +import com.peacecorps.malaria.db.DatabaseSQLiteHelper; public class ThirdAnalyticFragment extends Activity implements OnClickListener { @@ -61,7 +62,7 @@ public void onCreate(Bundle savedInstanceState) { /** Added by Ankita for getting specific month **/ Intent intent = getIntent(); - String mon= intent.getStringExtra(SecondAnalyticFragment.MONTH_REQ); + String mon= intent.getStringExtra("sendMonth"); Calendar cal; int intmon=0; Date dat; try{ dat = new SimpleDateFormat("MMMM").parse(mon); @@ -75,8 +76,8 @@ public void onCreate(Bundle savedInstanceState) { } _calendar = Calendar.getInstance(); year = _calendar.get(Calendar.YEAR); - _calendar.set(Calendar.MONTH,intmon+1); - month = _calendar.get(Calendar.MONTH); + _calendar.set(Calendar.MONTH,intmon); + month = _calendar.get(Calendar.MONTH)+1; Calendar cal_head= Calendar.getInstance(); cal_head.set(Calendar.MONTH,intmon); @@ -423,7 +424,7 @@ public View getView(int position, View convertView, ViewGroup parent) { break; case 2: gridcell.setBackgroundResource(R.drawable.calendar_button_selector); - gridcell.setTextColor(getResources().getColor(R.color.golden_brown)); + gridcell.setTextColor(getResources().getColor(R.color.text_color_primary)); break; } diff --git a/src/com/peacecorps/malaria/SharedPreferenceStore.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/model/SharedPreferenceStore.java similarity index 92% rename from src/com/peacecorps/malaria/SharedPreferenceStore.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/model/SharedPreferenceStore.java index a94a8a91..d6f52424 100755 --- a/src/com/peacecorps/malaria/SharedPreferenceStore.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/model/SharedPreferenceStore.java @@ -1,4 +1,4 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.model; import android.content.Context; import android.content.SharedPreferences; diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/DrugReminderCallerReceiver.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/DrugReminderCallerReceiver.java new file mode 100644 index 00000000..cc129504 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/DrugReminderCallerReceiver.java @@ -0,0 +1,14 @@ +package com.peacecorps.malaria.code.reciever; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +import com.peacecorps.malaria.notifications.DrugNotificationUtils; + +public class DrugReminderCallerReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + DrugNotificationUtils.startNotificationCheckSnooze(context); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/DrugReminderReceiver.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/DrugReminderReceiver.java new file mode 100644 index 00000000..998a2a2a --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/DrugReminderReceiver.java @@ -0,0 +1,266 @@ +package com.peacecorps.malaria.code.reciever; + +import android.app.AlarmManager; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.media.MediaPlayer; +import android.net.Uri; +import android.util.Log; +import android.widget.Toast; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.db.DatabaseSQLiteHelper; +import com.peacecorps.malaria.code.model.SharedPreferenceStore; +import com.peacecorps.malaria.notifications.service.AlarmService; +import com.peacecorps.malaria.utils.CalendarFunction; + +import java.util.Calendar; +import java.util.Date; + +public class DrugReminderReceiver extends BroadcastReceiver { + static SharedPreferenceStore mSharedPreferenceStore; + private static int mDrugAcceptedCount; + private static int mDrugRejectedCount; + private int flag; + String TAG = getClass().getName(); + + @Override + public void onReceive(Context context, Intent intent) { + NotificationManager alarmNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + switch (intent.getAction()) { + case "0": + //not taken + notTaken(context); + break; + case "1": + //snooze + if (flag == 0 || flag == 2) { + snooze(context); + } else { + Toast.makeText(context, "You have already taken medicine, no need to snooze.", Toast.LENGTH_SHORT).show(); + } + break; + case "2": + //taken + taken(context); + break; + } + alarmNotificationManager.cancel(12345); + playBlackGroundSound(context); + } + + private void playBlackGroundSound(Context context) { + Uri sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.soundsmedication); + final MediaPlayer mp = MediaPlayer.create(context,sound); + mp.start(); + } + + private void notTaken(Context context) { + getSharedPreferences(context); + getSettings(context); + if (flag == 0) { + if (mSharedPreferenceStore.mPrefsStore.getBoolean( + "com.peacecorps.malaria.isWeekly", false)) { + saveUsersettings(context,true, false); + /**Marked as Not Taken. No reminders now,it ll be for next time now.**/ + DatabaseSQLiteHelper databaseSQLiteHelper = new DatabaseSQLiteHelper(context); + databaseSQLiteHelper.getUserMedicationSelection(context, "weekly", + Calendar.getInstance().getTime(), + "no", computeAdherenceRate(context)); + changeWeeklyAlarmTime(context); + + } else { + if (checkDrugTakenTimeInterval("dateDrugTaken",context) > 0) { + saveUsersettings(context,false, false); + DatabaseSQLiteHelper databaseSQLiteHelper = new DatabaseSQLiteHelper(context); + databaseSQLiteHelper.getUserMedicationSelection(context, "daily", + Calendar.getInstance().getTime(), + "no", computeAdherenceRate(context)); + + } + } + } else { + if (flag == 1) { + Toast.makeText(context, "You have taken the medicine. Modify it later, if you have not taken it.", Toast.LENGTH_SHORT).show(); + + } else { + Toast.makeText(context, "You have not taken the medicine.", Toast.LENGTH_SHORT).show(); + snooze(context); + } + } + } + + public void getSharedPreferences(Context context) { + mSharedPreferenceStore.mPrefsStore = context + .getSharedPreferences(context.getString(R.string.shared_preferences_store_time_picked), + Context.MODE_PRIVATE); + mSharedPreferenceStore.mEditor = mSharedPreferenceStore.mPrefsStore + .edit(); + } + + + public void getSettings(Context context) { + /**Setting the reminder according to setting**/ + mDrugAcceptedCount = mSharedPreferenceStore.mPrefsStore.getInt( + context.getString(R.string.shared_preferences_drug_accepted_count), 0); + mDrugRejectedCount = mSharedPreferenceStore.mPrefsStore.getInt( + context.getString(R.string.shared_preferences_drug_rejected_count), 0); + + Calendar c = Calendar.getInstance(); + int d = c.get(Calendar.DATE); + int m = c.get(Calendar.MONTH); + int y = c.get(Calendar.YEAR); + + DatabaseSQLiteHelper sqLite = new DatabaseSQLiteHelper(context); + if (sqLite.getStatus(d, m, y).equalsIgnoreCase("yes") == true) { + flag = 1; + } else if (sqLite.getStatus(d, m, y).equalsIgnoreCase("no") == true) { + flag = 2; + } else + flag = 0; + + } + + public void changeWeeklyAlarmTime(Context context) { + /**Function to set the alarm for next week**/ + int hour = Calendar.getInstance().get(Calendar.HOUR); + int minute = Calendar.getInstance().get(Calendar.MINUTE) - 1; + context.startService( + new Intent(context, AlarmService.class)); + mSharedPreferenceStore.mEditor + .putInt(context.getString(R.string.shared_preferences_alarm_hour), hour) + .commit(); + mSharedPreferenceStore.mEditor + .putInt(context.getString(R.string.shared_preferences_alarm_minute), minute) + .commit(); + } + + public void saveUsersettings(Context context, Boolean state, Boolean isWeekly) { + if (isWeekly) { + /**Storing the Dates**/ + mSharedPreferenceStore.mEditor + .putLong(context.getString(R.string.shared_preferences_weekly_date), + new Date().getTime()).commit(); + mSharedPreferenceStore.mEditor.putBoolean( + context.getString(R.string.shared_preferences_is_weekly_drug_taken), state) + .commit(); + } else { + mSharedPreferenceStore.mEditor + .putLong(context.getString(R.string.shared_preferences_date_drug_taken), + new Date().getTime()).commit(); + mSharedPreferenceStore.mEditor + .putBoolean(context.getString(R.string.shared_preferences_is_drug_taken), + state).commit(); + } + mSharedPreferenceStore.mEditor + .putInt(context.getString(R.string.shared_preferences_drug_rejected_count), + mDrugRejectedCount).commit(); + mSharedPreferenceStore.mEditor + .putInt(context.getString(R.string.shared_preferences_drug_accepted_count), + mDrugAcceptedCount).commit(); + + } + + public void snooze(Context context) { + /**Snoozing The Alarm**/ + getSharedPreferences(context); + Intent intent = new Intent(context, + DrugReminderCallerReceiver.class); + PendingIntent pendingSnooze = PendingIntent.getBroadcast( + context.getApplicationContext(), 0, intent, + PendingIntent.FLAG_UPDATE_CURRENT); + AlarmManager alarmManager = (AlarmManager) context + .getSystemService(context.ALARM_SERVICE); + Calendar calender = Calendar.getInstance(); + Date date = new Date(); + calender.setTime(date); + calender.add(Calendar.MINUTE, 10); + alarmManager.set(AlarmManager.RTC_WAKEUP, + calender.getTimeInMillis(), pendingSnooze); + + + } + + + private void taken(Context context) { + getSharedPreferences(context); + getSettings(context); + if (flag == 0) { + if (mSharedPreferenceStore.mPrefsStore.getBoolean( + "com.peacecorps.malaria.isWeekly", false)) { + /**Updates the date when weekly drug was taken and set the alarm for nex weekly Date**/ + saveUsersettings(context,true, true); + DatabaseSQLiteHelper databaseSQLiteHelper = new DatabaseSQLiteHelper(context); + databaseSQLiteHelper.getUserMedicationSelection(context, "weekly", Calendar.getInstance().getTime(), + "yes", computeAdherenceRate(context)); + changeWeeklyAlarmTime(context); + + } else { + /**Updating the Daily Alarm and Cancelling today's notification because Drug is already Taken**/ + if (checkDrugTakenTimeInterval("dateDrugTaken", context) > 0) { + saveUsersettings(context,true, false); + DatabaseSQLiteHelper databaseSQLiteHelper = new DatabaseSQLiteHelper(context); + databaseSQLiteHelper.getUserMedicationSelection(context, "daily", Calendar.getInstance().getTime(), + "yes", computeAdherenceRate(context)); + + } + } + } else { + if (flag == 1) { + Toast.makeText(context, "You have already taken medicine", Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(context, "You have not taken medicine. Modify later, if you have taken.", Toast.LENGTH_SHORT).show(); + snooze(context); + } + } + } + + public long checkDrugTakenTimeInterval(String time, Context context) { + long interval = 0; + + /**Calculating the Interval**/ + long today = new Date().getTime(); + Date tdy = Calendar.getInstance().getTime(); + tdy.setTime(today); + DatabaseSQLiteHelper sqLite = new DatabaseSQLiteHelper(context); + long takenDate = sqLite.getFirstTime(); + if (time.compareTo("firstRunTime") == 0) { + if (takenDate != 0) { + Log.d(TAG, "First Run Time at ADF->" + takenDate); + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(takenDate); + cal.add(Calendar.MONTH, 1); + Date start = cal.getTime(); + int weekDay = cal.get(Calendar.DAY_OF_WEEK); + if (SharedPreferenceStore.mPrefsStore.getBoolean("com.peacecorps.malaria.isWeekly", false)) + interval = CalendarFunction.getIntervalWeekly(start, tdy, weekDay); + else + interval = CalendarFunction.getIntervalDaily(start, tdy); + SharedPreferenceStore.mEditor.putLong("com.peacecorps.malaria." + + time, takenDate).apply(); + + return interval; + } else + return 1; + } else { + takenDate = SharedPreferenceStore.mPrefsStore.getLong("com.peacecorps.malaria." + + time, takenDate); + long oneDay = 1000 * 60 * 60 * 24; + interval = (today - takenDate) / oneDay; + return interval; + } + } + + public double computeAdherenceRate(Context context) { + /**calculating Adherence Rate**/ + long interval = checkDrugTakenTimeInterval("firstRunTime",context); + DatabaseSQLiteHelper sqLite = new DatabaseSQLiteHelper(context); + long takenCount = sqLite.getCountTaken(); + double adherenceRate = ((double) takenCount / (double) interval) * 100; + Log.d(TAG, "adherence:" + adherenceRate); + return adherenceRate; + } +} diff --git a/src/com/peacecorps/malaria/TripAlarmReceiver.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/TripAlarmReceiver.java similarity index 72% rename from src/com/peacecorps/malaria/TripAlarmReceiver.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/TripAlarmReceiver.java index 5155acb3..d3a1a7e4 100644 --- a/src/com/peacecorps/malaria/TripAlarmReceiver.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/TripAlarmReceiver.java @@ -1,4 +1,4 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.reciever; /** * Created by Ankita on 8/8/2015. @@ -7,6 +7,7 @@ import android.content.ComponentName; import android.content.Context; import android.content.Intent; +import android.content.SharedPreferences; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; @@ -14,6 +15,8 @@ import android.support.v4.content.WakefulBroadcastReceiver; import android.util.Log; +import com.peacecorps.malaria.code.reciever.services.TripAlarmService; + /** * On receiving the calarm call from Alarm Service, * it sets the parameter for ring alarm @@ -21,11 +24,10 @@ public class TripAlarmReceiver extends WakefulBroadcastReceiver { + public static Ringtone ringtone; @Override public void onReceive(final Context context, Intent intent) { //this will update the UI with message - TripIndicatorFragmentActivity inst = TripIndicatorFragmentActivity.instance(); - PowerManager powerManager = (PowerManager) context .getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock( @@ -35,13 +37,23 @@ public void onReceive(final Context context, Intent intent) { //this will sound the alarm tone //this will sound the alarm once, if you wish to //raise alarm in loop continuously then use MediaPlayer and setLooping(true) + SharedPreferences prefs = context.getSharedPreferences("ringtone", 0); + String restoredText = prefs.getString("toneUri", null); + Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); if (alarmUri == null) { - alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); + alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); + } + // if shared preference is not empty then the user selected tone will be played + if(restoredText!=null) + { + alarmUri= Uri.parse(restoredText); } - Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri); + + ringtone = RingtoneManager.getRingtone(context, alarmUri); ringtone.play(); + //this will send a notification message ComponentName comp = new ComponentName(context.getPackageName(), TripAlarmService.class.getName()); @@ -49,7 +61,7 @@ public void onReceive(final Context context, Intent intent) { startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); - + //Todo incorrect wakelock usage, check it wakeLock.release(); Log.d("TripAlarmReceiver","Set the service"); diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/notification/DrugReminderNotification.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/notification/DrugReminderNotification.java new file mode 100644 index 00000000..1ca388dc --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/notification/DrugReminderNotification.java @@ -0,0 +1,95 @@ +package com.peacecorps.malaria.code.reciever.notification; + +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.support.v4.app.NotificationCompat; +import android.util.Log; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.main.MainActivity; +import com.peacecorps.malaria.code.reciever.DrugReminderReceiver; +import com.peacecorps.malaria.db.DatabaseSQLiteHelper; + +import java.util.Calendar; + +public class DrugReminderNotification { + private Context context; + + public DrugReminderNotification(Context context) { + this.context = context; + buildNotification(); + } + + private void buildNotification() { + NotificationManager notificationManager; + notificationManager = (NotificationManager) context + .getSystemService(Context.NOTIFICATION_SERVICE); + + PendingIntent contentIntent = PendingIntent.getActivity(context, 0, + new Intent(context, MainActivity.class), 0); + + /* Add Actions in Notification + /*Action Not Taken*/ + Intent intentNotTaken = new Intent(context, DrugReminderReceiver.class); + intentNotTaken.setAction(context.getString(R.string.notification_action_code_not_taken)); + PendingIntent pendingIntentNotTaken = PendingIntent.getBroadcast(context, 0, intentNotTaken, + PendingIntent.FLAG_UPDATE_CURRENT); + NotificationCompat.Action actionNotTaken; + actionNotTaken = new NotificationCompat.Action(R.drawable.ic_cancel_black_18dp, context.getString(R.string.drug_reminder_notification_action_not_taken) + , pendingIntentNotTaken); + + /*Action Taken*/ + Intent intentTaken = new Intent(context, DrugReminderReceiver.class); + intentTaken.setAction(context.getString(R.string.notification_action_code_taken)); + PendingIntent pendingIntentTaken = PendingIntent.getBroadcast(context, 0, intentTaken, PendingIntent.FLAG_UPDATE_CURRENT); + NotificationCompat.Action actionTaken; + actionTaken = new NotificationCompat.Action(R.drawable.ic_done_black_18dp, context.getString(R.string.drug_reminder_notification_action_taken) + , pendingIntentTaken); + + Uri sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.soundsmedication); + /**Building Notifications**/ + NotificationCompat.Builder builder = new NotificationCompat.Builder( + context).setContentTitle(context.getString(R.string.drug_reminder_notification_title)) + .setSmallIcon(R.drawable.app_icon) + .setStyle(new NotificationCompat.BigTextStyle().bigText(context.getString(R.string.drug_reminder_notification_message))) + .setContentText(context.getString(R.string.drug_reminder_notification_message)) + .setAutoCancel(false) + .setOngoing(true) + .addAction(actionNotTaken) + .addAction(actionTaken); + + if (addSnoozeButton()) { + /*Action Snooze*/ + Intent intentSnooze = new Intent(context, DrugReminderReceiver.class); + intentSnooze.setAction(context.getString(R.string.notification_action_code_snooze)); + PendingIntent pendingIntentSnooze = PendingIntent.getBroadcast(context, 0, intentSnooze, + PendingIntent.FLAG_UPDATE_CURRENT); + NotificationCompat.Action actionSnooze; + actionSnooze = new NotificationCompat.Action(R.drawable.ic_snooze_black_18dp, context.getString(R.string.drug_reminder_notification_action_snooze) + , pendingIntentSnooze); + + builder.addAction(actionSnooze); + } + builder.setSound(sound); + builder.setContentIntent(contentIntent); + notificationManager.notify(12345, builder.build()); + Log.d("DrugReminderNotif", "Notification sent."); + } + + private boolean addSnoozeButton() { + Calendar c = Calendar.getInstance(); + int d = c.get(Calendar.DATE); + int m = c.get(Calendar.MONTH); + int y = c.get(Calendar.YEAR); + DatabaseSQLiteHelper sqLite = new DatabaseSQLiteHelper(context); + if (sqLite.getStatus(d, m, y).equalsIgnoreCase("yes") == true) { + return false; + } else if (sqLite.getStatus(d, m, y).equalsIgnoreCase("no") == true) { + return true; + } else + return true; + } +} diff --git a/src/com/peacecorps/malaria/TripAlarmService.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/services/TripAlarmService.java similarity index 58% rename from src/com/peacecorps/malaria/TripAlarmService.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/services/TripAlarmService.java index b179b806..0acc7f6a 100644 --- a/src/com/peacecorps/malaria/TripAlarmService.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/reciever/services/TripAlarmService.java @@ -1,4 +1,4 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.code.reciever.services; /** * Created by Ankita on 8/8/2015. @@ -8,11 +8,16 @@ import android.app.PendingIntent; import android.content.Context; import android.content.Intent; +import android.content.SharedPreferences; import android.support.v4.app.NotificationCompat; import android.util.Log; +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.code.activities.TripAlarmActivity; +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.utils.InjectionClass; + public class TripAlarmService extends IntentService { - private NotificationManager alarmNotificationManager; public TripAlarmService() { super("TripAlarmService"); @@ -20,13 +25,16 @@ public TripAlarmService() { @Override public void onHandleIntent(Intent intent) { - sendNotification("Get Ready to Pack your Bags for Trip!" + "\n" + TripIndicatorFragmentActivity.mItemPicked, intent); + AppDataManager dataManager = InjectionClass.provideDataManager(this); + SharedPreferences preferences = getSharedPreferences("WidgetReminder", Context.MODE_PRIVATE); + sendNotification("Get Ready to Pack your Bags!" + "\n" + + dataManager.getReminderMessageForTrip(), intent); } private void sendNotification(String msg,Intent intent) { Log.d("AlarmService", "Preparing to send notification...: " + msg); - alarmNotificationManager = (NotificationManager) this + NotificationManager alarmNotificationManager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE); Intent activIntent = new Intent(this,TripAlarmActivity.class); @@ -37,13 +45,15 @@ private void sendNotification(String msg,Intent intent) { activIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder( - this).setContentTitle("Reminder for Trip").setSmallIcon(R.drawable.appicon_themed) + this).setContentTitle("Upcoming Trip Reminder").setSmallIcon(R.drawable.app_icon) .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) - .setContentText(msg); + .setContentText(msg) + .addAction(R.drawable.checked, "Trip Checklist", contentIntent) + .setOngoing(true); - alamNotificationBuilder.setContentIntent(contentIntent); + //alamNotificationBuilder.setContentIntent(contentIntent); alarmNotificationManager.notify(1, alamNotificationBuilder.build()); Log.d("TripAlarmService", "Notification sent."); } -} \ No newline at end of file +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/code/widget/MedicineStatusWidgetProvider.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/widget/MedicineStatusWidgetProvider.java new file mode 100644 index 00000000..64ca696d --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/code/widget/MedicineStatusWidgetProvider.java @@ -0,0 +1,71 @@ +package com.peacecorps.malaria.code.widget; + +import android.app.PendingIntent; +import android.appwidget.AppWidgetManager; +import android.appwidget.AppWidgetProvider; +import android.content.Context; +import android.content.Intent; +import android.util.Log; +import android.widget.RemoteViews; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.code.fragment.ThirdAnalyticFragment; +import com.peacecorps.malaria.code.activities.DayFragmentActivity; +import com.peacecorps.malaria.db.DatabaseSQLiteHelper; + +import java.util.Calendar; +import java.util.Date; + +/** + * Created by yatna on 28/5/16. + */ +public class MedicineStatusWidgetProvider extends AppWidgetProvider{ + + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + final int N = appWidgetIds.length; + + // Perform this loop procedure for each App Widget that belongs to this provider + for (int i=0; i= 10) { + ts = "" + cal.get(Calendar.YEAR) + "/" + monthStr + "/" + cal.get(Calendar.DATE); + } else { + ts = "" + cal.get(Calendar.YEAR) + "/" + monthStr + "/0" + cal.get(Calendar.DATE); + } + final UserMedicine userMedicine = new UserMedicine(drug, choice, cal.get(Calendar.MONTH), cal.get(Calendar.YEAR), cal.get(Calendar.DATE), status, percentage, ts); + Runnable medicineRunnable = new Runnable() { + @Override + public void run() { + userMedicineDao.setUserMedicineSelection(userMedicine); + } + }; + appExecutors.diskIO().execute(medicineRunnable); + } + + /*Method to Be used in Future for storing appSettings directly in the Database, decreasing complexity**/ + @Override + public void insertAppSettings(String drug, String choice, long date) { + Calendar c = Calendar.getInstance(); + c.setTimeInMillis(date); + int w = c.get(Calendar.DAY_OF_WEEK); + final AppSetting appSetting = new AppSetting(drug, choice, w, date, "true"); + Runnable runnable = new Runnable() { + @Override + public void run() { + String value = appSettingDao.checkFirstInstall(); + if (value.compareTo("true") == 0) { + appSettingDao.deleteFirstRow(); + appSettingDao.insertAppSettings(appSetting); + } else { + appSettingDao.insertAppSettings(appSetting); + } + } + }; + appExecutors.diskIO().execute(runnable); + } + + /** + * Getting Medication Data of Each Day in Day Fragment Activity + **/ + @Override + public void getMedicationData(final int date, final int month, final int year, final LoadStringCallback callback) { + final StringBuffer buffer = new StringBuffer(); + Runnable medicationRunnable = new Runnable() { + @Override + public void run() { + List userMedicines = userMedicineDao.getMedicationData("daily", month, year); + for (UserMedicine medicine : userMedicines) { + int d = medicine.getDate(); + String ch = medicine.getStatus(); + if (d == date) { + buffer.append(ch); + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(buffer.toString()); + } + }); + } + } + } + }; + appExecutors.diskIO().execute(medicationRunnable); + } + + /** + * Method to Modify the entry of Each Day + **/ + @Override + public void updateMedicationEntry(final int date, final int month, final int year, final String entry, final double percentage) { + Runnable runnable = new Runnable() { + @Override + public void run() { + userMedicineDao.updateMedicationEntry(date, month, year, entry, percentage); + } + }; + appExecutors.diskIO().execute(runnable); + } + + //Todo Confused in logic -- followed existing code as it is, check logic later + /*If No Entry will be found it will enter in the database, so that it can be later updated. + * Usage is in Day Fragment Activity **/ + @Override + public void insertOrUpdateMissedMedicationEntry(final String drug, final String ch, final int date, final int month, final int year, final double percentage) { + Runnable runnable = new Runnable() { + @Override + public void run() { + String ts; + // calculation of timestamp + if (date >= 10) { + ts = "" + year + "-" + month + "-" + date; + } else { + ts = "" + year + "-" + month + "-0" + date; + } + int flag = 0; + List statusList = userMedicineDao.getStatusListByDateMonthYear(date, month, year); + if (statusList.size() > 0) + flag = 1; + + if (flag == 0) { + UserMedicine userMedicine = new UserMedicine(drug, ch, month, year, date, "", percentage, ts); + userMedicineDao.setUserMedicineSelection(userMedicine); + + List dateList = userMedicineDao.getDateListByMonthYear(month, year); + int count = 1, p, lim, ft = 0; + for (int i : dateList) { + p = i; + count++; + if (count == 1) { + ft = p; + } else if (count == 2) { + lim = p - ft; + for (int j = 1; j < lim; j++) { + if ((date + j) >= 10) { + ts = "" + year + "-" + month + "-" + (date + j); + } else { + ts = "" + year + "-" + month + "-0" + (date + j); + } + userMedicineDao.setUserMedicineSelection(new UserMedicine(drug, ch, month, year, date + j, "", percentage, ts)); + } + } + } + } + } + }; + appExecutors.diskIO().execute(runnable); + } + + /*Is Entered is Used for Getting the Style of Each Calendar Grid Cell According to the Medication Status Taken or Not Taken*/ + @Override + public void isEntered(final int date, final int month, final int year, final LoadIntegerCallback callback) { + Runnable runnable = new Runnable() { + @Override + public void run() { + final String status = userMedicineDao.isEntered(date, month, year); + + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + if (status.equalsIgnoreCase("yes")) { + callback.onDataLoaded(0); + } else if (status.equalsIgnoreCase("no")) { + callback.onDataLoaded(1); + } + } + }); + } + }; + appExecutors.diskIO().execute(runnable); + + } + + /** + * Getting the oldest registered entry of Pill + **/ + @Override + public void getFirstTimeByTimeStamp(final LoadLongCallback callback) { + Runnable runnable = new Runnable() { + @Override + public void run() { + String timeStamp = userMedicineDao.getFirstTimeTimeStamp(); + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()); + Date comp_date = Calendar.getInstance().getTime(); + try { + comp_date = sdf.parse(timeStamp); + } catch (Exception e) { + ToastLogSnackBarUtil.showErrorLog("AppDbHelper: Exception in parsing date " + timeStamp); + } + final Calendar cal = Calendar.getInstance(); + cal.setTime(comp_date); + final long firstRunTime = cal.getTimeInMillis(); + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(firstRunTime); + } + }); + } + }; + appExecutors.diskIO().execute(runnable); + } + + /** + * Getting the Status of Each Day, like whether the Medicine was taken or not. + * Usages in Alert Dialog Fragment for getting the status of pill for setting up Reminder + * Usages in Day Fragment Activity for getting the previous status of day before updating it as not taken. + **/ + @Override + public void getDailyStatus(final int date, final int month, final int year, final LoadStringCallback callback) { + Runnable runnable = new Runnable() { + @Override + public void run() { + final String status = userMedicineDao.getDailyStatus(date, month, year); + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + if (status != null) { + callback.onDataLoaded(status); + } else { + callback.onDataLoaded("miss"); + } + } + }); + + } + }; + appExecutors.diskIO().execute(runnable); + } + + /** + * From the Last Time Pill was Taken it Calculates the maximum weeks in a row medication was taken + * Need at Home Screen, First Analytic Scrren, Second Analytic Scrren, Day Fragment Screen + * Main Activity for updating the dosesInArow as it changes according to the status we enter. + **/ + @Override + public void getDosesInaRowWeekly(final LoadIntegerCallback callback) { + Runnable runnable = new Runnable() { + @Override + public void run() { + List userMedicines = userMedicineDao.getDosesInaRow(); + int dosesInaRow = 1; + int aMonth; + int pMonth; + Date ado, pdo; + int pPara; + long aPara; + int numDays; + String ats; + String pts; + if (userMedicines != null) { + ats = userMedicines.get(0).getTimeStamp(); + aMonth = userMedicines.get(0).getMonth() + 1; + ats = getHumanDateFormat(ats, aMonth); + ado = getDateObject(ats); + + int size = userMedicines.size() - 1; + for (int i = 1; i <= size; i++) { + pts = userMedicines.get(i).getTimeStamp(); + pMonth = userMedicines.get(i).getMonth() + 1; + pts = getHumanDateFormat(pts, pMonth); + pdo = getDateObject(pts); + numDays = CalendarFunction.getDayofWeek(pdo); + pPara = 7 - numDays + 7; + aPara = CalendarFunction.getNumberOfDays(pdo, ado); + if (aPara <= pPara) { + dosesInaRow++; + } else { + break; + } + ado = pdo; + } + + + } + final int finalDosesInaRow = dosesInaRow; + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(finalDosesInaRow); + } + }); + } + }; + appExecutors.diskIO().execute(runnable); + } + + @Override + public void getDosesInaRowDaily(final LoadIntegerCallback callback) { + Runnable runnable = new Runnable() { + @Override + public void run() { + List userMedicines = userMedicineDao.getDosesInaRow(); + int dosesInaRow = 0; + int prevDate = 0; + int currDate; + int currDateMonth; + int prevDateMonth = 0; + int currDateYear; + + String ts; + /**One Iteration is done before entering the while loop for updating the previous and current date**/ + if (userMedicines.size() > 0) { + ts = userMedicines.get(0).getTimeStamp(); + currDate = userMedicines.get(0).getDate(); + ToastLogSnackBarUtil.showDebugLog("curr date 1->" + ts); + + if (userMedicines.get(0).getStatus() != null && (userMedicines.get(0).getStatus().compareTo("yes") == 0)) { + prevDate = userMedicines.get(0).getDate(); + prevDateMonth = userMedicines.get(0).getMonth(); + if (Math.abs(currDate - prevDate) <= 1) + dosesInaRow++; + } + + /**Since Previous and Current Date our Updated, + * Now backwards scan is done till we receive consecutive previous and current date **/ + for (UserMedicine medicine : userMedicines) { + currDate = medicine.getDate(); + currDateMonth = medicine.getMonth(); + currDateYear = medicine.getYear(); + ts = medicine.getTimeStamp(); + ToastLogSnackBarUtil.showDebugLog("curr date -> " + ts); + + int parameter = Math.abs(currDate - prevDate); + if (medicine.getStatus() != null) { + if (currDateMonth == prevDateMonth) { + if (medicine.getStatus().compareTo("yes") == 0 && parameter == 1) { + dosesInaRow++; + } else + break; + } else { + parameter = Math.abs(currDate - prevDate) % + (CalendarFunction.getNumberOfDaysInMonth(currDateMonth, currDateYear) - 1); + if (medicine.getStatus().compareTo("yes") == 0 && parameter <= 1) { + dosesInaRow++; + } else + break; + } + } + prevDate = currDate; + prevDateMonth = currDateMonth; + ToastLogSnackBarUtil.showDebugLog("Doses in Row-> " + dosesInaRow); + } + } + ToastLogSnackBarUtil.showDebugLog("Final doses in row-> " + dosesInaRow); + final int finalDosesInaRow = dosesInaRow; + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(finalDosesInaRow); + } + }); + } + }; + appExecutors.diskIO().execute(runnable); + } + + /*Deleting the Database*/ + @Override + public void resetDatabase() { + Runnable deleteRunnable = new Runnable() { + @Override + public void run() { + appSettingDao.deleteTableRows(); + locationDao.deleteTableRows(); + packingDao.deleteFullPackingList(); + userMedicineDao.deleteTableRows(); + } + }; + appExecutors.diskIO().execute(deleteRunnable); + } + + /** + * Inserting the location for maintaining Location History + **/ + @Override + public void insertLocation(final String location) { + final int[] a = {0}; + final int[] flag = {0}; + Runnable runnable = new Runnable() { + @Override + public void run() { + List locations = locationDao.getLocationListByLocation(location); + for (Location l : locations) { + a[0] = l.getTime(); + a[0]++; + flag[0] = 1; + } + if (flag[0] == 1) { + locationDao.updateLocation(a[0], location); + } else { + Location insertLocation = new Location(location, a[0]); + locationDao.insertLocation(insertLocation); + } + + } + }; + appExecutors.diskIO().execute(runnable); + } + + /** + * Fetching the Location + **/ + @Override + public void getLocation(final loadListStringCallBack callback) { + Runnable locationRunnable = new Runnable() { + @Override + public void run() { + final List locations = locationDao.getLocationList(); + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(locations); + } + }); + } + }; + appExecutors.diskIO().execute(locationRunnable); + } + + /** + * Inserting the Packing Item in DataBase when using Add Item Edit Text + **/ + @Override + public void insertPackingItem(final String pItem, final int quantity, final boolean status) { + Runnable runnable = new Runnable() { + @Override + public void run() { + List intList = packingDao.getPackingQuantityList(pItem); + if (intList.size() > 0) { + packingDao.updatePacking(pItem, quantity, status); + } else { + packingDao.insertPacking(new Packing(pItem, quantity, status)); + } + } + }; + appExecutors.diskIO().execute(runnable); + } + + /** + * Fetching the Packing Item to be taken + **/ + @Override + public void getPackingItemChecked(final LoadListPackingCallback callback) { + Runnable packingRunnable = new Runnable() { + @Override + public void run() { + final List packings = packingDao.getPackingItemChecked(true); + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(packings); + } + }); + } + }; + appExecutors.diskIO().execute(packingRunnable); + } + + /** + * Fetching the list of Packing Item from which one can be chosen + **/ + @Override + public void getPackingItem(final LoadListPackingCallback callback) { + Runnable packingRunnable = new Runnable() { + @Override + public void run() { + final List packings = packingDao.getPackingItem(); + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(packings); + } + }); + } + }; + appExecutors.diskIO().execute(packingRunnable); + } + + /** + * Refreshing the status of each packing item to its original state + **/ + @Override + public void refreshPackingItemStatus() { + Runnable runnable = new Runnable() { + @Override + public void run() { + packingDao.refreshPackingItemStatus(true); + } + }; + appExecutors.diskIO().execute(runnable); + } + + /** + * @param id : deletes packing row where id is the row number + */ + @Override + public void deletePackingById(final int id) { + Runnable runnable = new Runnable() { + @Override + public void run() { + packingDao.deletePackingById(id); + ToastLogSnackBarUtil.showDebugLog("deleting sqlite row " + id); + } + }; + appExecutors.diskIO().execute(runnable); + } + + /** + * @param status : defines the packing status, defined by checkbox status + * @param position : defines the row position in table + */ + @Override + public void updatePackingStatus(final boolean status, final int position) { + Runnable runnable = new Runnable() { + @Override + public void run() { + ToastLogSnackBarUtil.showDebugLog("update pos status " + position); + packingDao.updatePackingStatus(status, position); + } + }; + appExecutors.diskIO().execute(runnable); + } + + /** + * @param callback : passes integer/size of the packing list using onDataLoaded(size) + */ + @Override + public void getPackingListSize(final LoadIntegerCallback callback) { + Runnable runnable = new Runnable() { + @Override + public void run() { + final int size = packingDao.getPackingListSize(); + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(size); + } + }); + } + }; + appExecutors.diskIO().execute(runnable); + } + + @Override + public void updateMedicinePacking(final String name, final int quantity) { + Runnable runnable = new Runnable() { + @Override + public void run() { + packingDao.updateMedicinePacking(name, quantity, false); + } + }; + appExecutors.diskIO().execute(runnable); + } + + @Override + public void getPackedMedDetails(final LoadPackingCallback callback) { + Runnable runnable = new Runnable() { + @Override + public void run() { + final Packing packing = packingDao.getPackedMedicine(); + if (packing != null) { + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(packing); + } + }); + } else { + ToastLogSnackBarUtil.showErrorLog("AppDbHelper/getPackedMedDetails: No packing exist"); + } + + } + }; + appExecutors.diskIO().execute(runnable); + } + + /** + * Finding the Last Date the Drug was taken + **/ + @Override + public void getLastTaken(final LoadStringCallback callback) { + Runnable runnable = new Runnable() { + @Override + public void run() { + final List medicines = userMedicineDao.getLastTaken("yes"); + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + if (medicines.size() > 0) + callback.onDataLoaded(medicines.get(medicines.size() - 1)); + } + }); + } + }; + appExecutors.diskIO().execute(runnable); + } + + /** + * Finding the No. of Drugs + **/ + @Override + public void getMedicineCountTaken(final LoadIntegerCallback callback) { + Runnable runnable = new Runnable() { + @Override + public void run() { + final int count = userMedicineDao.getCountTaken("yes"); + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(count); + } + }); + } + }; + appExecutors.diskIO().execute(runnable); + } + + /** + * Finding the Drugs between two dates for updating Adherence in Day Fragment Activity of any selected date + **/ + @Override + public void getCountTakenBetween(final Date s, final Date e, final LoadIntegerCallback callback) { + Runnable runnable = new Runnable() { + @Override + public void run() { + List timeStampList = userMedicineDao.getLastTaken("yes"); + int count = 0; + for (String time : timeStampList) { + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()); + Date curr = Calendar.getInstance().getTime(); + try { + curr = sdf.parse(time); + } catch (ParseException e1) { + ToastLogSnackBarUtil.showErrorLog("AppDbHelper/getCountTakenBetween: Parse Exception " + time); + } + long currt = curr.getTime(); + long endt = e.getTime(); + + Calendar cal = Calendar.getInstance(); + cal.setTime(s); + cal.add(Calendar.MONTH, 1); + Date p = cal.getTime(); + long strt = p.getTime(); + + Log.d("AppDbHelper", "Current Long:" + currt); + Log.d("AppDbHelper", "End Long:" + endt); + Log.d("AppDbHelper", "Start Long:" + strt); + if (currt >= strt && currt <= endt) { + count++; + } else if (strt == endt) { + count++; + } + } + final int finalCount = count; + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(finalCount); + } + }); + } + }; + appExecutors.diskIO().execute(runnable); + + } + + @Override + public void getAlarmData(final LoadAlarmDataCallback callback) { + Runnable runnable = new Runnable() { + @Override + public void run() { + final AlarmTime time = alarmDao.getAlarmData(); + appExecutors.mainThread().execute(new Runnable() { + @Override + public void run() { + callback.onDataLoaded(time); + } + }); + } + }; + appExecutors.diskIO().execute(runnable); + } + + @Override + public void insertAlarmData(final AlarmTime time) { + Runnable runnable = new Runnable() { + @Override + public void run() { + alarmDao.insertAlarmData(time); + } + }; + appExecutors.diskIO().execute(runnable); + + } + + @Override + public void updateAlarmTime(final int hour, final int min) { + Runnable runnable = new Runnable() { + @Override + public void run() { + alarmDao.updateTime(hour, min); + } + }; + appExecutors.diskIO().execute(runnable); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/DbHelper.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/DbHelper.java new file mode 100644 index 00000000..b17f155f --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/DbHelper.java @@ -0,0 +1,99 @@ +package com.peacecorps.malaria.data.db; + +import com.peacecorps.malaria.data.db.entities.AlarmTime; +import com.peacecorps.malaria.data.db.entities.Location; +import com.peacecorps.malaria.data.db.entities.Packing; + +import java.util.Date; +import java.util.List; + +public interface DbHelper { + interface LoadIntegerCallback { + void onDataLoaded(int value); + } + + interface LoadStringCallback { + void onDataLoaded(String data); + } + + interface loadListStringCallBack { + void onDataLoaded(List data); + } + + interface LoadLongCallback { + void onDataLoaded(Long value); + } + + interface LoadListLocationCallback { + void onDataLoaded(List locations); + } + + interface LoadListPackingCallback { + void onDataLoaded(List packingList); + } + + interface LoadPackingCallback { + void onDataLoaded(Packing packing); + } + interface LoadAlarmDataCallback { + void onDataLoaded(AlarmTime time); + } + + void getCountForProgressBar( int month, int year, String status, String choice, LoadIntegerCallback callback); + + void setUserMedicineSelection(String drug, String choice, Date date, String status, Double percentage); + + void insertAppSettings(String drug, String choice, long date); + + void getMedicationData(int date, int month, int year, LoadStringCallback callback); + + void updateMedicationEntry(int date, int month, int year, String entry,double percentage); + + void insertOrUpdateMissedMedicationEntry(String drug, String ch, int date, int month, int year,double percentage); + + void isEntered(int date,int month, int year, LoadIntegerCallback callback); + + void getFirstTimeByTimeStamp(LoadLongCallback callback); + + void getDailyStatus(int date,int month,int year, LoadStringCallback callback); + + void getDosesInaRowWeekly(LoadIntegerCallback callback); + + void getDosesInaRowDaily(LoadIntegerCallback callback); + + void resetDatabase(); + + void insertLocation(String location); + + void getLocation(loadListStringCallBack callback); + + void insertPackingItem(String pItem,int quantity, boolean status); + + void getPackingItemChecked(LoadListPackingCallback callback); + + void getPackingItem(LoadListPackingCallback callback); + + void refreshPackingItemStatus(); + + void deletePackingById(int id); + + void updatePackingStatus(boolean status, int position); + + void getPackingListSize(LoadIntegerCallback callback); + + void updateMedicinePacking(String name, int quantity); + + void getPackedMedDetails(LoadPackingCallback callback); + + void getLastTaken(LoadStringCallback callback); + + void getMedicineCountTaken(LoadIntegerCallback callback); + + void getCountTakenBetween(Date s,Date e, LoadIntegerCallback callback); + + void getAlarmData(LoadAlarmDataCallback callback); + + void insertAlarmData(AlarmTime time); + + void updateAlarmTime(int hour, int min); +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/AlarmDao.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/AlarmDao.java new file mode 100644 index 00000000..df7409fc --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/AlarmDao.java @@ -0,0 +1,19 @@ +package com.peacecorps.malaria.data.db.dao; + +import android.arch.persistence.room.Dao; +import android.arch.persistence.room.Insert; +import android.arch.persistence.room.Query; + +import com.peacecorps.malaria.data.db.entities.AlarmTime; + +@Dao +public interface AlarmDao { + @Insert + void insertAlarmData(AlarmTime data); + + @Query("SELECT * FROM alarmtime WHERE id = 1") + AlarmTime getAlarmData(); + + @Query("UPDATE alarmtime SET hour= :hour , minute= :minute") + void updateTime(int hour, int minute); +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/AppSettingDao.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/AppSettingDao.java new file mode 100644 index 00000000..f4eb4156 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/AppSettingDao.java @@ -0,0 +1,25 @@ +package com.peacecorps.malaria.data.db.dao; + +import android.arch.persistence.room.Dao; +import android.arch.persistence.room.Insert; +import android.arch.persistence.room.Query; + +import com.peacecorps.malaria.data.db.entities.AppSetting; + +@Dao +public interface AppSettingDao { + + @Insert + void insertAppSettings(AppSetting appSetting); + + @Query("SELECT freshInstall FROM AppSetting ORDER BY appSettingId ASC LIMIT 1") + String checkFirstInstall(); + + @Query("DELETE FROM AppSetting WHERE appSettingId = 1") + void deleteFirstRow(); + + @Query("DELETE FROM UserMedicine") + void deleteTableRows(); + + +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/LocationDao.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/LocationDao.java new file mode 100644 index 00000000..49dc8c2f --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/LocationDao.java @@ -0,0 +1,28 @@ +package com.peacecorps.malaria.data.db.dao; + +import android.arch.persistence.room.Dao; +import android.arch.persistence.room.Insert; +import android.arch.persistence.room.Query; + +import com.peacecorps.malaria.data.db.entities.Location; + +import java.util.List; + +@Dao +public interface LocationDao { + + @Insert + void insertLocation(Location location); + + @Query("SELECT * FROM Location WHERE locationName= :location") + List getLocationListByLocation(String location); + + @Query("SELECT locationName FROM Location ORDER BY locationId ASC") + List getLocationList(); + + @Query("UPDATE Location SET time= :a WHERE locationName= :location ") + void updateLocation(int a, String location); + + @Query("DELETE FROM Location") + void deleteTableRows(); +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/PackingDao.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/PackingDao.java new file mode 100644 index 00000000..97b8ba24 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/PackingDao.java @@ -0,0 +1,49 @@ +package com.peacecorps.malaria.data.db.dao; + +import android.arch.persistence.room.Dao; +import android.arch.persistence.room.Insert; +import android.arch.persistence.room.Query; + +import com.peacecorps.malaria.data.db.entities.Packing; + +import java.util.List; + +@Dao +public interface PackingDao { + + @Query("DELETE FROM packing_settings") + void deleteFullPackingList(); + + @Query("SELECT packingQuantity FROM packing_settings WHERE packingItem= :item") + List getPackingQuantityList(String item); + + @Query("UPDATE packing_settings SET packingItem= :pItem , packingQuantity= :quantity, packingStatus= :status WHERE packingItem= :pItem") + void updatePacking(String pItem, int quantity, boolean status); + + @Insert + void insertPacking(Packing packing); + + @Query("SELECT * FROM PACKING_SETTINGS WHERE packingStatus= :status ORDER BY packingId ASC") + List getPackingItemChecked(boolean status); + + @Query("SELECT * FROM PACKING_SETTINGS ORDER BY packingId ASC") + List getPackingItem(); + + @Query("UPDATE packing_settings SET packingStatus= :status") + void refreshPackingItemStatus(boolean status); + + @Query("DELETE FROM packing_settings WHERE packingId = :id") + void deletePackingById(int id); + + @Query("UPDATE packing_settings SET packingStatus= :status WHERE packingId= :position") + void updatePackingStatus(boolean status, int position); + + @Query("SELECT Count(*) FROM packing_settings") + int getPackingListSize(); + + @Query("UPDATE packing_settings SET packingItem= :name , packingQuantity= :quantity, packingStatus= :status WHERE packingId= 1") + void updateMedicinePacking(String name, int quantity, boolean status); + + @Query("SELECT * FROM packing_settings WHERE packingId = 1") + Packing getPackedMedicine(); +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/UserMedicineDao.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/UserMedicineDao.java new file mode 100644 index 00000000..2d704a2e --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/dao/UserMedicineDao.java @@ -0,0 +1,55 @@ +package com.peacecorps.malaria.data.db.dao; + +import android.arch.persistence.room.Dao; +import android.arch.persistence.room.Insert; +import android.arch.persistence.room.Query; + +import com.peacecorps.malaria.data.db.entities.UserMedicine; + +import java.util.List; + +@Dao +public interface UserMedicineDao { + + @Query("SELECT * FROM UserMedicine ORDER BY timeStamp ASC") + List getUserMedicineChoiceByTimeAsc(); + + @Query("SELECT COUNT(*) FROM usermedicine WHERE month= :month and year = :year and status = :status and choice= :choice") + int getDataForProgressBar(int month, int year, String status, String choice); + + @Insert + void setUserMedicineSelection(UserMedicine userMedicine); + + @Query("SELECT * FROM UserMedicine WHERE month= :month and year= :year and choice= :choice") + List getMedicationData(String choice,int month, int year); + + @Query("UPDATE UserMedicine SET status = :entry and percentage = :percentage WHERE month= :month and year= :year and date= :date") + void updateMedicationEntry(int date, int month, int year, String entry,double percentage); + + @Query("SELECT status FROM usermedicine WHERE date= :date and month= :month and year= :year") + String isEntered(int date,int month, int year); + + @Query("SELECT timeStamp FROM usermedicine ORDER BY Timestamp ASC LIMIT 1") + String getFirstTimeTimeStamp(); + + @Query("SELECT status FROM usermedicine WHERE date= :date and month= :month and year= :year") + String getDailyStatus(int date,int month,int year); + + @Query("SELECT * FROM UserMedicine ORDER BY timeStamp DESC") + List getDosesInaRow(); + + @Query("DELETE FROM UserMedicine") + void deleteTableRows(); + + @Query("SELECT timeStamp FROM UserMedicine WHERE status= :status ORDER BY timeStamp ASC") + List getLastTaken(String status); + + @Query("SELECT COUNT(*) FROM UserMedicine WHERE status= :status") + int getCountTaken(String status); + + @Query("SELECT status FROM UserMedicine WHERE date= :date and month= :month and year= :year") + List getStatusListByDateMonthYear (int date, int month, int year); + + @Query("SELECT date FROM UserMedicine WHERE month= :month and year= :year ORDER BY date ASC") + List getDateListByMonthYear(int month, int year); +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/AlarmTime.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/AlarmTime.java new file mode 100644 index 00000000..03f6c5fc --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/AlarmTime.java @@ -0,0 +1,71 @@ +package com.peacecorps.malaria.data.db.entities; + +import android.arch.persistence.room.Entity; +import android.arch.persistence.room.PrimaryKey; + +@Entity +public class AlarmTime { + @PrimaryKey(autoGenerate = true) + private int id; + private int hour; + private int minute; + private int month; + private int year; + private int checkDay; + + public AlarmTime(int hour, int minute, int month, int year, int checkDay) { + this.hour = hour; + this.minute = minute; + this.month = month; + this.year = year; + this.checkDay = checkDay; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getHour() { + return hour; + } + + public void setHour(int hour) { + this.hour = hour; + } + + public int getMinute() { + return minute; + } + + public void setMinute(int minute) { + this.minute = minute; + } + + public int getMonth() { + return month; + } + + public void setMonth(int month) { + this.month = month; + } + + public int getYear() { + return year; + } + + public void setYear(int year) { + this.year = year; + } + + public int getCheckDay() { + return checkDay; + } + + public void setCheckDay(int checkDay) { + this.checkDay = checkDay; + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/AppSetting.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/AppSetting.java new file mode 100644 index 00000000..682fcee2 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/AppSetting.java @@ -0,0 +1,71 @@ +package com.peacecorps.malaria.data.db.entities; + +import android.arch.persistence.room.Entity; +import android.arch.persistence.room.PrimaryKey; + +@Entity +public class AppSetting { + @PrimaryKey(autoGenerate = true) + private int appSettingId; + private String drugName; + private String choice; + private int weeklyDay; + private long firstTime; + private String freshInstall; + + public AppSetting(String drugName, String choice, int weeklyDay, long firstTime, String freshInstall) { + this.drugName = drugName; + this.choice = choice; + this.weeklyDay = weeklyDay; + this.firstTime = firstTime; + this.freshInstall = freshInstall; + } + + public int getAppSettingId() { + return appSettingId; + } + + public void setAppSettingId(int appSettingId) { + this.appSettingId = appSettingId; + } + + public String getDrugName() { + return drugName; + } + + public void setDrugName(String drugName) { + this.drugName = drugName; + } + + public String getChoice() { + return choice; + } + + public void setChoice(String choice) { + this.choice = choice; + } + + public int getWeeklyDay() { + return weeklyDay; + } + + public void setWeeklyDay(int weeklyDay) { + this.weeklyDay = weeklyDay; + } + + public long getFirstTime() { + return firstTime; + } + + public void setFirstTime(long firstTime) { + this.firstTime = firstTime; + } + + public String getFreshInstall() { + return freshInstall; + } + + public void setFreshInstall(String freshInstall) { + this.freshInstall = freshInstall; + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/Location.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/Location.java new file mode 100644 index 00000000..10dc9fad --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/Location.java @@ -0,0 +1,44 @@ +package com.peacecorps.malaria.data.db.entities; + +import android.arch.persistence.room.Entity; +import android.arch.persistence.room.PrimaryKey; + +@Entity +public class Location { + + @PrimaryKey(autoGenerate = true) + private int locationId; + + private String locationName; + + private int time; + + public Location(String locationName, int time) { + this.locationName = locationName; + this.time = time; + } + + public int getLocationId() { + return locationId; + } + + public void setLocationId(int locationId) { + this.locationId = locationId; + } + + public String getLocationName() { + return locationName; + } + + public void setLocationName(String locationName) { + this.locationName = locationName; + } + + public int getTime() { + return time; + } + + public void setTime(int time) { + this.time = time; + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/Packing.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/Packing.java new file mode 100644 index 00000000..f6f17158 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/Packing.java @@ -0,0 +1,51 @@ +package com.peacecorps.malaria.data.db.entities; + +import android.arch.persistence.room.Entity; +import android.arch.persistence.room.PrimaryKey; + +@Entity(tableName = "packing_settings") +public class Packing { + @PrimaryKey(autoGenerate = true) + private int packingId; + private String packingItem; + private int packingQuantity; + private boolean packingStatus; + + public Packing(String packingItem, int packingQuantity, boolean packingStatus) { + this.packingItem = packingItem; + this.packingQuantity = packingQuantity; + this.packingStatus = packingStatus; + } + + public int getPackingId() { + return packingId; + } + + public void setPackingId(int packingId) { + this.packingId = packingId; + } + + public String getPackingItem() { + return packingItem; + } + + public void setPackingItem(String packingItem) { + this.packingItem = packingItem; + } + + public int getPackingQuantity() { + return packingQuantity; + } + + public void setPackingQuantity(int packingQuantity) { + this.packingQuantity = packingQuantity; + } + + public boolean getPackingStatus() { + return packingStatus; + } + + public void setPackingStatus(boolean packingStatus) { + this.packingStatus = packingStatus; + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/UserMedicine.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/UserMedicine.java new file mode 100644 index 00000000..c39b2e36 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/db/entities/UserMedicine.java @@ -0,0 +1,98 @@ +package com.peacecorps.malaria.data.db.entities; + +import android.arch.persistence.room.Entity; +import android.arch.persistence.room.PrimaryKey; + +@Entity +public class UserMedicine { + @PrimaryKey(autoGenerate = true) + private int userMedicineId; + private String drug; + private String choice; + private int month; + private int year; + private int date; + private String status; + private double percentage; + private String timeStamp; + + public UserMedicine(String drug, String choice, int month, int year, int date, String status, + double percentage, String timeStamp) { + this.drug = drug; + this.choice = choice; + this.month = month; + this.year = year; + this.date = date; + this.status = status; + this.percentage = percentage; + this.timeStamp = timeStamp; + } + + public int getUserMedicineId() { + return userMedicineId; + } + + public void setUserMedicineId(int userMedicineId) { + this.userMedicineId = userMedicineId; + } + + public int getDate() { + return date; + } + + public void setDate(int date) { + this.date = date; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public double getPercentage() { + return percentage; + } + + public void setPercentage(double percentage) { + this.percentage = percentage; + } + + public String getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(String timeStamp) { + this.timeStamp = timeStamp; + } + + public String getDrug() { + return drug; + } + + public void setDrug(String drug) { + this.drug = drug; + } + + public String getChoice() { + return choice; + } + + public void setChoice(String choice) { + this.choice = choice; + } + + public int getMonth() { + return month; + } + + public void setMonth(int month) { + this.month = month; + } + + public int getYear() { + return year; + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/prefs/AppPreferencesHelper.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/prefs/AppPreferencesHelper.java new file mode 100644 index 00000000..69a8fb6d --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/prefs/AppPreferencesHelper.java @@ -0,0 +1,335 @@ +package com.peacecorps.malaria.data.prefs; + +import android.content.Context; +import android.content.SharedPreferences; + +public class AppPreferencesHelper implements PreferencesHelper{ + + private static final String PREF_KEY_USER_PREFERENCES = "HAS_USER_SET_PREFERENCES"; + private static final String PREF_KEY_USER_SCORE = "USER_SCORE"; + private static final String PREF_KEY_GAME_SCORE = "GAME_SCORE"; + private static final String PREF_KEY_DRUG_PICKED = "com_peacecorps_malaria_drugPicked"; + private static final String PREF_KEY_FIRST_RUN_TIME = "com_peacecorps_malaria_firstRunTime"; + private static final String PREF_KEY_DRUG_ACCEPTED_COUNTED = "com_peacecorps_malaria_drugAcceptedCount"; + private static final String PREF_KEY_DRUG_REJECTED_COUNT = "com.peacecorps.malaria.isRejected"; + private static final String PREF_KEY_MEDICINE_STORE = "MEDICINE_STORE"; + private static final String PREF_KEY_MEDICINE_LAST_TAKEN_TIME = "check_medicine_last_taken_time"; + private static final String PREF_KEY_TONE_URI = "TONE_URI"; + private static final String PREF_KEY_TRIP_DATE = "com_peacecorps_malaria_trip_date"; + private static final String PREF_KEY_TRIP_LOCATION = "TRIP_LOCATION"; + private static final String PREF_KEY_USER_NAME = "USER_NAME"; + private static final String PREF_KEY_USER_EMAIL = "USER_EMAIL"; + private static final String PREF_KEY_USER_AGE = "USER_AGE"; + private static final String PREF_KEY_IS_FIRST_RUN = "IS_FIRST_RUN"; + private static final String PREF_KEY_ALERT_TIME = "NUMBER_ALERT_TIME"; + private static final String PREF_KEY_TRIP_REMINDER = "view_upcoming_reminder"; + + private static final String PREF_KEY_WEEKLY_DATE = "com.peacecorps.malaria.weekly_date"; + private static final String PREF_KEY_IS_WEEKLY_DRUG_TAKEN = "com.peacecorps.malaria.isWeeklyDrugTaken"; + private static final String PREF_KEY_DOSES_WEEKLY = "com_peacecorps_malaria_weekly_dose"; + private static final String PREF_KEY_IS_WEEKLY = "com_peacecorps_malaria_isWeekly"; + private static final String PREF_KEY_WEEKLY_DAY = "com_peacecorps_malaria_weeklyDay"; + private static final String PREF_KEY_DOSES_DAILY = "com_peacecorps_malaria_daily_dose"; + private static final String PREF_KEY_IS_DAILY_DRUG_TAKEN = "com.peacecorps.malaria.isDailyDrugTaken"; + private static final String PREF_KEY_DAILY_DRUG_DATE = "com_peacecorps_malaria_date_drug_taken"; + private static final String PREF_KEY_IS_DRUG_TAKEN = "com_peacecorps_malaria_is_drug_taken"; + private static final String PREF_KEY_RAPID_FIRE_TARGET = "rapid_fire_game"; + private static final String PREF_KEY_MYTH_FACT_TARGET = "myth_fact_game"; + + + + private final SharedPreferences mPrefs; + + public AppPreferencesHelper(Context context, String prefFileName) { + mPrefs = context.getSharedPreferences(prefFileName, Context.MODE_PRIVATE); + } + @Override + public boolean hasUserSetPreferences() { + return mPrefs.getBoolean(PREF_KEY_USER_PREFERENCES,false); + } + + @Override + public void setUserPreferences(boolean value) { + mPrefs.edit().putBoolean(PREF_KEY_USER_PREFERENCES,value).apply(); + } + + @Override + public int getUserScore() { + return mPrefs.getInt(PREF_KEY_USER_SCORE, 0); + } + + @Override + public void setUserScore(int score) { + mPrefs.edit().putInt(PREF_KEY_USER_SCORE, score).apply(); + } + + @Override + public int getGameScore() { + return mPrefs.getInt(PREF_KEY_GAME_SCORE, 0); + } + + @Override + public void setGameScore(int score) { + mPrefs.edit().putInt(PREF_KEY_GAME_SCORE, score).apply(); + } + + @Override + public String getDrugPicked() { + return mPrefs.getString(PREF_KEY_DRUG_PICKED,""); + } + + @Override + public void setDrugPicked(String drug) { + mPrefs.edit().putString(PREF_KEY_DRUG_PICKED, drug).apply(); + } + + @Override + public long getFirstRunTime() { + return mPrefs.getLong(PREF_KEY_FIRST_RUN_TIME, 0 ); + } + + @Override + public void setFirstRunTime(long value) { + mPrefs.edit().putLong(PREF_KEY_FIRST_RUN_TIME, value).apply(); + } + + @Override + public int getDrugAcceptedCount() { + return mPrefs.getInt(PREF_KEY_DRUG_ACCEPTED_COUNTED, 0); + } + + @Override + public void setDrugAcceptedCount(int value) { + mPrefs.edit().putInt(PREF_KEY_DRUG_ACCEPTED_COUNTED, value).apply(); + } + + @Override + public boolean isDosesWeekly() { + return mPrefs.getBoolean(PREF_KEY_IS_WEEKLY, false); + } + + @Override + public void setDoseWeekly(boolean value) { + mPrefs.edit().putBoolean(PREF_KEY_IS_WEEKLY, value).apply(); + } + + @Override + public int checkDosesDaily() { + return mPrefs.getInt(PREF_KEY_DOSES_DAILY, 0); + } + + @Override + public int getDayWeekly() { + return mPrefs.getInt(PREF_KEY_WEEKLY_DAY,1); + } + + @Override + public void setDosesDaily(int value) { + mPrefs.edit().putInt(PREF_KEY_DOSES_DAILY, value).apply(); + } + + @Override + public void setDayWeekly(int value) { + mPrefs.edit().putInt(PREF_KEY_WEEKLY_DAY,value).apply(); + } + + @Override + public int checkDosesWeekly() { + return mPrefs.getInt(PREF_KEY_DOSES_WEEKLY, 0); + } + + @Override + public void setDosesWeekly(int value) { + mPrefs.edit().putInt(PREF_KEY_DOSES_WEEKLY, value).apply(); + } + + @Override + public int getMedicineStoreValue() { + return mPrefs.getInt(PREF_KEY_MEDICINE_STORE, 0); + } + + @Override + public void setMedicineStoreValue(int value) { + mPrefs.edit().putInt(PREF_KEY_MEDICINE_STORE, value).apply(); + } + + @Override + public String getMedicineLastTakenTime() { + return mPrefs.getString(PREF_KEY_MEDICINE_LAST_TAKEN_TIME, ""); + } + + @Override + public void setMedicineLastTakenTime(String time) { + mPrefs.edit().putString(PREF_KEY_MEDICINE_LAST_TAKEN_TIME, time).apply(); + } + + @Override + public String getToneUri() { + return mPrefs.getString(PREF_KEY_TONE_URI, ""); + } + + @Override + public void setToneUri(String uri) { + mPrefs.edit().putString(PREF_KEY_TONE_URI, uri).apply(); + } + + @Override + public String getTripDate() { + return mPrefs.getString(PREF_KEY_TRIP_DATE, null); + } + + @Override + public void setTripDate(String date) { + mPrefs.edit().putString(PREF_KEY_TRIP_DATE, date).apply(); + } + + @Override + public String getTripLocation() { + return mPrefs.getString(PREF_KEY_TRIP_LOCATION, ""); + } + + @Override + public void setTripLocation(String location) { + mPrefs.edit().putString(PREF_KEY_TRIP_LOCATION, location).apply(); + } + + @Override + public String getUserName() { + return mPrefs.getString(PREF_KEY_USER_NAME, ""); + } + + @Override + public String getUserEmail() { + return mPrefs.getString(PREF_KEY_USER_EMAIL, ""); + } + + @Override + public int getUserAge() { + return mPrefs.getInt(PREF_KEY_USER_AGE, 0); + } + + @Override + public void setUserName(String name) { + mPrefs.edit().putString(PREF_KEY_USER_NAME, name).apply(); + } + + @Override + public void setUserEmail(String email) { + mPrefs.edit().putString(PREF_KEY_USER_EMAIL, email).apply(); + } + + @Override + public void setUserAge(int age) { + mPrefs.edit().putInt(PREF_KEY_USER_AGE, age).apply(); + } + + @Override + public boolean isFirstRun() { + return mPrefs.getBoolean(PREF_KEY_IS_FIRST_RUN, true); + } + + @Override + public void setFirstRun(boolean val) { + mPrefs.edit().putBoolean(PREF_KEY_IS_FIRST_RUN, val).apply(); + } + + @Override + public boolean isDrugTaken() { + return mPrefs.getBoolean(PREF_KEY_IS_DRUG_TAKEN, false); + } + + @Override + public void setDrugTaken(boolean value) { + mPrefs.edit().putBoolean(PREF_KEY_IS_DRUG_TAKEN, value).apply(); + } + + @Override + public int getAlertNumberDaysOrWeeks() { + return mPrefs.getInt(PREF_KEY_ALERT_TIME, -1); + } + + @Override + public void setAlertNumberDaysOrWeeks(int value) { + mPrefs.edit().putInt(PREF_KEY_ALERT_TIME, value).apply(); + } + + @Override + public String getReminderMessageForTrip() { + return mPrefs.getString(PREF_KEY_TRIP_REMINDER, ""); + } + + @Override + public void setReminderMessageForTrip(String messageForTrip) { + mPrefs.edit().putString(PREF_KEY_TRIP_REMINDER, messageForTrip).apply(); + } + + @Override + public void setLongWeeklyDate(long value) { + mPrefs.edit().putLong(PREF_KEY_WEEKLY_DATE, value).apply(); + } + + @Override + public long getLongWeeklyDate() { + return mPrefs.getLong(PREF_KEY_WEEKLY_DATE, 0); + } + + @Override + public void setDateDrugTaken(long value) { + mPrefs.edit().putLong(PREF_KEY_DAILY_DRUG_DATE, value).apply(); + } + + @Override + public long getDateDrug() { + return mPrefs.getLong(PREF_KEY_DAILY_DRUG_DATE, 0); + } + + @Override + public void setWeeklyDrugTaken(boolean value) { + mPrefs.edit().putBoolean(PREF_KEY_IS_WEEKLY_DRUG_TAKEN, value).apply(); + } + + @Override + public boolean isWeeklyDrugTaken() { + return mPrefs.getBoolean(PREF_KEY_IS_WEEKLY_DRUG_TAKEN, false); + } + + @Override + public boolean isDailyDrugTaken() { + return mPrefs.getBoolean(PREF_KEY_IS_DAILY_DRUG_TAKEN, false); + } + + @Override + public void setDailyDrugTaken(boolean value) { + mPrefs.edit().putBoolean(PREF_KEY_IS_DAILY_DRUG_TAKEN, value).apply(); + } + + @Override + public int getDrugRejectedCount() { + return mPrefs.getInt(PREF_KEY_DRUG_REJECTED_COUNT, 0); + } + + @Override + public void setDrugRejectedCount(int value) { + mPrefs.edit().putInt(PREF_KEY_DRUG_REJECTED_COUNT, value).apply(); + } + + @Override + public boolean checkRapidFireTarget() { + return mPrefs.getBoolean(PREF_KEY_RAPID_FIRE_TARGET, false); + } + + @Override + public void setRapidFireTarget(boolean value) { + mPrefs.edit().putBoolean(PREF_KEY_RAPID_FIRE_TARGET, value).apply(); + } + + @Override + public boolean checkMythFactTarget() { + return mPrefs.getBoolean(PREF_KEY_MYTH_FACT_TARGET, false); + } + + @Override + public void setMythFactTarget(boolean value) { + mPrefs.edit().putBoolean(PREF_KEY_MYTH_FACT_TARGET, value).apply(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/data/prefs/PreferencesHelper.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/prefs/PreferencesHelper.java new file mode 100644 index 00000000..f4bddc68 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/data/prefs/PreferencesHelper.java @@ -0,0 +1,62 @@ +package com.peacecorps.malaria.data.prefs; + +public interface PreferencesHelper { + boolean hasUserSetPreferences(); + void setUserPreferences(boolean value); + int getUserScore(); + void setUserScore(int score); + int getGameScore(); + void setGameScore(int score); + String getDrugPicked(); + void setDrugPicked(String drug); + long getFirstRunTime(); + void setFirstRunTime(long value); + int getDrugAcceptedCount(); + void setDrugAcceptedCount(int value); + boolean isDosesWeekly(); + void setDoseWeekly(boolean value); + int checkDosesDaily(); + int getDayWeekly(); + void setDosesDaily(int value); + void setDayWeekly(int value); + int checkDosesWeekly(); + void setDosesWeekly(int value); + int getMedicineStoreValue(); + void setMedicineStoreValue(int value); + String getMedicineLastTakenTime(); + void setMedicineLastTakenTime(String time); + String getToneUri(); + void setToneUri(String uri); + String getTripDate(); + void setTripDate(String date); + String getTripLocation(); + void setTripLocation(String location); + String getUserName(); + String getUserEmail(); + int getUserAge(); + void setUserName(String name); + void setUserEmail(String email); + void setUserAge(int age); + boolean isFirstRun(); + void setFirstRun(boolean val); + boolean isDrugTaken(); + void setDrugTaken(boolean value); + int getAlertNumberDaysOrWeeks(); + void setAlertNumberDaysOrWeeks(int value); + String getReminderMessageForTrip(); + void setReminderMessageForTrip(String messageForTrip); + void setLongWeeklyDate(long value); + long getLongWeeklyDate(); + void setDateDrugTaken(long value); + long getDateDrug(); + void setWeeklyDrugTaken(boolean value); + boolean isWeeklyDrugTaken(); + void setDailyDrugTaken(boolean value); + boolean isDailyDrugTaken(); + int getDrugRejectedCount(); + void setDrugRejectedCount(int value); + boolean checkRapidFireTarget(); + void setRapidFireTarget(boolean value); + boolean checkMythFactTarget(); + void setMythFactTarget(boolean value); +} diff --git a/src/com/peacecorps/malaria/DatabaseSQLiteHelper.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/db/DatabaseSQLiteHelper.java similarity index 81% rename from src/com/peacecorps/malaria/DatabaseSQLiteHelper.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/db/DatabaseSQLiteHelper.java index cdc99eef..944af60b 100644 --- a/src/com/peacecorps/malaria/DatabaseSQLiteHelper.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/db/DatabaseSQLiteHelper.java @@ -1,4 +1,4 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.db; import android.content.ContentValues; import android.content.Context; @@ -8,38 +8,44 @@ import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; -import java.text.ParseException; +import com.peacecorps.malaria.code.model.SharedPreferenceStore; +import com.peacecorps.malaria.utils.CalendarFunction; + import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; +import static com.peacecorps.malaria.utils.CalendarFunction.getDateObject; +import static com.peacecorps.malaria.utils.CalendarFunction.getHumanDateFormat; + /** * Created by Chimdi on 7/18/14. * Edited by Ankita **/ public class DatabaseSQLiteHelper extends SQLiteOpenHelper { + // database name and table names private static final String DATABASE_NAME = "MalariaDatabase"; private static final String userMedicationChoiceTable = "userSettings"; private static final String appSettingTable = "appSettings"; private static final String locationTable = "locationSettings"; private static final String packingTable = "packingSettings"; + + // tag private static final String TAGDSH= "DatabaseSQLiteHelper"; + public static final String LOCATION = "Location"; public static final String PACKING_ITEM = "PackingItem"; public static final String KEY_ROW_ID = "_id"; public static final String QUANTITY = "Quantity"; - private final int[] daysOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, - 31, 30, 31 }; - private final int[] daysOfMonthLeap = { 31, 29, 31, 30, 31, 30, 31, 31, 30, - 31, 30, 31 }; - + // constructor public DatabaseSQLiteHelper(Context context) { super(context, DATABASE_NAME, null, 1); } + // creating tables @Override public void onCreate(SQLiteDatabase database) { /**Creating Tables**/ @@ -59,6 +65,7 @@ public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { public static ArrayList date; /**Method to Update the Progress Bars**/ + // only returning count value public int getData(int month, int year, String choice) { percentage = new ArrayList(); @@ -67,7 +74,8 @@ public int getData(int month, int year, String choice) { SQLiteDatabase sqLiteDatabase = getWritableDatabase(); String column[] = {"_id", "Date", "Percentage"}; String args[] = {"" + month, "" + year, "yes", choice}; - Cursor cursor = sqLiteDatabase.query(userMedicationChoiceTable, column, "Month =? AND Year =? AND Status =? AND Choice =?", args, null, null,"Date ASC"); + Cursor cursor = sqLiteDatabase.query(userMedicationChoiceTable, column, "Month =? AND Year =? AND Status =? AND Choice =?", args, + null, null,"Date ASC"); boolean isDataFound = false; while (cursor.moveToNext()) { isDataFound = true; @@ -203,23 +211,28 @@ public void updateMedicationEntry(int date, int month, int year, String entry,do SQLiteDatabase sqDB = getReadableDatabase(); ContentValues values = new ContentValues(2); + values.put("Status", entry); values.put("Percentage", percentage); + String[] args = new String[]{String.valueOf(date), String.valueOf(month),String.valueOf(year)}; String[] column = {"Percentage"}; - /**Update is used instead of Insert, because the entry already exist**/ + + // Update is used instead of Insert, because the entry already exist**/ sqDB.update(userMedicationChoiceTable, values, "Date=? AND Month=? AND YEAR=?", args); - Cursor cursor=sqDB.query(userMedicationChoiceTable,column,null,null,null,null,null); - while(cursor.moveToNext()) - { - Log.d(TAGDSH, "Percentage:" + cursor.getDouble(0)); - } + //Cursor cursor=sqDB.query(userMedicationChoiceTable,column,null,null,null,null,null); +// while(cursor.moveToNext()) +// { +// Log.d(TAGDSH, "Percentage:" + cursor.getDouble(0)); +// } sqDB.close(); } /*If No Entry will be found it will enter in the database, so that it can be later updated. * Usage is in Day Fragment Activity **/ + // take drug value too from prefernces, hence in param + // send preference value too in parameters Is Weekly -- calculation of Choice public void insertOrUpdateMissedMedicationEntry(int date, int month, int year,double percentage) { SQLiteDatabase sqDB = this.getWritableDatabase(); @@ -229,6 +242,8 @@ public void insertOrUpdateMissedMedicationEntry(int date, int month, int year,do Choice="weekly"; else Choice="daily"; + + // calculation of timestamp if(date>=10) ts=""+year+"-"+month+"-"+date; else @@ -236,10 +251,13 @@ public void insertOrUpdateMissedMedicationEntry(int date, int month, int year,do String []columns={"Status"}; String []selArgs= {""+date,""+month,""+year}; - Cursor cursor = sqDB.query(userMedicationChoiceTable, columns, "Date=? AND Month =? AND Year =?", selArgs, null, null, null, null); + Cursor cursor = sqDB.query(userMedicationChoiceTable, columns, "Date=? AND Month =? AND Year =?", selArgs, + null, null, null, null); + int idx0; String st=""; int flag=0; while(cursor.moveToNext()) { + // st is status where date, month and year given is same in database & if such value exists, put flag = 1 idx0=cursor.getColumnIndex("Status"); st=cursor.getString(idx0); flag=1; @@ -359,7 +377,8 @@ public String getStatus(int date,int month,int year){ SQLiteDatabase sqDB = getWritableDatabase(); String []column = {"Status"}; String []selArgs = {""+date,""+month,""+year}; - Cursor cursor= sqDB.query(userMedicationChoiceTable,column,"Date =? AND Month =? AND Year =?",selArgs,null,null,null,null); + Cursor cursor= sqDB.query(userMedicationChoiceTable,column,"Date =? AND Month =? AND Year =?", + selArgs,null,null,null,null); while(cursor.moveToNext()) { @@ -391,11 +410,14 @@ public int getDosesInaRowDaily() } catch (Exception e) { return 0; } - if (cursor.getString(0).compareTo("yes") == 0) { - prevDate = cursor.getInt(2); - prevDateMonth = cursor.getInt(3); - if (Math.abs(currDate - prevDate) <= 1) - dosesInaRow++; + + if(cursor.getString(0)!=null){ + if (cursor.getString(0).compareTo("yes") == 0){ + prevDate = cursor.getInt(2); + prevDateMonth = cursor.getInt(3); + if (Math.abs(currDate - prevDate) <= 1) + dosesInaRow++; + } } /**Since Previous and Current Date our Updated, @@ -405,6 +427,7 @@ public int getDosesInaRowDaily() currDateMonth = cursor.getInt(3); currDateYear = cursor.getInt(4); ts = cursor.getString(cursor.getColumnIndex("Timestamp")); + Log.d(TAGDSH, "curr date ->" + ts); int parameter = Math.abs(currDate - prevDate); if ((cursor.getString(0)) != null) { @@ -414,7 +437,7 @@ public int getDosesInaRowDaily() else break; } else { - parameter = Math.abs(currDate - prevDate) % (getNumberofDaysinMonth(currDateMonth, currDateYear) - 1); + parameter = Math.abs(currDate - prevDate) % (CalendarFunction.getNumberOfDaysInMonth(currDateMonth, currDateYear) - 1); if (cursor.getString(0).compareTo("yes") == 0 && parameter <= 1) dosesInaRow++; else @@ -433,23 +456,6 @@ public int getDosesInaRowDaily() return dosesInaRow; } - /**Method to give no. of days in month. */ - private int getNumberofDaysinMonth(int month,int year) - { - if(isLeapYear(year)) - { - return daysOfMonthLeap[month]; - } - else - return daysOfMonth[month]; - } - - /**Check whether it is a leap layer**/ - private static boolean isLeapYear(int year) { - Calendar cal = Calendar.getInstance(); - cal.set(Calendar.YEAR, year); - return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365; - } /**From the Last Time Pill was Taken it Calculates the maximum weeks in a row medication was taken * Need at Home Screen, First Analytic Scrren, Second Analytic Scrren, Day Fragment Screen @@ -458,7 +464,6 @@ public int getDosesInaRowWeekly() { SQLiteDatabase sqDB = getWritableDatabase(); String []column={"Status","Timestamp","Date","Month","Year"}; - Cursor cursor= sqDB.query(userMedicationChoiceTable,column,null,null,null,null,"Timestamp DESC"); int dosesInaRow=1,aMonth=0,pMonth=0; Date ado,pdo; @@ -469,7 +474,6 @@ public int getDosesInaRowWeekly() if(cursor!=null) { cursor.moveToNext(); if(cursor!=null) { - try { ats = cursor.getString(1); } @@ -477,7 +481,6 @@ public int getDosesInaRowWeekly() { return 0; } - aMonth = cursor.getInt(3) + 1; ats = getHumanDateFormat(ats, aMonth); ado = getDateObject(ats); @@ -486,9 +489,9 @@ public int getDosesInaRowWeekly() pMonth = cursor.getInt(3) + 1; pts = getHumanDateFormat(pts, pMonth); pdo = getDateObject(pts); - numDays = getDayofWeek(pdo); + numDays = CalendarFunction.getDayofWeek(pdo); pPara = 7 - numDays + 7; - aPara = getNumberOfDays(pdo, ado); + aPara = CalendarFunction.getNumberOfDays(pdo, ado); if (aPara <= pPara) dosesInaRow++; else @@ -503,60 +506,13 @@ public int getDosesInaRowWeekly() } - /*Getting the Date Object from the String**/ - private Date getDateObject(String s) - { - Date dobj=null; - - SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); - try { - dobj= sdf.parse(s); - } - catch (ParseException e) - { - e.printStackTrace(); - } - - return dobj; - } - - /*Getting the Day of Week from the String**/ - private int getDayofWeek(Date d) - { - Calendar cal=Calendar.getInstance(); - cal.setTime(d); - int day=cal.get(Calendar.DAY_OF_WEEK); - return day; - } - - /*Getting no. of Days between two interval**/ - private long getNumberOfDays(Date d1,Date d2) { - long interval = 0; - Calendar c= Calendar.getInstance(); - c.setTime(d1); - long ld1 = c.getTimeInMillis(); - c.setTime(d2); - long ld2=c.getTimeInMillis(); - long oneDay = 1000 * 60 * 60 * 24; - interval = (ld2-ld1) / oneDay; - return interval; - } - - /*Setting the Date Object to Human Readable Format**/ - private String getHumanDateFormat(String ats,int aMonth) - { - String aYear=ats.substring(0, 4); - String aDate=ats.substring(Math.max(ats.length() - 2, 0)); - ats=aYear+"-"+aMonth+"-"+aDate; - return ats; - } - public String getMediLastTakenTime() { SQLiteDatabase sqDB=getWritableDatabase(); String [] column={"Date","Month","Year"}; String recentDate=""; - Cursor cursor = sqDB.query(userMedicationChoiceTable, column, null, null, null, null, "Timestamp DESC LIMIT 1"); + Cursor cursor = sqDB.query(userMedicationChoiceTable, column, null, null, + null, null, "Timestamp DESC LIMIT 1"); if(cursor!=null) { cursor.moveToNext(); try @@ -614,7 +570,6 @@ public void insertLocation(String location) /**Fetching the Location**/ public Cursor getLocation() { - SQLiteDatabase sqDB = getWritableDatabase(); String []column={"_id","Location"}; @@ -639,7 +594,7 @@ public void insertPackingItem(String pItem,int quantity, String status) while (cursor.moveToNext()) { - q= cursor.getInt(1); + q= cursor.getInt(1); flag++; Log.d(TAGDSH,"Flag: "+flag); } @@ -712,21 +667,47 @@ public void refreshPackingItemStatus() { break; } + } + } + /**Finding the Last Date the Drug was taken**/ + public String getLastTaken() + { + SQLiteDatabase sqDB = getWritableDatabase(); + String []column={"Status","Timestamp","Date","Month","Year","Choice"}; + Cursor cursor= sqDB.query(userMedicationChoiceTable,column,null,null,null,null,"Timestamp ASC"); + String lastDate=""; + if(cursor!=null) + { + while (cursor.moveToNext()) + { + try { + if (cursor.getString(0).equalsIgnoreCase("yes")) { + lastDate=cursor.getString(1); + } + } + catch(NullPointerException npe) + { + return ""; + } + } } + sqDB.close(); + return lastDate; - } + } /**Finding the No. of Drugs**/ public int getCountTaken() { SQLiteDatabase sqDB = getWritableDatabase(); String []column={"Status","Timestamp","Date","Month","Year","Choice"}; - Cursor cursor= sqDB.query(userMedicationChoiceTable,column,null,null,null,null,"Timestamp ASC"); + Cursor cursor= sqDB.query(userMedicationChoiceTable,column,null,null,null, + null,"Timestamp ASC"); int count=0; if(cursor!=null) { @@ -752,63 +733,7 @@ public int getCountTaken() } - - /**Finding the No. of weekly days between two dates for calculating Adherence**/ - public int getIntervalWeekly(Date s, Date e, int weekday) - { - Calendar startCal; - Calendar endCal; - startCal = Calendar.getInstance(); - startCal.setTime(s); - endCal = Calendar.getInstance(); - endCal.setTime(e); - int medDays = 0,flag=0; - //If working dates are same,then checking what is the day on that date. - if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) { - if (startCal.get(Calendar.DAY_OF_WEEK) == weekday) - { - ++medDays; - return medDays; - } - } - /*If start date is coming after end date, Then shuffling Dates and storing dates - by incrementing upto end date in do-while part.*/ - if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) { - startCal.setTime(e); - endCal.setTime(s); - } - - do { - - if (startCal.get(Calendar.DAY_OF_WEEK)==weekday) { - ++medDays; - } - startCal.add(Calendar.DAY_OF_MONTH, 1); - } while (startCal.getTimeInMillis() <= endCal.getTimeInMillis()); - - if(startCal.get(Calendar.DAY_OF_WEEK)==endCal.get(Calendar.DAY_OF_WEEK) && (startCal.get(Calendar.DAY_OF_WEEK)==weekday)) - ++medDays; - - return medDays; - } - - /**Finding the No. of days between two dates for calculating adherence of daily drugs**/ - public int getIntervalDaily(Date s,Date e) - { - long sLong=s.getTime(); - long eLong=e.getTime(); - - long oneDay=24*60*60*1000; - - long interval=(eLong-sLong)/oneDay; - - int interv=(int)interval+1; - - return interv; - - } - - /**Finding the Drugs between two dates for updaing Adherence in Day Fragment Activity of any selected date**/ + /**Finding the Drugs between two dates for updating Adherence in Day Fragment Activity of any selected date**/ public int getCountTakenBetween(Date s,Date e) { SQLiteDatabase sqDB = getWritableDatabase(); @@ -820,8 +745,6 @@ public int getCountTakenBetween(Date s,Date e) { while (cursor.moveToNext()) { - try { - String d= cursor.getString(1); Log.d(TAGDSH,"Curr Time:"+d); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); @@ -848,21 +771,14 @@ public int getCountTakenBetween(Date s,Date e) Log.d(TAGDSH,"End Long:"+endt); Log.d(TAGDSH,"Start Long:"+strt); - if (cursor.getString(0).equalsIgnoreCase("yes") == true) { + if (cursor.getString(0).equalsIgnoreCase("yes")) { - if(currt>=strt && currt<=endt) + if (currt >= strt && currt <= endt) count++; - else if(strt==endt) - { + else if (strt == endt) { count++; } } - } - catch(NullPointerException npe) - { - return 0; - - } } } sqDB.close(); diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/notifications/DrugNotificationUtils.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/notifications/DrugNotificationUtils.java new file mode 100644 index 00000000..0772fe06 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/notifications/DrugNotificationUtils.java @@ -0,0 +1,159 @@ +package com.peacecorps.malaria.notifications; + +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Build; +import android.support.v4.app.NotificationCompat; +import android.support.v4.content.ContextCompat; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.data.db.DbHelper; +import com.peacecorps.malaria.notifications.receiver.DrugNotificationReceiver; +import com.peacecorps.malaria.ui.main.MainActivity; +import com.peacecorps.malaria.utils.InjectionClass; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import java.util.Calendar; + +public class DrugNotificationUtils { + private static final int START_ACTIVITY_PENDING_INTENT_ID = 245; + private static final int ACTION_ACCEPT_PENDING_INTENT_ID = 502; + private static final int ACTION_REJECT_PENDING_INTENT_ID = 504; + public static final int ACTION_SNOOZE_PENDING_INTENT_ID = 506; + private static final String NOTIFICATION_CHANNEL_ID = "drug_reminder_channel_id"; + private static final int NOTIFICATION_MANAGER_ID = 568; + + public static final String ACTION_ACCEPTED_MEDICINE = "ACTION_ACCEPTED_MEDICINE"; + public static final String ACTION_REJECT_MEDICINE = "ACTION_REJECT_MEDICINE"; + public static final String ACTION_SNOOZE_MEDICINE = "ACTION_SNOOZE_MEDICINE"; + + // function to create and start notification for drug reminder + private static void startNotificationForDrugs(boolean snooze, Context context) { + NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + + if(Build.VERSION.SDK_INT>Build.VERSION_CODES.O) { + NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, + context.getString(R.string.drug_reminder_notification_title), + NotificationManager.IMPORTANCE_DEFAULT); + if (manager != null) { + manager.createNotificationChannel(channel); + } + } + + NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context) + .setColor(ContextCompat.getColor(context, R.color.lightest_brown)) + .setContentTitle(context.getString(R.string.drug_reminder_notification_title)) + .setContentText(context.getString(R.string.drug_reminder_notification_message)) + .setContentIntent(contentIntent(context)) + .setDefaults(Notification.DEFAULT_VIBRATE) + .setSmallIcon(R.drawable.app_icon) + .setStyle(new NotificationCompat.BigTextStyle().bigText( + context.getString(R.string.drug_reminder_notification_message))) + .addAction(acceptMedicineAction(context)) + .addAction(rejectMedicineAction(context)) + .setWhen(0) + .setAutoCancel(true); + + if(snooze) { + notificationBuilder.addAction(snoozeAction(context)); + } + + Uri sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.soundsmedication); + + if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN && + Build.VERSION.SDK_INT 0) { + saveUserSettings(state, false); + calculateAdherenceAndSetUserSelection(interval, drugPicked, "daily", status); + } + } + + private void calculateAdherenceAndSetUserSelection(final double interval, final String drugPicked, final String choice, + final String status) { + dataManager.getMedicineCountTaken(new DbHelper.LoadIntegerCallback() { + @Override + public void onDataLoaded(int takenCount) { + double adherenceRate = ((double) takenCount / interval) * 100; + dataManager.setUserMedicineSelection(drugPicked, choice, Calendar.getInstance().getTime(), + status, adherenceRate); + } + }); + } + + private void playBlackGroundSound(Context context) { + Uri sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.soundsmedication); + final MediaPlayer mp = MediaPlayer.create(context, sound); + mp.start(); + } + + /** + * Function to set the alarm for next week + */ + private void changeWeeklyAlarmTime(Context context) { + int hour = Calendar.getInstance().get(Calendar.HOUR); + int minute = Calendar.getInstance().get(Calendar.MINUTE) - 1; + context.startService( + new Intent(context, AlarmService.class)); + dataManager.updateAlarmTime(hour, minute); + } +} diff --git a/src/com/peacecorps/malaria/AlarmService.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/notifications/service/AlarmService.java similarity index 63% rename from src/com/peacecorps/malaria/AlarmService.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/notifications/service/AlarmService.java index 4440f786..abb78d29 100755 --- a/src/com/peacecorps/malaria/AlarmService.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/notifications/service/AlarmService.java @@ -1,14 +1,17 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.notifications.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; -public class AlarmService extends Service { +import com.peacecorps.malaria.notifications.receiver.AlarmHandlerClass; - /**Setting up Alarm Calls his Alarm Service**/ +/** + * setting up alarm using the service + */ +public class AlarmService extends Service { - AlarmHandlerClass alarmHandlerClass = new AlarmHandlerClass(); + private AlarmHandlerClass alarmHandlerClass = new AlarmHandlerClass(); @Override public IBinder onBind(Intent intent) { @@ -17,7 +20,6 @@ public IBinder onBind(Intent intent) { } public void onStart(Intent intent, int startId) { - alarmHandlerClass.setAlarm(AlarmService.this); } @@ -28,9 +30,12 @@ public void onCreate() { } + /** + * alarm service request made + * alarm handler will start alarm + */ @Override public int onStartCommand(Intent intent, int flags, int startId) { - /**Alarm Service Request Made and Alarm Handler will Handle It. **/ alarmHandlerClass.setAlarm(AlarmService.this); return START_STICKY; } diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/BaseActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/BaseActivity.java new file mode 100644 index 00000000..27c0fff0 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/BaseActivity.java @@ -0,0 +1,25 @@ +package com.peacecorps.malaria.ui.base; + +import android.os.Bundle; +import android.support.annotation.Nullable; +import android.support.v7.app.AppCompatActivity; + +public abstract class BaseActivity extends AppCompatActivity implements MvpView { + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + protected abstract void init(); + + @Override + public boolean isNetworkConnected() { + return false; + } + + @Override + protected void onDestroy() { + super.onDestroy(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/BaseFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/BaseFragment.java new file mode 100644 index 00000000..cf252543 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/BaseFragment.java @@ -0,0 +1,46 @@ +package com.peacecorps.malaria.ui.base; + +import android.os.Bundle; +import android.support.annotation.LayoutRes; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.v4.app.Fragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Toast; + +public abstract class BaseFragment extends Fragment implements MvpView { + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + super.onCreateView(inflater, container, savedInstanceState); + return inflater.inflate(getContentResource(), container, false); + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + } + + @Override + public boolean isNetworkConnected() { + return false; + } + + /** + * Layout resource to inflate + * + * @return layout resource + */ + @LayoutRes + protected abstract int getContentResource(); + + protected abstract void init(); + + void displayToastMessage(String message) { + Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); + } + +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/BasePresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/BasePresenter.java new file mode 100644 index 00000000..e9330957 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/BasePresenter.java @@ -0,0 +1,54 @@ +package com.peacecorps.malaria.ui.base; + +import android.content.Context; + +import com.peacecorps.malaria.data.AppDataManager; + +/** + * Base class that implements the Presenter interface and provides a base implementation for + * onAttach() and onDetach(). It also handles keeping a reference to the mvpView that + * can be accessed from the children classes by calling getMvpView(). + */ + + +public class BasePresenter implements MvpPresenter { + private Context context; + private V mvpView; + private AppDataManager manager; + + public BasePresenter(AppDataManager manager, Context context) { + this.context = context; + this.manager = manager; + } + + @Override + public void attachView(V view) { + mvpView = view; + } + + @Override + public void detachView() { + mvpView = null; + } + + /* + * method to check if the view is attached or not + * + * @return true if attached + */ + public boolean isViewAttached() { + return mvpView != null; + } + + public V getView() { + return mvpView; + } + + public AppDataManager getDataManager() { + return manager; + } + + public Context getContext() { + return context; + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/MvpPresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/MvpPresenter.java new file mode 100644 index 00000000..d0a13e19 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/MvpPresenter.java @@ -0,0 +1,16 @@ +package com.peacecorps.malaria.ui.base; + +public interface MvpPresenter { + + /** + * called when view is attached to presenter + * + * @param view + */ + void attachView(V view); + + /** + * called when view is detached from presenter + */ + void detachView(); +} \ No newline at end of file diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/MvpView.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/MvpView.java new file mode 100644 index 00000000..c6bcd444 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/MvpView.java @@ -0,0 +1,5 @@ +package com.peacecorps.malaria.ui.base; + +public interface MvpView { + boolean isNetworkConnected(); +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/MyApp.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/MyApp.java new file mode 100644 index 00000000..bddf7856 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/base/MyApp.java @@ -0,0 +1,19 @@ +package com.peacecorps.malaria.ui.base; + +import android.app.Application; + +import com.peacecorps.malaria.utils.TypefaceUtil; + +/** + * Created by Anamika Tripathi on 7/8/18. + */ +public class MyApp extends Application { + + @Override + public void onCreate() { + super.onCreate(); + TypefaceUtil.overrideFont(getApplicationContext(), "SERIF", + "fonts/garreg.ttf"); + + } +} \ No newline at end of file diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/HomeContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/HomeContract.java new file mode 100644 index 00000000..15909d79 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/HomeContract.java @@ -0,0 +1,35 @@ +package com.peacecorps.malaria.ui.home_screen; + +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +/** + * Created by Anamika Tripathi on 5/8/18. + */ +public interface HomeContract { + + interface HomeMvpView extends MvpView{ + void setCurrentDayAndDate(String date, String day); + void setWarningText(); + void isDrugTakenUI(); + void isDrugNotTakenUI(); + void newDayUI(); + void missedWeekUI(); + void startAlarmServiceClass(); + + } + + interface HomeMvpPresenter extends MvpPresenter { + void checkDayDateOfWeek(); + void checkWarningVisibility(); + void increaseDrugAcceptedCount(); + void updateUserMedicineSelection(double adherenceRate, boolean isAcceptButton); + void checkDrugIntervalFirstRunTime(boolean isAcceptButton); + void decideDrugTakenUIBoolean(boolean isWeekly, boolean isTaken); + void increaseDrugRejectCount(); + void decideDrugTakenForUI(); + void checkDrugIntervalWeeklyDate(); + void storeMediTimeLastChecked(); + + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/HomePresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/HomePresenter.java new file mode 100644 index 00000000..22404a2d --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/HomePresenter.java @@ -0,0 +1,325 @@ +package com.peacecorps.malaria.ui.home_screen; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; + +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.data.db.DbHelper; +import com.peacecorps.malaria.notifications.service.AlarmService; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.home_screen.HomeContract.HomeMvpView; +import com.peacecorps.malaria.utils.CalendarFunction; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +/** + * Created by Anamika Tripathi on 5/8/18. + */ +public class HomePresenter extends BasePresenter implements HomeContract.HomeMvpPresenter { + HomePresenter(AppDataManager manager, Context context) { + super(manager, context); + } + + /** + * takes date from calendar, uses SimpleDataFormat to parse date in to current Day & date in specific format + * calls setCurrentDayAndDelete to set date+day in fragment + */ + @Override + public void checkDayDateOfWeek() { + @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("EEEE", Locale.getDefault()); + Date d = new Date(); + String dayOfTheWeek = sdf.format(d); + String date = new SimpleDateFormat("dd/MM/yyyy", + Locale.getDefault()).format(d); + getView().setCurrentDayAndDate(date, dayOfTheWeek); + } + + /** + * check if medicine in Store count is less than user's setting for warning? + * If yes, show warning message + */ + @Override + public void checkWarningVisibility() { + // alert ime set by user in MedicineStoreFragment + int alertTime = getDataManager().getAlertNumberDaysOrWeeks(); + int medicineCount = getDataManager().getMedicineStoreValue(); + //display warning + if (alertTime != 1 && medicineCount < alertTime) { + getView().setWarningText(); + } + + } + + /** + * decides UI decision by drug history saved in preferences + * calls appropriate getView function to update UI + */ + @Override + public void decideDrugTakenForUI() { + final long today = new Date().getTime(); + getDataManager().getFirstTimeByTimeStamp(new DbHelper.LoadLongCallback() { + @Override + public void onDataLoaded(Long value) { + long takenWeeklyDate = getDataManager().getLongWeeklyDate(); + long takenDailyDate = getDataManager().getDateDrug(); + boolean isWeekly = getDataManager().isDosesWeekly(); + boolean isWeeklyDrugTaken = getDataManager().isWeeklyDrugTaken(); + if (isWeekly) { + long interval; + long oneDay = 1000 * 60 * 60 * 24; + interval = (today - takenWeeklyDate) / oneDay; + + if (interval == 0) { + if (isWeeklyDrugTaken) { + getView().isDrugTakenUI(); + } else { + getView().newDayUI(); + } + } else { + if (interval < 7 && interval > 0) { + if (isWeeklyDrugTaken) { + getView().isDrugTakenUI(); + } else { + getDataManager().setDosesWeekly(0); + getView().missedWeekUI(); + getView().newDayUI(); + } + } else if (interval > 7) { + getDataManager().setDrugAcceptedCount(0); + getDataManager().setDosesWeekly(0); + getView().missedWeekUI(); + getView().newDayUI(); + } + } + } else { + long interval; + long oneDay = 1000 * 60 * 60 * 24; + interval = (today - takenDailyDate) / oneDay; + if (interval == 0) { + if (getDataManager().isDrugTaken()) { + getView().isDrugTakenUI(); + } else { + getView().isDrugNotTakenUI(); + } + } else { + if (interval > 1) { + getDataManager().setDosesDaily(0); + } + getView().newDayUI(); + } + } + } + }); + + } + + /** + * increases drug accepted count in preferences + */ + @Override + public void increaseDrugAcceptedCount() { + // get the value + int value = getDataManager().getDrugAcceptedCount(); + // increase by 1 + getDataManager().setDrugAcceptedCount(value + 1); + } + + /** + * used to update in db if medicine is taken or not + * decrease current medicine count in preferences if taken + * increase user-points in preferences if taken + */ + @Override + public void updateUserMedicineSelection(double adherenceRate, boolean isAcceptButton) { + // returns true if weekly or false for daily + boolean isWeekly = getDataManager().isDosesWeekly(); + String drugPicked = getDataManager().getDrugPicked(); + Date date = Calendar.getInstance().getTime(); + if (isAcceptButton) { + if (isWeekly) { + decideDrugTakenUIBoolean(true, true); + getDataManager().setUserMedicineSelection(drugPicked, "weekly", date, + "yes", adherenceRate); + getDataManager().getDosesInaRowWeekly(new DbHelper.LoadIntegerCallback() { + @Override + public void onDataLoaded(int value) { + getDataManager().setDosesWeekly(value); + } + }); + } else { + decideDrugTakenUIBoolean(false, true); + getDataManager().setUserMedicineSelection(drugPicked, "daily", date, "yes", adherenceRate); + getDataManager().getDosesInaRowDaily(new DbHelper.LoadIntegerCallback() { + @Override + public void onDataLoaded(int value) { + getDataManager().setDosesDaily(value); + } + }); + } + //get user's score + int score = getDataManager().getUserScore(); + //get medicine in store + int medicineStore = getDataManager().getMedicineStoreValue(); + //increase score if medicine is taken + getDataManager().setUserScore(score + 1); + //decrease medicine store by one if medicine is taken + getDataManager().setMedicineStoreValue(medicineStore - 1); + ToastLogSnackBarUtil.showDebugLog("HomePresenter/updateUserMedicineSelection: score updated"); + } else { + if (isWeekly) { + decideDrugTakenUIBoolean(true, false); + getDataManager().setUserMedicineSelection(drugPicked, "weekly", date, "no", adherenceRate); + } else { + decideDrugTakenUIBoolean(false, false); + getDataManager().setUserMedicineSelection(drugPicked, "daily", date, "no", adherenceRate); + } + } + } + + /** + * determines interval for firstRunTime and calls computerAdherenceInterval to calculate adherence + */ + @Override + public void checkDrugIntervalFirstRunTime(final boolean isAcceptButton) { + + final long today = new Date().getTime(); + getDataManager().getFirstTimeByTimeStamp(new DbHelper.LoadLongCallback() { + @Override + public void onDataLoaded(Long value) { + long interval; + if (value != 0) { + ToastLogSnackBarUtil.showDebugLog("First Run Time at FAF->" + value); + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(value); + cal.add(Calendar.MONTH, 1); + + Date start = cal.getTime(); + Date end = Calendar.getInstance().getTime(); + end.setTime(today); + // saving in preferences + getDataManager().setFirstRunTime(value); + if (getDataManager().isDosesWeekly()) { + int dayWeekly = getDataManager().getDayWeekly(); + interval = CalendarFunction.getIntervalWeekly(start, end, dayWeekly); + } else { + interval = CalendarFunction.getIntervalDaily(start, end); + } + } else { + interval = 1; + } + computeAdherenceRate(interval, isAcceptButton); + } + }); + + } + + @Override + public void checkDrugIntervalWeeklyDate() { + final long today = new Date().getTime(); + final long takenDate = getDataManager().getLongWeeklyDate(); + getDataManager().getFirstTimeByTimeStamp(new DbHelper.LoadLongCallback() { + @Override + public void onDataLoaded(Long value) { + if (takenDate == 0) { + long oneDay = 1000 * 60 * 60 * 24; + long interval; + interval = (today - takenDate) / oneDay; + if (interval > 1) { + changeWeeklyAlarmTime(); + } + } + } + }); + } + + /** + * @param interval : interval between drug taken time + * desc : calculates adherence rate & calls updateUserMedicineSelection + */ + private void computeAdherenceRate(final long interval, final boolean isAcceptButton) { + getDataManager().getMedicineCountTaken(new DbHelper.LoadIntegerCallback() { + @Override + public void onDataLoaded(int value) { + double adherenceRate = ((double) value / (double) interval) * 100; + ToastLogSnackBarUtil.showDebugLog("HomePresenter/computerAdherence: " + interval + " " + value + " " + adherenceRate); + updateUserMedicineSelection(adherenceRate, isAcceptButton); + } + }); + } + + /** + * @param isWeekly : determines if drug is weekly or daily + * @param isTaken : determines if it is taken or not/depends on accept or reject button + */ + @Override + public void decideDrugTakenUIBoolean(boolean isWeekly, boolean isTaken) { + if (isWeekly) { + checkDrugIntervalWeeklyDate(); + } + saveUserSettings(isTaken, isWeekly); + if (isTaken) { + getView().isDrugTakenUI(); + } else { + getView().isDrugNotTakenUI(); + } + } + + /** + * increase drug reject count in preferences + */ + @Override + public void increaseDrugRejectCount() { + int value = getDataManager().getDrugRejectedCount(); + getDataManager().setDrugRejectedCount(value + 1); + } + + /** + * set last medicine taken time + * used in isDrugTakenUI + */ + @Override + public void storeMediTimeLastChecked() { + String lastMedicationCheckedTime = ""; + Calendar c = Calendar.getInstance(); + lastMedicationCheckedTime = new SimpleDateFormat("dd/MM/yyyy", + Locale.getDefault()).format(c.getTime()); + getDataManager().setMedicineLastTakenTime(lastMedicationCheckedTime); + } + + /** + * @param isTaken : determines if it is taken or not/depends on accept or reject button + * @param isWeekly : determines if drug is weekly or daily + * desc : checks weekly or daily drug, updates preference data + */ + private void saveUserSettings(boolean isTaken, boolean isWeekly) { + if (isWeekly) { + // updates on last taken date + getDataManager().setLongWeeklyDate(new Date().getTime()); + // sets true or false if drug is taken or not + getDataManager().setWeeklyDrugTaken(isTaken); + } else { + getDataManager().setDateDrugTaken(new Date().getTime()); + getDataManager().setDrugTaken(isTaken); + } + // increases drug accepted count + int count = getDataManager().getDrugAcceptedCount(); + getDataManager().setDrugAcceptedCount(count + 1); + } + + private void changeWeeklyAlarmTime() { + int hour = Calendar.getInstance().get(Calendar.HOUR); + int minute = Calendar.getInstance().get(Calendar.MINUTE) - 1; + + if (getContext() != null) { + getContext().startService(new Intent(getContext(), AlarmService.class)); + } + getView().startAlarmServiceClass(); + getDataManager().updateAlarmTime(hour, minute); + } + +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/HomeScreenFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/HomeScreenFragment.java new file mode 100644 index 00000000..de9d998c --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/HomeScreenFragment.java @@ -0,0 +1,187 @@ +package com.peacecorps.malaria.ui.home_screen; + +import android.content.Context; +import android.content.Intent; +import android.graphics.Color; +import android.graphics.Typeface; +import android.media.MediaPlayer; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.TextView; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.notifications.service.AlarmService; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.utils.InjectionClass; + +import butterknife.BindView; +import butterknife.ButterKnife; +import butterknife.OnClick; + +/** + * Created by Anamika Tripathi on 5/8/18. + */ +public class HomeScreenFragment extends BaseFragment implements HomeContract.HomeMvpView { + + + private Context context; + private HomePresenter presenter; + @BindView(R.id.btn_accept_medication) + Button mAcceptMedicationButton; + @BindView(R.id.btn_reject_medication) + Button mRejectMedicationButton; + @BindView(R.id.tv_current_date) + TextView mCurrentDateLabel; + @BindView(R.id.tv_day_of_week) + TextView mCurrentDayOfweekLabel; + @BindView(R.id.warningView) + TextView warningView; + @BindView(R.id.warningButton) + Button warningButton; + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, + @Nullable Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_home_screen, container, false); + context = getContext(); + ButterKnife.bind(this, view); + presenter = new HomePresenter<>(InjectionClass.provideDataManager(context), context); + presenter.attachView(this); + return view; + } + + @Override + protected int getContentResource() { + return R.layout.fragment_home_screen; + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + init(); + } + + // get drug accepted + rejected count from preferences + @Override + protected void init() { + // setting font for day & date labels + setFont(); + // checking current date and day + presenter.checkDayDateOfWeek(); + // checking visibility of warning text using preferences + presenter.checkWarningVisibility(); + // decide drug taken for UI + presenter.decideDrugTakenForUI(); + } + + // set current date and day + @Override + public void setCurrentDayAndDate(String date, String day) { + mCurrentDateLabel.setText(date); + mCurrentDayOfweekLabel.setText(day); + } + + // make warning text visible + @Override + public void setWarningText() { + warningView.setVisibility(View.VISIBLE); + warningButton.setVisibility(View.VISIBLE); + + } + + @Override + public void isDrugTakenUI() { + mCurrentDateLabel.setTextColor(Color.rgb(89, 43, 21)); + mCurrentDayOfweekLabel.setTextColor(Color.rgb(89, 43, 21)); + mAcceptMedicationButton + .setBackgroundResource(R.drawable.accept_medi_checked_); + mRejectMedicationButton + .setBackgroundResource(R.drawable.reject_medi_grayscale); + setButtonState(false); + presenter.storeMediTimeLastChecked(); + } + + @Override + public void isDrugNotTakenUI() { + mAcceptMedicationButton + .setBackgroundResource(R.drawable.accept_medi_grayscale); + mRejectMedicationButton + .setBackgroundResource(R.drawable.reject_medi_checked); + setButtonState(false); + } + + @Override + public void newDayUI() { + mAcceptMedicationButton + .setBackgroundResource(R.drawable.accept_medi_checked_); + mRejectMedicationButton + .setBackgroundResource(R.drawable.reject_medi_checked); + setButtonState(true); + } + + @Override + public void missedWeekUI() { + mCurrentDateLabel.setTextColor(Color.RED); + mCurrentDayOfweekLabel.setTextColor(Color.RED); + } + + @Override + public void startAlarmServiceClass() { + if (getActivity() != null) { + getActivity().startService( + new Intent(getActivity(), AlarmService.class)); + } + } + + public void setButtonState(boolean state) { + mAcceptMedicationButton.setEnabled(state); + mRejectMedicationButton.setEnabled(state); + } + + // setting fonts from assets file + private void setFont() { + if (getActivity() != null) { + Typeface custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/garreg.ttf"); + mCurrentDayOfweekLabel.setTypeface(custom_font); + mCurrentDateLabel.setTypeface(custom_font); + } + } + + @OnClick(R.id.fragment_home_screen_set_tone_button) + public void reminderButtonListener() { + Intent myIntent = new Intent(getActivity(), ReminderToneActivity.class); + startActivity(myIntent); + } + + @OnClick(R.id.btn_accept_medication) + public void acceptButtonListener() { + // create media player for sound + MediaPlayer.create(getActivity(), R.raw.accept_button_sound) + .start(); + // increase drug accepted count by 1 + presenter.increaseDrugAcceptedCount(); + + presenter.checkDrugIntervalFirstRunTime(true); + } + + @OnClick(R.id.btn_reject_medication) + public void rejectButtonListener() { + + MediaPlayer.create(getActivity(), R.raw.reject_button_sound) + .start(); + presenter.increaseDrugRejectCount(); + + presenter.checkDrugIntervalFirstRunTime(false); + } + +// @OnClick(R.id.fragment_home_screen_settings_button) +// public void settingListener() { +// DrugNotificationUtils.startNotificationCheckSnooze(context); +// } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/ReminderToneActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/ReminderToneActivity.java new file mode 100644 index 00000000..a798dd08 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/home_screen/ReminderToneActivity.java @@ -0,0 +1,84 @@ +package com.peacecorps.malaria.ui.home_screen; + +import android.app.Activity; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.utils.InjectionClass; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +/** + * Created by DELL on 1/16/2016. + */ +public class ReminderToneActivity extends Activity implements View.OnClickListener{ + + private EditText path; + private Uri audioFileUri; + + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.remainder_tone_dialog); + Button btnBrowse = findViewById(R.id.browse); + path= findViewById(R.id.tone_path); + Button btnOK = findViewById(R.id.dialogButtonOKReminder); + Button btnCancel = findViewById(R.id.dialogButtonCancelReminder); + btnBrowse.setOnClickListener(this); + btnOK.setOnClickListener(this); + btnCancel.setOnClickListener(this); + } + + @Override + public void onClick(View v) { + switch(v.getId()) { + case R.id.browse: + Intent intent; + intent = new Intent(); + intent.setAction(Intent.ACTION_GET_CONTENT); + intent.setType("audio/mpeg"); + startActivityForResult(Intent.createChooser(intent, "Select Via..."), 1); + break; + + case R.id.dialogButtonOKReminder: + + if(path.toString().isEmpty() || !isAudioFile()){ + path.setError("Specify valid path"); + break; + } + AppDataManager dataManager = InjectionClass.provideDataManager(this); + dataManager.setToneUri(audioFileUri.toString()); + ToastLogSnackBarUtil.showToast(this, "Reminder Tone Set"); + dataManager = null; + this.finish(); + break; + + case R.id.dialogButtonCancelReminder: + this.finish(); + break; + default: ToastLogSnackBarUtil.showErrorLog("ReminderToneActivity: Invalid id"); + } + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + if (resultCode == RESULT_OK && requestCode == 1) { + audioFileUri = data.getData(); + if(audioFileUri!=null) { + String MP3Path = audioFileUri.getPath(); + path.setText(MP3Path); + } + } + } + public boolean isAudioFile() { + if(audioFileUri!=null) { + String type= getContentResolver().getType(audioFileUri); + return "audio/mpeg".equals(type); + } + return false; + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/InfoHubContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/InfoHubContract.java new file mode 100644 index 00000000..bb6b5238 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/InfoHubContract.java @@ -0,0 +1,18 @@ +package com.peacecorps.malaria.ui.info_hub; + +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +/** + * Created by Anamika Tripathi on 17/7/18. + */ + +public interface InfoHubContract { + interface InfoHubMvpView extends MvpView { + + } + + interface InfoHubMvpPresenter extends MvpPresenter { + + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/InfoHubFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/InfoHubFragment.java new file mode 100644 index 00000000..54f2d721 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/InfoHubFragment.java @@ -0,0 +1,83 @@ +package com.peacecorps.malaria.ui.info_hub; + +import android.content.Context; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import butterknife.ButterKnife; + +/** + * Created by Anamika Tripathi on 18/7/18. + */ +public class InfoHubFragment extends BaseFragment implements InfoHubContract.InfoHubMvpView, View.OnClickListener { + + private Context context; + + + // returns a new instance of the Fragment + public static InfoHubFragment newInstance() { + return new InfoHubFragment(); + } + + @Override + public void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + // Inflate the layout for this fragment + View view = inflater.inflate(R.layout.info_hub_screen, container, false); + context = getContext(); + // butterknife binding + ButterKnife.bind(this, view); + // instantiating presenter, passing datamanger, view & attaching view to the presenter + return view; + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + } + + + @Override + protected int getContentResource() { + return R.layout.info_hub_screen; + } + + @Override + protected void init() { + // no need of it init() now, necessary to override + } + + // still needs to be worked upon + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.btn_peace_corps_policy: + break; + case R.id.btn_percent_side_effects: + break; + case R.id.btn_side_effects_pcv: + break; + case R.id.btn_side_effects_non_pcv: + break; + case R.id.btn_volunteer_adherence: + break; + case R.id.btn_effectiveness: + break; + default: + ToastLogSnackBarUtil.showToast(context, "Wrong button click"); + } + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/InfoHubPresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/InfoHubPresenter.java new file mode 100644 index 00000000..277dd912 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/InfoHubPresenter.java @@ -0,0 +1,18 @@ +package com.peacecorps.malaria.ui.info_hub; + +import android.content.Context; + +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.info_hub.InfoHubContract.InfoHubMvpPresenter; +import com.peacecorps.malaria.ui.info_hub.InfoHubContract.InfoHubMvpView; + +/** + * Created by Anamika Tripathi on 17/7/18. + */ +public class InfoHubPresenter extends BasePresenter implements InfoHubMvpPresenter { + + InfoHubPresenter(AppDataManager manager, Context context) { + super(manager, context); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/info_hub_fragments/PeaceCorpsPolicyFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/info_hub_fragments/PeaceCorpsPolicyFragment.java new file mode 100644 index 00000000..7b0657d0 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/info_hub/info_hub_fragments/PeaceCorpsPolicyFragment.java @@ -0,0 +1,33 @@ +package com.peacecorps.malaria.ui.info_hub.info_hub_fragments; + +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import com.peacecorps.malaria.ui.base.BaseFragment; + +/** + * Created by Anamika Tripathi on 18/7/18. + */ +public class PeaceCorpsPolicyFragment extends BaseFragment { + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + return super.onCreateView(inflater, container, savedInstanceState); + } + + + @Override + protected int getContentResource() { + return 0; + } + + @Override + protected void init() { + //Todo Still needs to be implemented + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/main/MainActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/main/MainActivity.java new file mode 100755 index 00000000..900777bc --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/main/MainActivity.java @@ -0,0 +1,218 @@ +package com.peacecorps.malaria.ui.main; + +import android.app.Dialog; +import android.content.Intent; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.design.widget.BottomNavigationView; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentTransaction; +import android.support.v7.widget.Toolbar; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.data.db.entities.Packing; +import com.peacecorps.malaria.ui.base.BaseActivity; +import com.peacecorps.malaria.ui.home_screen.HomeScreenFragment; +import com.peacecorps.malaria.ui.main.MainContract.IHomeView; +import com.peacecorps.malaria.ui.info_hub.InfoHubFragment; +import com.peacecorps.malaria.ui.medicine_store.MedicineStoreActivity; +import com.peacecorps.malaria.ui.play.PlayFragment; +import com.peacecorps.malaria.ui.trip_reminder.PlanTripFragment; +import com.peacecorps.malaria.ui.trip_reminder.PlanTripFragment.OnPlanFragmentListener; +import com.peacecorps.malaria.ui.trip_reminder.trip_select_item.ItemDialogFragment; +import com.peacecorps.malaria.ui.trip_reminder.trip_select_item.ItemDialogFragment.OnSaveDialogListener; +import com.peacecorps.malaria.ui.user_medicine_setting.MedicineSettingsActivity; +import com.peacecorps.malaria.ui.user_profile.ProfileFragment; +import com.peacecorps.malaria.utils.BottomNavigationViewHelper; +import com.peacecorps.malaria.utils.InjectionClass; + +public class MainActivity extends BaseActivity implements IHomeView, + OnPlanFragmentListener, OnSaveDialogListener { + + private Toolbar toolbar; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + if (savedInstanceState == null) { + Fragment fragment = new HomeScreenFragment(); + loadFragment(fragment); + } + init(); + } + + @Override + public void init() { + // setting up presenter and attaching views + AppDataManager dataManager = InjectionClass.provideDataManager(this); + MainPresenter presenter = new MainPresenter<>(dataManager, this); + presenter.attachView(this); + + toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + // adding ic_launcher icon to the Toolbar + if (getSupportActionBar() != null) { + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_launcher); + } + + //setting up bottom navigation + setBottomNavigation(); + } + + @Override + protected void onStop() { + super.onStop(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + } + + private void setBottomNavigation() { + BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation); + // disables moving/shifting mode (by default available for >3 items in bottom navigation) for application + BottomNavigationViewHelper.disableShiftMode(bottomNavigationView); + + // set home icon to be default selected & add Home screen fragment in Frame layout + bottomNavigationView.setSelectedItemId(R.id.home_screen_fragment); + bottomNavigationView.getMenu().findItem(R.id.bnv_home).setChecked(true); + + + // listener implementation for bottom navigation, replaces frame layout with different fragments + bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { + @Override + public boolean onNavigationItemSelected(@NonNull MenuItem item) { + Fragment fragment; + switch (item.getItemId()) { + case R.id.bnv_home: + fragment = new HomeScreenFragment(); + toolbar.setTitle(getString(R.string.app_name)); + loadFragment(fragment); + break; + + case R.id.bnv_trip_button: + fragment = new PlanTripFragment(); + toolbar.setTitle("Trip details"); + loadFragment(fragment); + break; + + case R.id.bnv_info_button: + fragment = new InfoHubFragment(); + toolbar.setTitle("Information hub"); + loadFragment(fragment); + break; + + case R.id.bnv_play_button: + fragment = new PlayFragment(); + toolbar.setTitle("Game screen"); + loadFragment(fragment); + break; + + case R.id.bnv_user_profile: + fragment = new ProfileFragment(); + toolbar.setTitle("Profile"); + loadFragment(fragment); + break; + default: + fragment = new HomeScreenFragment(); + loadFragment(fragment); + } + return true; + } + }); + } + + /** + * @param fragment : replaces frame layout with parameter received in main activity + */ + private void loadFragment(Fragment fragment) { + // load fragment + FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); + transaction.replace(R.id.frame_container, fragment, ""); + transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); + transaction.addToBackStack(null); + transaction.commit(); + } + + + // reset button to create a dialog & if clicked okay, delete all data & start User medicine settings activity + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() == R.id.btn_menu_reset) { + // creating dialog to display + final Dialog dialog; + dialog = new Dialog(this, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar); + dialog.setContentView(R.layout.resetdata_dialog); + dialog.setTitle("Reset Data"); + // reset database & dismiss dialog + dialog.findViewById(R.id.btn_dialog_reset_okay).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + + dialog.dismiss(); + + } + }); + // dismiss dialog + dialog.findViewById(R.id.btn_dialog_reset_cancel).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + dialog.dismiss(); + } + }); + dialog.show(); + return true; + } else if(item.getItemId() == R.id.btn_menu_store) { + startActivity(new Intent(MainActivity.this, MedicineStoreActivity.class)); + return true; + } + return super.onOptionsItemSelected(item); + } + + // inflates the main_menu which contains "reset button for action" + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.main_menu, menu); + return true; + } + + // replaces trip fragment with select item fragment + @Override + public void startSelectItemFragment(long quantity) { + FragmentManager fragmentManager = getSupportFragmentManager(); + ItemDialogFragment newFragment = ItemDialogFragment.newInstance(quantity); + + // using a large layout, so show the fragment as a dialog + FragmentTransaction transaction = fragmentManager.beginTransaction(); + // For a little polish, specify a transition animation + transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); + transaction.add(android.R.id.content, newFragment) + .addToBackStack(null).commit(); + + } + + @Override + public void passMedicineSelected(Packing packing) { + Fragment fragmentInFrame = getSupportFragmentManager() + .findFragmentById(R.id.frame_container); + if (fragmentInFrame instanceof PlanTripFragment) { + PlanTripFragment tripFragment = (PlanTripFragment) fragmentInFrame; + tripFragment.updateSelectItemText(packing.getPackingItem() + ":" + packing.getPackingQuantity()); + } + } + + @Override + public void startMedicineSettingActivity() { + Intent intent = new Intent(this, MedicineSettingsActivity.class); + startActivity(intent); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/main/MainContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/main/MainContract.java new file mode 100644 index 00000000..57998306 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/main/MainContract.java @@ -0,0 +1,13 @@ +package com.peacecorps.malaria.ui.main; + +import com.peacecorps.malaria.ui.base.MvpView; + +public interface MainContract { + interface IHomeView extends MvpView { + void startMedicineSettingActivity(); + } + + interface IHomePresenter { + void resetDatabase(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/main/MainPresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/main/MainPresenter.java new file mode 100644 index 00000000..7df0ee9f --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/main/MainPresenter.java @@ -0,0 +1,20 @@ +package com.peacecorps.malaria.ui.main; + +import android.content.Context; + +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.main.MainContract.IHomePresenter; + +public class MainPresenter extends BasePresenter implements IHomePresenter { + + MainPresenter(AppDataManager manager, Context context) { + super(manager, context); + } + + @Override + public void resetDatabase() { + //Todo reset preferences too + getDataManager().resetDatabase(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStoreActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStoreActivity.java new file mode 100644 index 00000000..5d14d3b8 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStoreActivity.java @@ -0,0 +1,69 @@ +package com.peacecorps.malaria.ui.medicine_store; + +import android.os.Bundle; +import android.support.annotation.Nullable; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentTransaction; +import android.support.v7.widget.Toolbar; +import android.view.MenuItem; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseActivity; + +/** + * Created by Anamika Tripathi on 12/8/18. + */ +public class MedicineStoreActivity extends BaseActivity { + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_medicine_store); + init(); + } + + + @Override + protected void init() { + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + toolbar.setTitle("Medicine Store"); + if (getSupportActionBar() != null) { + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + + Fragment fragment = new MedicineStoreFragment(); + loadFragment(fragment); + } + + + /** + * @param fragment : replaces frame layout with parameter received in main activity + */ + private void loadFragment(Fragment fragment) { + // load fragment + FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); + transaction.replace(R.id.medicine_store_container, fragment, "medicine store"); + transaction.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK); + transaction.addToBackStack(null); + transaction.commit(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == android.R.id.home) { + // close activity + finish(); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + finish(); + } + +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStoreContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStoreContract.java new file mode 100644 index 00000000..a208799b --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStoreContract.java @@ -0,0 +1,26 @@ +package com.peacecorps.malaria.ui.medicine_store; + +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +/** + * Created by Anamika Tripathi on 18/7/18. + */ +public interface MedicineStoreContract { + interface MedicineMvpView extends MvpView { + void displayMedicineStoreValues(String drugName, String daysLeft); + } + + interface MedicineMvpPresenter extends MvpPresenter { + void checkMedicineStore(); + boolean checkMedicineNumberValidity(String text); + boolean testIsEmpty(String text); + void updateMedicineStoreValue(String text); + int getMedicineStoreValue(); + String getMessageBodyForOrder(); + boolean isDrugWeekly(); + int getAlertReminderNumber(); + boolean checkAlertReminderValidity(String text); + void updateAlertReminder(int number); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStoreFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStoreFragment.java new file mode 100644 index 00000000..117813ec --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStoreFragment.java @@ -0,0 +1,213 @@ +package com.peacecorps.malaria.ui.medicine_store; + +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.telephony.SmsManager; +import android.text.Html; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.EditText; +import android.widget.TextView; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.ui.medicine_store.MedicineStoreContract.MedicineMvpView; +import com.peacecorps.malaria.utils.InjectionClass; + +import butterknife.BindView; +import butterknife.ButterKnife; +import butterknife.OnClick; + +/** + * Created by Anamika Tripathi on 18/7/18. + */ +public class MedicineStoreFragment extends BaseFragment implements MedicineMvpView { + + @BindView(R.id.tv_medicine_name) + TextView medicineName; + @BindView(R.id.tv_days_left) + TextView daysLeft; + private Context context; + private MedicineStorePresenter presenter; + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.medicine_store, container, false); + // set up butterknife + ButterKnife.bind(this, view); + context = getContext(); + // set up presenter, passing datamanger and context & attaching view to presenter + presenter = new MedicineStorePresenter<>(InjectionClass.provideDataManager(context), context); + presenter.attachView(this); + return view; + } + + @Override + protected int getContentResource() { + return R.layout.medicine_store; + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + init(); + } + + @Override + protected void init() { + presenter.checkMedicineStore(); + } + + @Override + public void displayMedicineStoreValues(String drugName, String days) { + medicineName.setText(drugName); + daysLeft.setText(days); + } + + @OnClick(R.id.btn_add_medicine) + public void addMedicineListener() { + final Dialog addMedicineDialog = new Dialog(context, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar); + addMedicineDialog.setContentView(R.layout.add_medicine_dialog); + + // Setting Dialog Title + final EditText medicineQuantityEt = addMedicineDialog.findViewById(R.id.add_medicine_quantity); + addMedicineDialog.findViewById(R.id.add_medicine_quantity).requestFocus(); + addMedicineDialog.findViewById(R.id.btn_dialog_add_medicine).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (presenter.checkMedicineNumberValidity(medicineQuantityEt.getText().toString().trim())) { + presenter.updateMedicineStoreValue(medicineQuantityEt.getText().toString().trim()); + addMedicineDialog.dismiss(); + } else { + medicineQuantityEt.setError("Quantity Required"); + medicineQuantityEt.requestFocus(); + } + } + }); + addMedicineDialog.findViewById(R.id.btn_dialog_cancel).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + addMedicineDialog.dismiss(); + } + }); + + // Showing Alert Message + addMedicineDialog.show(); + } + + @OnClick(R.id.btn_order_medicine) + public void orderMedicineListener() { + final Dialog orderMedicineDialog = new Dialog(context, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar); + orderMedicineDialog.setContentView(R.layout.order_medicine_dialog); + + // Setting Dialog Title + final EditText quantity = orderMedicineDialog.findViewById(R.id.btn_order_quantity); + + orderMedicineDialog.findViewById(R.id.btn_order_quantity).requestFocus(); + + //implement the email button + orderMedicineDialog.findViewById(R.id.btn_order_by_email).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (presenter.checkMedicineNumberValidity(quantity.getText().toString().trim())) { + + Intent emailIntent = new Intent(Intent.ACTION_SEND); + emailIntent.setData(Uri.parse("mailto:")); + emailIntent.setType("text/plain"); + emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"anamikatripathi1601@gmail.com", "yatna.verma.ece13@itbhu.ac.in"}); + emailIntent.putExtra(Intent.EXTRA_SUBJECT, "URGENT: Reqiured Malaria Medicines"); + emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml( + presenter.getMessageBodyForOrder() + + "" + Integer.parseInt(quantity.getText().toString()) + "")); + startActivity(Intent.createChooser(emailIntent, "Send mail via...")); + orderMedicineDialog.dismiss(); + + } else { + //send and email + quantity.setError("Quantity Required"); + quantity.requestFocus(); + + } + } + }); + //implement the message button + //Todo ask for SEND Message permission + orderMedicineDialog.findViewById(R.id.btn_order_by_msg).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (presenter.checkMedicineNumberValidity(quantity.getText().toString().trim())) { + quantity.setError("Quantity Required"); + } else { + SmsManager smsManager = SmsManager.getDefault(); + smsManager.sendTextMessage("123", null, + presenter.getMessageBodyForOrder() + + Integer.parseInt(quantity.getText().toString()), null, null); + orderMedicineDialog.dismiss(); + } + } + }); + + // Showing Alert Message + orderMedicineDialog.show(); + } + + // setting button listener in medicine store fragment + @OnClick(R.id.btn_dialog_setting) + public void settingDialogListener() { + + final Dialog settingsDialog = new Dialog(context, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar); + settingsDialog.setContentView(R.layout.reminder_screen_setting_dialog); + + // Setting Dialog Title + final EditText time = settingsDialog.findViewById(R.id.time); + settingsDialog.findViewById(R.id.time).requestFocus(); + TextView warningTv = settingsDialog.findViewById(R.id.warning_textview); + + //if drug is weekly + if (presenter.isDrugWeekly()) { + warningTv.setText(R.string.warning_reminder_weeks); + } + //if drug is daily + else { + warningTv.setText(R.string.warning_reminder_days); + } + + //get previous value if any + final int prevAlertTime = presenter.getAlertReminderNumber(); + //fill editText with previous set values + if (prevAlertTime != -1) { + time.setText(String.valueOf(prevAlertTime)); + } + settingsDialog.findViewById(R.id.set).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (presenter.checkAlertReminderValidity(time.getText().toString().trim())) { + presenter.updateAlertReminder(Integer.parseInt(time.getText().toString())); + //Todo add a reminder as per input + settingsDialog.dismiss(); + } else { + + time.setError(getString(R.string.error_store_alert_reminder)); + time.requestFocus(); + } + } + }); + settingsDialog.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + settingsDialog.dismiss(); + } + }); + + // Showing Alert Message + settingsDialog.show(); + + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStorePresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStorePresenter.java new file mode 100644 index 00000000..89149f30 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/medicine_store/MedicineStorePresenter.java @@ -0,0 +1,125 @@ +package com.peacecorps.malaria.ui.medicine_store; + +import android.content.Context; +import android.text.TextUtils; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.medicine_store.MedicineStoreContract.MedicineMvpPresenter; +import com.peacecorps.malaria.ui.medicine_store.MedicineStoreContract.MedicineMvpView; + +/** + * Created by Anamika Tripathi on 18/7/18. + */ +public class MedicineStorePresenter extends BasePresenter implements MedicineMvpPresenter { + + MedicineStorePresenter(AppDataManager manager, Context context) { + super(manager, context); + } + + @Override + public void attachView(V view) { + super.attachView(view); + } + + @Override + public void detachView() { + super.detachView(); + } + + // check if drug is weekly or daily and calls displayMedicineStoreValues with drugName(by prefernces) and daysLeft + @Override + public void checkMedicineStore() { + int store = getDataManager().getMedicineStoreValue(); + String drugName = getDataManager().getDrugPicked(); + String daysLeft; + //if drug is weekly + if (drugName.compareTo(getContext().getResources().getString(R.string.med_option_three)) == 0) { + if (store >= 0) { + daysLeft = store + " Weeks"; + } else { + store = store * -1; + daysLeft = store + " Weeks Due"; + } + } else { + //if drug is daily + if (store >= 0) { + daysLeft = store + " Days"; + } else { + store = store * -1; + daysLeft = store + " Days Due"; + } + } + getView().displayMedicineStoreValues(drugName, daysLeft); + } + + @Override + public boolean checkMedicineNumberValidity(String text) { + if (testIsEmpty(text)) + return false; + int num = Integer.valueOf(text); + return num > 0 && num <= 500; + + } + + @Override + public boolean testIsEmpty(String text) { + return TextUtils.isEmpty(text); + } + + // updates total medicine left in store and calls checkMedicineStore for UI update + @Override + public void updateMedicineStoreValue(String text) { + int quantity = Integer.parseInt(text); + int currValue = getDataManager().getMedicineStoreValue(); + getDataManager().setMedicineStoreValue(currValue + quantity); + checkMedicineStore(); + } + + @Override + public int getMedicineStoreValue() { + return getDataManager().getMedicineStoreValue(); + } + + // creates message body and returns it as a string + @Override + public String getMessageBodyForOrder() { + int storeValue = getMedicineStoreValue(); + String flag; + if (getDataManager().isDosesWeekly()) { + flag = "weeks"; + } else { + flag = "days"; + } + + return "My malaria pills will last for the coming " + "" + storeValue + "" + " " + + flag + " only.
Send the following immediately:
" + + "Medicine Name: " + "" + getDataManager().getDrugPicked() + "" + "
" + + "Quantity: "; + } + + @Override + public boolean isDrugWeekly() { + return getDataManager().isDosesWeekly(); + } + + @Override + public int getAlertReminderNumber() { + return getDataManager().getAlertNumberDaysOrWeeks(); + } + + // checking if entered number is valid or not, putting a maximum 30days advance reminder + @Override + public boolean checkAlertReminderValidity(String text) { + if (testIsEmpty(text)) + return false; + int num = Integer.valueOf(text); + return num > 0 && num <= 30; + } + + @Override + public void updateAlertReminder(int number) { + getDataManager().setAlertNumberDaysOrWeeks(number); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/PlayFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/PlayFragment.java new file mode 100644 index 00000000..3fefd90e --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/PlayFragment.java @@ -0,0 +1,66 @@ +package com.peacecorps.malaria.ui.play; + +import android.content.Intent; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.ui.play.myth_vs_fact.MythFactActivity; +import com.peacecorps.malaria.ui.play.rapid_fire.RapidFireActivity; + +import butterknife.ButterKnife; +import butterknife.OnClick; + +/** + * Created by Anamika Tripathi on 18/7/18. + */ +public class PlayFragment extends BaseFragment { + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_play, container, false); + // butter knife binding + ButterKnife.bind(this, view); + return view; + } + + @Override + protected int getContentResource() { + return R.layout.fragment_play; + } + + // listener for badge button in play fragment + @OnClick(R.id.btn_myth_vs_fact) + public void mythVsFactListener(View view) { + // start MythFactActivity + startActivity(new Intent(getContext(), MythFactActivity.class)); + } + + // listener for rapid fire button in play fragment + @OnClick(R.id.btn_rapid_fire) + public void rapidFireListener(View view) { + // start Rapid fire activity + startActivity(new Intent(getContext(), RapidFireActivity.class)); + } + + @Override + protected void init() { + + } + + // setting null values to the listener, presenter + @Override + public void onDetach() { + super.onDetach(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactActivity.java new file mode 100644 index 00000000..7308e949 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactActivity.java @@ -0,0 +1,72 @@ +package com.peacecorps.malaria.ui.play.myth_vs_fact; + +import android.os.Bundle; +import android.support.annotation.Nullable; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentTransaction; +import android.support.v7.widget.Toolbar; +import android.view.MenuItem; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseActivity; + +/** + * Created by Anamika Tripathi on 13/8/18. + */ +public class MythFactActivity extends BaseActivity implements MythFactFragment.OnMythFragmentListener { + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_myth_fact); + init(); + } + + @Override + protected void init() { + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + toolbar.setTitle("Myth Vs Fact"); + if (getSupportActionBar() != null) { + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + + Fragment fragment = new MythFactFragment(); + loadFragment(fragment); + } + + /** + * @param fragment : replaces frame layout with parameter received in main activity + */ + private void loadFragment(Fragment fragment) { + // load fragment + FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); + transaction.replace(R.id.myth_fact_container, fragment, ""); + transaction.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK); + transaction.addToBackStack(null); + transaction.commit(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == android.R.id.home) { + // close activity + finish(); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + finish(); + } + + @Override + public void goBackToPlayFragment() { + finish(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactContract.java new file mode 100644 index 00000000..07f9e33d --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactContract.java @@ -0,0 +1,18 @@ +package com.peacecorps.malaria.ui.play.myth_vs_fact; + +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +/** + * Created by Anamika Tripathi on 18/7/18. + */ +public interface MythFactContract { + interface MythFactMvpView extends MvpView { + void playTapTargetViewer(); + } + + interface MythFactMvpPresenter extends MvpPresenter { + void updateGameScore(int currPoints); + void checkFirstTime(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactFragment.java new file mode 100644 index 00000000..89921f97 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactFragment.java @@ -0,0 +1,354 @@ +package com.peacecorps.malaria.ui.play.myth_vs_fact; + +import android.annotation.SuppressLint; +import android.content.ClipData; +import android.content.Context; +import android.content.DialogInterface; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.v7.app.AlertDialog; +import android.view.DragEvent; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.TextView; + +import com.getkeepsafe.taptargetview.TapTarget; +import com.getkeepsafe.taptargetview.TapTargetSequence; +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.ui.play.myth_vs_fact.MythFactContract.MythFactMvpView; +import com.peacecorps.malaria.utils.InjectionClass; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import java.util.Arrays; +import java.util.List; + +import butterknife.BindView; +import butterknife.ButterKnife; +import butterknife.OnClick; + +/** + * Created by Anamika Tripathi on 18/7/18. + */ +public class MythFactFragment extends BaseFragment implements MythFactMvpView { + + private Context context; + private List questions, answers; + @BindView(R.id.tv_total_score) + TextView tvUserPoints; + @BindView(R.id.tv_question) + TextView tvQuestion; + @BindView(R.id.btn_next) + Button nextButton; + @BindView(R.id.btn_exit) + Button exitButton; + @BindView(R.id.chest) + TextView chest; + @BindView(R.id.trash) + TextView trash; + private int points = 0, i = 0; + private MythFactPresenter presenter; + private OnMythFragmentListener listener; + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.myth_fact_game, container, false); + context = getContext(); + ButterKnife.bind(this, view); + presenter = new MythFactPresenter<>(InjectionClass.provideDataManager(context), context); + presenter.attachView(this); + return view; + } + + @Override + protected int getContentResource() { + return R.layout.myth_fact_game; + } + + @SuppressLint("ClickableViewAccessibility") + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + //set touch listeners + tvQuestion.setOnTouchListener(new ChoiceTouchListener()); + //set drag listeners + trash.setOnDragListener(new ChoiceDragListener()); + chest.setOnDragListener(new ChoiceDragListener()); + init(); + } + + @Override + protected void init() { + presenter.checkFirstTime(); + //setup questions + questions = Arrays.asList(getResources().getStringArray(R.array.array_myth_vs_fact_questions)); + //setup answers + answers = Arrays.asList(getResources().getStringArray(R.array.array_myth_vs_fact_answers)); + //initialize game score + tvUserPoints.setText(String.valueOf(points)); + //initial question + tvQuestion.setText(questions.get(i)); + //disable the next Button + nextButton.setClickable(false); + nextButton.setBackground(getResources().getDrawable(R.drawable.info_hub_button_grayed)); + } + + @OnClick(R.id.btn_next) + public void nextButtonListener() { + i = i + 1; + if (i < questions.size()) { + tvQuestion.setText(questions.get(i)); + setUpButton(); + } else { + // create a dialog with AlertDialog builder, set appropriate title & message + AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.MyDialogTheme); + builder.setTitle(getString(R.string.label_game_over)); + builder.setMessage(getString(R.string.description_wait_for_new_ques)); + + String positiveText = getString(android.R.string.ok); + builder.setPositiveButton(positiveText, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // dismiss the dialog, update game score in preference, starts play fragment again + // update game score to preferences + presenter.updateGameScore(points); + dialog.dismiss(); + listener.goBackToPlayFragment(); + } + }); + + AlertDialog dialog = builder.create(); + // display dialog + dialog.show(); + } + } + + // set up tvQuestion, trash, chest, next Button, called after question + private void setUpButton() { + trash.setText(""); + chest.setText(""); + tvQuestion.setVisibility(View.VISIBLE); + nextButton.setClickable(false); + nextButton.setBackground(getResources().getDrawable(R.drawable.info_hub_button_grayed)); + chest.setBackground(getResources().getDrawable(R.drawable.chest)); + trash.setBackground(getResources().getDrawable(R.drawable.trash)); + } + + @OnClick(R.id.btn_exit) + public void exitButtonListener() { + + AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.MyDialogTheme); + builder.setTitle(getString(R.string.label_exit_game)); + builder.setMessage(getString(R.string.description_sure_exit_game)); + + String positiveText = getString(android.R.string.ok); + builder.setPositiveButton(positiveText, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // dismiss alert dialog, update preferences with game score and restart play fragment + presenter.updateGameScore(points); + dialog.dismiss(); + listener.goBackToPlayFragment(); + } + }); + + String negativeText = getString(android.R.string.cancel); + builder.setNegativeButton(negativeText, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + // negative button logic + } + }); + + AlertDialog dialog = builder.create(); + // display dialog + dialog.show(); + } + + private class ChoiceTouchListener implements View.OnTouchListener { + @Override + public boolean onTouch(View v, MotionEvent motionEvent) { + if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { + //setup drag + ClipData data = ClipData.newPlainText("", ""); + //create shadow while being dragged + View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v); + //start dragging the item touched + v.startDrag(data, shadowBuilder, v, 0); + return true; + } else { + v.performClick(); + return false; + } + } + } + + private class ChoiceDragListener implements View.OnDragListener { + @Override + public boolean onDrag(View v, DragEvent event) { + switch (event.getAction()) { + case DragEvent.ACTION_DROP: + //handle the dragged view being dropped over a target view + View view = (View) event.getLocalState(); + //stop displaying the view where it was before it was dragged + view.setVisibility(View.INVISIBLE); + //view dragged item is being dropped on + TextView dropTarget = (TextView) v; + //update the text in the target view to reflect the data being dropped + switch (dropTarget.getId()) { + case R.id.chest: + if (answers.get(i).compareTo(getString(R.string.fact)) == 0) { + dropTarget.setText(getString(R.string.label_correct)); + chest.setBackgroundColor(getResources().getColor(R.color.transparent)); + points++; + } else { + dropTarget.setText(R.string.wrong); + chest.setBackgroundColor(getResources().getColor(R.color.transparent)); + } + break; + case R.id.trash: + if (answers.get(i).compareTo(getString(R.string.myth)) == 0) { + dropTarget.setText(getString(R.string.label_correct)); + trash.setBackgroundColor(getResources().getColor(R.color.transparent)); + points++; + } else { + dropTarget.setText(R.string.wrong); + trash.setBackgroundColor(getResources().getColor(R.color.transparent)); + } + break; + default: + ToastLogSnackBarUtil.showToast(context, "Wrong Drop!"); + } + //enable the next button + nextButton.setClickable(true); + nextButton.setBackground(getResources().getDrawable(R.drawable.button_background)); + tvUserPoints.setText(getString(R.string.label_myth_fact_total_score, points)); + break; + case DragEvent.ACTION_DRAG_ENDED: + //no action necessary + break; + default: + break; + } + return true; + } + } + + public interface OnMythFragmentListener { + void goBackToPlayFragment(); + } + + // Container Activity must implement this interface + @Override + public void onAttach(Context context) { + super.onAttach(context); + // This makes sure that the container activity has implemented + // the callback interface. If not, it throws an exception + if (context instanceof OnMythFragmentListener) { + listener = (OnMythFragmentListener) context; + } else { + // Show error Log for debugging & display snackbar to user + ToastLogSnackBarUtil.showErrorLog(context.toString() + " must implement OnMythFragmentListener"); + if (getActivity() != null) { + ToastLogSnackBarUtil.showSnackBar(context, getActivity().findViewById(android.R.id.content), + "Something went wrong!"); + } + } + } + + // setting null values to the listener, presenter + @Override + public void onDetach() { + super.onDetach(); + listener = null; + } + + + @Override + public void playTapTargetViewer() { + new TapTargetSequence(getActivity()) + .continueOnCancel(true) + .targets( + TapTarget.forView(tvQuestion, getString(R.string.help_myth_fact_question_title), + getString(R.string.help_myth_fact_question_description)) + .drawShadow(true) + .tintTarget(true) + .targetRadius(60) + .titleTextColor(R.color.textColorPrimary) + .descriptionTextColor(R.color.white) + .targetCircleColor(R.color.colorAccent) + .outerCircleAlpha(0.90f).id(3), + TapTarget.forView(chest, getString(R.string.help_myth_fact_chest_title), + "") + .drawShadow(true) + .tintTarget(true) + .titleTextColor(R.color.textColorPrimary) + .descriptionTextColor(R.color.white) + .targetRadius(60) + .targetCircleColor(R.color.colorAccent) + .outerCircleAlpha(0.90f).id(3), + TapTarget.forView(trash, getString(R.string.help_myth_fact_bin_title), + "") + .drawShadow(true) + .tintTarget(true) + .titleTextColor(R.color.textColorPrimary) + .descriptionTextColor(R.color.white) + .targetRadius(60) + .targetCircleColor(R.color.colorAccent) + .outerCircleAlpha(0.90f).id(3), + TapTarget.forView(tvUserPoints, getString(R.string.help_myth_fact_score_title), + "") + .drawShadow(true) + .tintTarget(true) + .titleTextColor(R.color.textColorPrimary) + .descriptionTextColor(R.color.white) + .targetRadius(60) + .targetCircleColor(R.color.colorAccent) + .outerCircleAlpha(0.90f).id(3), + TapTarget.forView(nextButton, getString(R.string.help_myth_fact_next_title), + getString(R.string.help_myth_fact_next_description)) + .drawShadow(true) + .tintTarget(true) + .titleTextColor(R.color.textColorPrimary) + .descriptionTextColor(R.color.white) + .targetRadius(60) + .targetCircleColor(R.color.colorAccent) + .outerCircleAlpha(0.90f).id(3), + TapTarget.forView(exitButton, getString(R.string.help_myth_fact_exit_title), + "") + .drawShadow(true) + .tintTarget(true) + .titleTextColor(R.color.textColorPrimary) + .descriptionTextColor(R.color.white) + .targetRadius(60) + .targetCircleColor(R.color.colorAccent) + .outerCircleAlpha(0.90f).id(3) + ) + .listener(new TapTargetSequence.Listener() { + @Override + public void onSequenceFinish() { + presenter.getDataManager().setMythFactTarget(true); + } + + @Override + public void onSequenceStep(TapTarget lastTarget, boolean targetClicked) { + // no need currently, compulsory overridden method + } + + @Override + public void onSequenceCanceled(TapTarget lastTarget) { + // no need currently, compulsory overridden method + } + }).start(); + } + +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactPresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactPresenter.java new file mode 100644 index 00000000..7b3e6f30 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/myth_vs_fact/MythFactPresenter.java @@ -0,0 +1,31 @@ +package com.peacecorps.malaria.ui.play.myth_vs_fact; + +import android.content.Context; + +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.play.myth_vs_fact.MythFactContract.MythFactMvpPresenter; +import com.peacecorps.malaria.ui.play.myth_vs_fact.MythFactContract.MythFactMvpView; + +/** + * Created by Anamika Tripathi on 18/7/18. + */ +public class MythFactPresenter extends BasePresenter implements MythFactMvpPresenter { + MythFactPresenter(AppDataManager manager, Context context) { + super(manager, context); + } + + // updates preferences with current game score points + @Override + public void updateGameScore(int currPoints) { + int oldPoints = getDataManager().getGameScore(); + getDataManager().setGameScore(oldPoints + currPoints); + } + + @Override + public void checkFirstTime() { + if(!getDataManager().checkMythFactTarget()) { + getView().playTapTargetViewer(); + } + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/QuestionModel.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/QuestionModel.java new file mode 100644 index 00000000..c932a313 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/QuestionModel.java @@ -0,0 +1,37 @@ +package com.peacecorps.malaria.ui.play.rapid_fire; + +/** + * Created by yatna on 10/6/16. + */ +// Used by RapidFirePresenter to prepare list of question, it's options and answers +public class QuestionModel { + private String question; + private String option1; + private String option2; + private String option3; + private int ans; + //constructs a question model for Rapid Fire game + public QuestionModel(String question, String option1, String option2, String option3, int ans){ + this.question=question; + this.option1=option1; + this.option2=option2; + this.option3=option3; + this.ans=ans; + } + //getters + public String getQuestion(){ + return question; + } + public String getOption1(){ + return option1; + } + public String getOption2(){ + return option2; + } + public String getOption3(){ + return option3; + } + public int getAns(){ + return ans; + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFireActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFireActivity.java new file mode 100644 index 00000000..c01698df --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFireActivity.java @@ -0,0 +1,71 @@ +package com.peacecorps.malaria.ui.play.rapid_fire; + +import android.os.Bundle; +import android.support.annotation.Nullable; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentTransaction; +import android.support.v7.widget.Toolbar; +import android.view.MenuItem; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseActivity; + +/** + * Created by Anamika Tripathi on 13/8/18. + */ +public class RapidFireActivity extends BaseActivity implements RapidFireFragment.OnRapidFragmentListener { + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_rapid_fire); + init(); + } + + @Override + protected void init() { + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + toolbar.setTitle("Rapid Fire"); + if (getSupportActionBar() != null) { + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + + Fragment fragment = new RapidFireFragment(); + loadFragment(fragment); + } + + /** + * @param fragment : replaces frame layout with parameter received in main activity + */ + private void loadFragment(Fragment fragment) { + // load fragment + FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); + transaction.replace(R.id.rapid_fire_container, fragment, ""); + transaction.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK); + transaction.addToBackStack(null); + transaction.commit(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == android.R.id.home) { + // close activity + finish(); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + finish(); + } + + @Override + public void goBackToPlayFragment() { + finish(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFireContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFireContract.java new file mode 100644 index 00000000..ad0c1805 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFireContract.java @@ -0,0 +1,25 @@ +package com.peacecorps.malaria.ui.play.rapid_fire; + +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +/** + * Created by Anamika Tripathi on 19/7/18. + */ +public interface RapidFireContract { + interface RapidFireMvpView extends MvpView { + void setButtonBackground(); + void prepareQuestionAndOptions(); + void enableOptions(boolean val); + void updateTimer(long miliLeft); + void playTapTargetViewer(); + } + + interface RapidFireMvpPresenter extends MvpPresenter { + void prepareQuestionList(int num); + int questionListSize(); + QuestionModel getQuestionModel(int i); + void updateGameScore(int currPoints); + void checkFirstTime(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFireFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFireFragment.java new file mode 100644 index 00000000..57bea70d --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFireFragment.java @@ -0,0 +1,428 @@ +package com.peacecorps.malaria.ui.play.rapid_fire; + +import android.content.Context; +import android.content.DialogInterface; +import android.os.Bundle; +import android.os.CountDownTimer; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.v7.app.AlertDialog; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.TextView; + +import com.getkeepsafe.taptargetview.TapTarget; +import com.getkeepsafe.taptargetview.TapTargetSequence; +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.ui.play.rapid_fire.RapidFireContract.RapidFireMvpView; +import com.peacecorps.malaria.utils.InjectionClass; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import butterknife.BindView; +import butterknife.ButterKnife; +import butterknife.OnClick; + +/** + * Created by Anamika Tripathi on 19/7/18. + */ +@SuppressWarnings("NonAtomicOperationOnVolatileField") +public class RapidFireFragment extends BaseFragment implements RapidFireMvpView { + // used for saving values in saveInstanceState + private static final String COUNTER_MILLIS_LEFT = "COUNTER_MILLIS_LEFT"; + private static final String GAME_SCORE = "GAME_SCORE"; + private static final String QUES_NO = "QUES_NO"; + // options for game + @BindView(R.id.btn_rapid_option_one) + Button optionOne; + @BindView(R.id.btn_rapid_option_two) + Button optionTwo; + @BindView(R.id.btn_rapid_option_three) + Button optionThree; + // question text view + @BindView(R.id.tv_rapid_question) + TextView tvQuestion; + // displays game score + @BindView(R.id.tv_score) + TextView totalScore; + // timer textView + @BindView(R.id.tv_timers) + TextView timerView; + @BindView(R.id.btn_rapid_fire_exit) + Button exitButton; + + private RapidFirePresenter presenter; + private Context context; + // keeps count of current question number, volatile (variable getting updated across threads) + private volatile int quesNo; + // used for timer + private volatile long millisLeft; + // saves game score + private int gameScore; + private RapidFireTimeCounter counter; + private long timerCount; + private OnRapidFragmentListener listener; + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.rapid_fire, container, false); + // butterknife binding + ButterKnife.bind(this, view); + context = getContext(); + // instantiating presenter, passing datamanger, view & attaching view to the presenter + presenter = new RapidFirePresenter<>(InjectionClass.provideDataManager(context), context); + presenter.attachView(this); + return view; + } + + @Override + protected int getContentResource() { + return R.layout.rapid_fire; + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + init(); + setGameScore(); + //displays the time left for the next question + updateTimer(millisLeft / 1000); + //presenter.prepareQuestionList(quesNo); + } + + // option one for game listener + @OnClick(R.id.btn_rapid_option_one) + public void optionOneListener() { + // stops counter + counter.cancel(); + // checks if correct answers for the current quesNO is 1 or not + if (presenter.getQuestionModel(quesNo).getAns() == 1) { + // increment game score, set button background to green to display right answers + gameScore++; + optionOne.setBackgroundColor(getResources().getColor(R.color.light_green)); + } else { + optionOne.setBackground(getResources().getDrawable(R.color.colorAccent)); + } + + // disable all buttons till next question is displayed + enableOptions(false); + prepNextQues(); + } + + // option two for game listener + @OnClick(R.id.btn_rapid_option_two) + public void optionTwoListener() { + // stops counter + counter.cancel(); + // checks if correct answers for the current quesNO is 2 or not + if (presenter.getQuestionModel(quesNo).getAns() == 2) { + // increment game score, set button background to green to display right answers else red background + gameScore++; + optionTwo.setBackgroundColor(getResources().getColor(R.color.light_green)); + } else { + optionTwo.setBackground(getResources().getDrawable(R.color.colorAccent)); + } + // disable all buttons till next question is displayed + enableOptions(false); + prepNextQues(); + } + + // option three for game listener + @OnClick(R.id.btn_rapid_option_three) + public void optionThreeListener() { + // stops counter + counter.cancel(); + // checks if correct answers for the current quesNO is 3 or not + if (presenter.getQuestionModel(quesNo).getAns() == 3) { + // increment game score, set button background to green to display right answers else red background + gameScore++; + optionThree.setBackgroundColor(getResources().getColor(R.color.light_green)); + } else { + optionThree.setBackground(getResources().getDrawable(R.color.colorAccent)); + } + // disable all buttons till next question is displayed + enableOptions(false); + prepNextQues(); + + } + + @OnClick(R.id.btn_rapid_fire_exit) + public void exitGameListener() { + // stops counter + counter.cancel(); + // create a dialog with AlertDialog builder + AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.MyDialogTheme); + builder.setTitle(getString(R.string.label_exit_game)); + builder.setMessage(getString(R.string.description_sure_exit_game)); + + String positiveText = getString(android.R.string.ok); + builder.setPositiveButton(positiveText, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // dismiss alert dialog, update preferences with game score and restart play fragment + presenter.updateGameScore(gameScore); + listener.goBackToPlayFragment(); + dialog.dismiss(); + } + }); + + String negativeText = getString(android.R.string.cancel); + builder.setNegativeButton(negativeText, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // dismiss dialog, start counter again + dialog.dismiss(); + counter = new RapidFireTimeCounter(timerCount); + counter.start(); + } + }); + + AlertDialog dialog = builder.create(); + // display dialog + dialog.show(); + } + + // sets score value by appending to the string + private void setGameScore() { + totalScore.setText(getString(R.string.label_rapid_fire_total_score, gameScore)); + } + + @Override + protected void init() { + // below parameters are initialized with their initial value when game starts + quesNo = 0; + gameScore = 0; + millisLeft = 6000; + + presenter.checkFirstTime(); + + } + + private void prepNextQues() { + setGameScore(); + final android.os.Handler handler = new android.os.Handler(); + //provide a delay of 1 sec after an option is clicked by the user + handler.postDelayed(new Runnable() { + @Override + public void run() { + // it can happen due to orientation changes + if (quesNo < presenter.questionListSize()) { + quesNo++; + + if (quesNo < presenter.questionListSize()) { + millisLeft = 6000; + prepareQuestionAndOptions(); + } else { + showGameOverDialog(); + } + } + } + }, 1000); + } + + // setting button background to application theme when next question is set up + @Override + public void setButtonBackground() { + optionOne.setBackground(getResources().getDrawable(R.drawable.button_background)); + optionTwo.setBackground(getResources().getDrawable(R.drawable.button_background)); + optionThree.setBackground(getResources().getDrawable(R.drawable.button_background)); + } + + // receives model from presenter, sets it to the question, options and enables the buttons + @Override + public void prepareQuestionAndOptions() { + setButtonBackground(); + if (quesNo == presenter.questionListSize()) + quesNo--; + QuestionModel model = presenter.getQuestionModel(quesNo); + tvQuestion.setText(model.getQuestion()); + optionOne.setText(model.getOption1()); + optionTwo.setText(model.getOption2()); + optionThree.setText(model.getOption3()); + + enableOptions(true); + //checks that quesNo is within questionList size which is possible on orientation change + if (quesNo != presenter.questionListSize()) { + counter = new RapidFireTimeCounter(millisLeft); + counter.start(); + } + } + + // enables/display all options val transferred to function + @Override + public void enableOptions(boolean val) { + optionOne.setEnabled(val); + optionOne.setClickable(val); + optionTwo.setEnabled(val); + optionTwo.setClickable(val); + optionThree.setEnabled(val); + optionThree.setClickable(val); + } + + // update timer + @Override + public void updateTimer(long miliLeft) { + timerView.setText(getString(R.string.blank_text, miliLeft / 1000)); + } + + // Dialog shown when game is over + private void showGameOverDialog() { + // create a dialog with AlertDialog builder, set appropriate title & message + AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.MyDialogTheme); + builder.setTitle(getString(R.string.label_game_over)); + builder.setMessage(getString(R.string.description_wait_for_new_ques)); + + String positiveText = getString(android.R.string.ok); + builder.setPositiveButton(positiveText, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // dismiss the dialog, update game score in preference, starts play fragment again + dialog.dismiss(); + presenter.updateGameScore(gameScore); + listener.goBackToPlayFragment(); + } + }); + + AlertDialog dialog = builder.create(); + // display dialog + dialog.show(); + } + + + // saving value in case of orientation changes + @Override + public void onSaveInstanceState(@NonNull Bundle outState) { + super.onSaveInstanceState(outState); + outState.putLong(COUNTER_MILLIS_LEFT, millisLeft); + outState.putInt(GAME_SCORE, gameScore); + outState.putInt(QUES_NO, quesNo); + } + + // cancel counter, set presenter and listener to null + @Override + public void onDetach() { + super.onDetach(); + counter.cancel(); + presenter = null; + listener = null; + } + + //Implementing the timer + class RapidFireTimeCounter extends CountDownTimer { + RapidFireTimeCounter(long millisInFuture) { + super(millisInFuture, 1000); + } + + @Override + public void onTick(long l) { + timerCount = l; + timerView.setText(getString(R.string.blank_text, l / 1000)); + millisLeft = l; + + } + + @Override + public void onFinish() { + counter.cancel(); + prepNextQues(); + } + } + + public interface OnRapidFragmentListener { + void goBackToPlayFragment(); + } + + // Container Activity must implement this interface + @Override + public void onAttach(Context context) { + super.onAttach(context); + // This makes sure that the container activity has implemented + // the callback interface. If not, it throws an exception + if (context instanceof OnRapidFragmentListener) { + listener = (OnRapidFragmentListener) context; + } else { + // Show error Log for debugging & display snack bar to user + ToastLogSnackBarUtil.showErrorLog(context.toString() + " must implement OnRapidFragmentListener"); + if (getActivity() != null) { + ToastLogSnackBarUtil.showSnackBar(context, getActivity().findViewById(android.R.id.content), + "Something went wrong!"); + } + } + } + + @Override + public void onDestroy() { + super.onDestroy(); + counter.cancel(); + } + + @Override + public void playTapTargetViewer() { + new TapTargetSequence(getActivity()) + .continueOnCancel(true) + .targets( + TapTarget.forView(tvQuestion, getString(R.string.help_rapid_fire_question_title), + getString(R.string.help_rapid_fire_question_description)) + .drawShadow(true) + .tintTarget(true) + .targetRadius(60) + .titleTextColor(R.color.textColorPrimary) + .descriptionTextColor(R.color.white) + .targetCircleColor(R.color.colorAccent) + .outerCircleAlpha(0.90f).id(3), + TapTarget.forView(totalScore, getString(R.string.help_rapid_fire_score_title), + "") + .drawShadow(true) + .tintTarget(true) + .titleTextColor(R.color.textColorPrimary) + .descriptionTextColor(R.color.white) + .targetRadius(60) + .targetCircleColor(R.color.colorAccent) + .outerCircleAlpha(0.90f).id(3), + TapTarget.forView(timerView, getString(R.string.help_rapid_fire_timer_title), + getString(R.string.help_rapid_fire_timer_description)) + .drawShadow(true) + .tintTarget(true) + .titleTextColor(R.color.textColorPrimary) + .descriptionTextColor(R.color.white) + .targetRadius(60) + .targetCircleColor(R.color.colorAccent) + .outerCircleAlpha(0.90f).id(3), + TapTarget.forView(exitButton, getString(R.string.help_rapid_fire_exit_title), + "") + .drawShadow(true) + .tintTarget(true) + .titleTextColor(R.color.textColorPrimary) + .descriptionTextColor(R.color.white) + .targetRadius(60) + .targetCircleColor(R.color.colorAccent) + .outerCircleAlpha(0.90f).id(3) + + ) + .listener(new TapTargetSequence.Listener() { + @Override + public void onSequenceFinish() { + presenter.getDataManager().setRapidFireTarget(true); + presenter.prepareQuestionList(quesNo); + } + + @Override + public void onSequenceStep(TapTarget lastTarget, boolean targetClicked) { + // no need currently, compulsory overridden method + } + + @Override + public void onSequenceCanceled(TapTarget lastTarget) { + // no need currently, compulsory overridden method + } + }).start(); + } + + +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFirePresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFirePresenter.java new file mode 100644 index 00000000..9aaf045e --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/play/rapid_fire/RapidFirePresenter.java @@ -0,0 +1,73 @@ +package com.peacecorps.malaria.ui.play.rapid_fire; + +import android.content.Context; + +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.play.rapid_fire.RapidFireContract.RapidFireMvpPresenter; +import com.peacecorps.malaria.ui.play.rapid_fire.RapidFireContract.RapidFireMvpView; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Anamika Tripathi on 19/7/18. + */ +public class RapidFirePresenter extends BasePresenter implements RapidFireMvpPresenter { + // array list for questions & respective answer + private List questionList; + + RapidFirePresenter(AppDataManager manager, Context context) { + super(manager, context); + } + + // preparing question, answer in beginning of test. + @Override + public void prepareQuestionList(int num) { + questionList= new ArrayList<>(); + //adding questions + questionList.add(new QuestionModel("Melfoquine should be taken ", "Daily", "Weekly", "Monthly", 2)); + questionList.add(new QuestionModel("Malaria is caused by ", "Virus", "Bacteria", "Protozoa",3)); + questionList.add(new QuestionModel("Doxycycline should be taken ", "Daily", "Weekly", "Monthly", 1)); + questionList.add(new QuestionModel("Malaria is transmitted through _____ mosquito", "Female Aedes", "Female Anopheles", "Male Aedes", 2)); + questionList.add(new QuestionModel("Malarone should be taken ", "Daily", "Weekly", "Monthly", 1)); + getView().prepareQuestionAndOptions(); + } + + @Override + public void attachView(V view) { + super.attachView(view); + } + + @Override + public void detachView() { + super.detachView(); + } + + @Override + public int questionListSize() { + return questionList.size(); + } + + // returns ith row i.e model of question list + @Override + public QuestionModel getQuestionModel(int i) { + return questionList.get(i); + } + + // updates preferences with current game score points + @Override + public void updateGameScore(int currPoints) { + int oldPoints = getDataManager().getGameScore(); + getDataManager().setGameScore(oldPoints + currPoints); + } + + @Override + public void checkFirstTime() { + if(!getDataManager().checkRapidFireTarget()) { + getView().playTapTargetViewer(); + } else { + prepareQuestionList(0); + } + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/PlanTripContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/PlanTripContract.java new file mode 100644 index 00000000..e607c574 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/PlanTripContract.java @@ -0,0 +1,57 @@ +package com.peacecorps.malaria.ui.trip_reminder; + +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +import java.util.Date; +import java.util.List; + +/** + * Created by Anamika Tripathi on 24/7/18. + */ +public interface PlanTripContract { + interface PlanTripMvpView extends MvpView { + + void createSelectLocationDialog(List list); + + void startSelectItemFragment(long numberOfDrugs); + + void updateSelectItemText(String text); + + String getLocationText(); + + String getDepartureTimeText(); + + void showCustomSnackBar(String message); + + boolean validateTripLocation(); + + boolean validateDepartureDate(); + + boolean validateArrivalDate(); + + boolean validateSelectItem(); + + boolean validateReminderTime(); + } + + interface PlanTripMvpPresenter extends MvpPresenter { + void setUpLocationDialog(); + + String convertToTwelveHours(int hours, int mins); + + boolean testIsEmpty(String text); + + Date getDateObj(String s); + + long convertDateToTime(Date date); + + void checkDateValidity(String dateArr, String dateDepart); + + long calculateNumOfMedicine(long a, long d); + + void saveTripDetails(); + + void validationGenerateButton(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/PlanTripFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/PlanTripFragment.java new file mode 100644 index 00000000..9da83e96 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/PlanTripFragment.java @@ -0,0 +1,461 @@ +package com.peacecorps.malaria.ui.trip_reminder; + +import android.annotation.SuppressLint; +import android.app.DatePickerDialog; +import android.app.Dialog; +import android.app.TimePickerDialog; +import android.content.Context; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.design.widget.TextInputEditText; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.DatePicker; +import android.widget.ListView; +import android.widget.TimePicker; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.ui.trip_reminder.PlanTripContract.PlanTripMvpView; +import com.peacecorps.malaria.utils.DatePickerFragment; +import com.peacecorps.malaria.utils.InjectionClass; +import com.peacecorps.malaria.utils.TimePickerFragment; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import java.util.List; + +import butterknife.BindView; +import butterknife.ButterKnife; +import butterknife.OnClick; + +import static android.view.View.OnTouchListener; + +/** + * Created by Anamika Tripathi on 24/7/18. + */ +public class PlanTripFragment extends BaseFragment implements PlanTripMvpView { + + private PlanTripPresenter presenter; + private Context context; + // edit texts + @BindView(R.id.et_trip_location) + TextInputEditText etTripLocation; + @BindView(R.id.et_departure_date) + TextInputEditText etDepartureDate; + @BindView(R.id.et_arrival_date) + TextInputEditText etArrivalDate; + @BindView(R.id.et_select_items) + TextInputEditText etSelectItem; + @BindView(R.id.et_trip_reminder_time) + TextInputEditText etReminderTime; + + private boolean checkDepartureOrArrivalEt; + private boolean arr, dptr; + private OnPlanFragmentListener listener; + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_plan_trip, container, false); + context = getContext(); + ButterKnife.bind(this, view); + presenter = new PlanTripPresenter<>(InjectionClass.provideDataManager(context), context); + presenter.attachView(this); + return view; + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + if(presenter.isViewAttached()) { + init(); + } else { + ToastLogSnackBarUtil.showErrorLog("PlanTripFragment: View not attached"); + } + } + + @Override + protected int getContentResource() { + return R.layout.tripindicator_layout; + } + + @Override + protected void init() { + // setting touch listener on drawable Right -- location history + addLocationHistoryDialog(); + // setting date time picker on drawable Right -- etDepartureDate, etArrivalDate, etReminderTime + startDateTimePickerDialog(); + } + + @SuppressLint("ClickableViewAccessibility") + private void addLocationHistoryDialog() { + etTripLocation.setOnTouchListener(new OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + final int DRAWABLE_RIGHT = 2; + + if (event.getAction() == MotionEvent.ACTION_UP && + (event.getRawX() >= (etTripLocation.getRight() + - etTripLocation.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width()))) { + // creating a custom dialog with location history + presenter.setUpLocationDialog(); + return true; + } + return false; + } + + + }); + } + + @SuppressLint("ClickableViewAccessibility") + private void startDateTimePickerDialog() { + etDepartureDate.setOnTouchListener(new OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + final int DRAWABLE_RIGHT = 2; + + if (event.getAction() == MotionEvent.ACTION_UP && + (event.getRawX() >= (etDepartureDate.getRight() - etDepartureDate.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width()))) { + checkDepartureOrArrivalEt = true; + // creating show date picker dialog + showDatePicker(); + return true; + } + return false; + } + + + }); + + etArrivalDate.setOnTouchListener(new OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + final int DRAWABLE_RIGHT = 2; + + if (event.getAction() == MotionEvent.ACTION_UP && + (event.getRawX() >= (etArrivalDate.getRight() - etArrivalDate.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width()))) { + checkDepartureOrArrivalEt = false; + // creating show date picker dialog + showDatePicker(); + return true; + } + return false; + } + + + }); + + etReminderTime.setOnTouchListener(new OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + final int DRAWABLE_RIGHT = 2; + + if (event.getAction() == MotionEvent.ACTION_UP && + (event.getRawX() >= (etReminderTime.getRight() - etReminderTime.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width()))) { + checkDepartureOrArrivalEt = true; + // creating show date picker dialog + showTimePicker(); + return true; + } + return false; + } + + + }); + } + + @OnClick(R.id.et_departure_date) + public void departureDateListener() { + checkDepartureOrArrivalEt = true; + showDatePicker(); + } + + @OnClick(R.id.et_arrival_date) + public void arrivalDateListener() { + checkDepartureOrArrivalEt = false; + showDatePicker(); + } + + private void showDatePicker() { + DatePickerFragment date = new DatePickerFragment(); + + if (getFragmentManager() != null) { + date.show(getFragmentManager(), "Date Picker"); + } else { + ToastLogSnackBarUtil.showErrorLog("getFragmentManager is null in PlanTripFragment"); + } + + + DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() { + + public void onDateSet(DatePicker view, int year, int month, + int day) { + if (checkDepartureOrArrivalEt) { + dptr = true; + etDepartureDate.setText(getResources().getString(R.string.et_trip_date, day, month + 1, year)); + } else { + arr = true; + etArrivalDate.setText(getResources().getString(R.string.et_trip_date, day, month + 1, year)); + } + + } + }; + /* + * Set Call back to capture selected date + */ + date.setCallBack(onDateSetListener); + + } + + private void showTimePicker() { + TimePickerFragment timePickerFragment = new TimePickerFragment(); + if (getFragmentManager() != null && getActivity() != null) { + timePickerFragment.show(getActivity().getFragmentManager(), "Time Picker in PlanTripFragment"); + } else { + ToastLogSnackBarUtil.showErrorLog("PlanTripFragment: getFragmentManager/getActivity is null"); + } + + TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() { + @Override + public void onTimeSet(TimePicker view, int hourOfDay, int minute) { + etReminderTime.setText(presenter.convertToTwelveHours(hourOfDay, minute)); + } + }; + /* + * Set Call back to capture selected date + */ + timePickerFragment.setCallBack(listener); + + } + + /** + * @param view : starts focus on passed edit text as parameter + */ + private void requestFocus(View view) { + if (view.requestFocus() && getActivity() != null) { + getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); + } else { + ToastLogSnackBarUtil.showErrorLog("PlanTripFragment: getActivity is null or focusable is false"); + } + } + + // set select button listener + @OnClick(R.id.et_select_items) + public void selectButtonListener() { + if (arr && dptr) { + // departure & arrival value set , checks validity of dates + presenter.checkDateValidity(etArrivalDate.getText().toString(), etDepartureDate.getText().toString()); + } else { + ToastLogSnackBarUtil.showToast(context, "Select Arrival & Departure date first!"); + } + } + + // generate button listener + @OnClick(R.id.btn_trip_generate) + public void generateButtonListener() { + /* + * check etSelectItem, etReminderTime, etTripLocation is valid - (not null & not empty) + */ + presenter.validationGenerateButton(); + //Todo create alarm - need to implement alarm services first + /* + * Setting Up Alarm for a Week Before + * A day Before + * On day of Trip + */ + + } + + /** + * This interface is implemented in MainActivity which starts SelectItem Dialog fragment + */ + public interface OnPlanFragmentListener { + void startSelectItemFragment(long quantity); + } + + // Container Activity i.e MainActivity must implement this interface + @Override + public void onAttach(Context context) { + super.onAttach(context); + // This makes sure that the container activity has implemented + // the callback interface. If not, it throws an exception - showing message via Error log + if (context instanceof OnPlanFragmentListener) { + listener = (OnPlanFragmentListener) context; + } else { + // Show error Log for debugging & display snackbar to user + ToastLogSnackBarUtil.showErrorLog(context.toString() + " must implement OnPlanFragmentListener"); + if (getActivity() != null) { + ToastLogSnackBarUtil.showSnackBar(context, getActivity().findViewById(android.R.id.content), + "Something went wrong!"); + } + } + } + + /** + * PlanTripContract.PlanTripMvpView's functions + */ + + + // return false if view is null else true + private boolean checkViewNotNull(View view) { + return view != null; + } + + // returns true if etTripLocation not null & not empty, else provides appropriate message + @Override + public boolean validateTripLocation() { + if (checkViewNotNull(etTripLocation)) { + String text = etTripLocation.getText().toString().trim(); + if (!presenter.testIsEmpty(text)) { + return true; + } else { + etTripLocation.setError("can't leave empty"); + requestFocus(etTripLocation); + return false; + } + } else { + ToastLogSnackBarUtil.showErrorLog("PlanTripFragment: etTripLocation is null"); + } + return false; + } + + // returns true if etDepartureDate not null & not empty, else provides appropriate message + @Override + public boolean validateDepartureDate() { + if (checkViewNotNull(etDepartureDate)) { + String text = etDepartureDate.getText().toString().trim(); + return !presenter.testIsEmpty(text); + } else { + ToastLogSnackBarUtil.showErrorLog("PlanTripFragment: etDepartureDate is null"); + } + return false; + } + + // returns true if etArrivalDate not null & not empty, else provides appropriate message + @Override + public boolean validateArrivalDate() { + if (checkViewNotNull(etArrivalDate)) { + String text = etArrivalDate.getText().toString().trim(); + return !presenter.testIsEmpty(text); + } else { + ToastLogSnackBarUtil.showErrorLog("PlanTripFragment: etArrivalDate is null"); + } + return false; + } + + // returns true if etSelectItem not null & not empty, else provides appropriate message + @Override + public boolean validateSelectItem() { + if (checkViewNotNull(etSelectItem)) { + String text = etSelectItem.getText().toString().trim(); + if (!presenter.testIsEmpty(text)) { + return true; + } else { + etSelectItem.setError("can't leave empty"); + return false; + } + } else { + ToastLogSnackBarUtil.showErrorLog("PlanTripFragment: etSelectItem is null"); + } + return false; + } + + // returns true if etReminderTime not null & not empty, else provides appropriate message + @Override + public boolean validateReminderTime() { + if (checkViewNotNull(etReminderTime)) { + String text = etReminderTime.getText().toString().trim(); + if (!presenter.testIsEmpty(text)) { + return true; + } else { + etSelectItem.setError("can't leave empty"); + return false; + } + } else { + ToastLogSnackBarUtil.showErrorLog("PlanTripFragment: etReminderTime is null"); + } + return false; + } + + /** + * @param numberOfDrugs : total number of medicine calculated - displayed in SelectItemFragment + */ + @Override + public void startSelectItemFragment(long numberOfDrugs) { + ToastLogSnackBarUtil.showDebugLog("PlanTripF: calling show Dialog"); + listener.startSelectItemFragment(numberOfDrugs); + } + + // sets text for select item + @Override + public void updateSelectItemText(String text) { + etSelectItem.setText(text); + } + + /** + * @param list : List of all history location fetched from sqlite db inside presenter + */ + @Override + public void createSelectLocationDialog(final List list) { + if (list.size() > 0) { + final Dialog alertDialog = new Dialog(context, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar); + alertDialog.setContentView(R.layout.trip_location_dialog); + alertDialog.setCancelable(false); + + ListView lv = alertDialog.findViewById(R.id.list_history_location); + ArrayAdapter adapter; + + // Setting Dialog Title + alertDialog.setTitle(getString(R.string.heading_previous_location)); + adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, list); + lv.setAdapter(adapter); + lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView parent, View view, int position, long id) { + etTripLocation.setText(list.get(position)); + alertDialog.cancel(); + } + }); + // Showing Alert Message + alertDialog.show(); + // doKeepDialog(alertDialog); + } else { + if (getActivity() != null) { + ToastLogSnackBarUtil.showSnackBar(context, getActivity().findViewById(android.R.id.content), "No location History found!"); + } else { + ToastLogSnackBarUtil.showErrorLog("getActivity return null in PlanTripFragment"); + } + } + + } + + // returns location (validity of text checked before calling this function) + @Override + public String getLocationText() { + return etTripLocation.getText().toString().trim(); + } + + // returns departure date (validity of text checked before calling this function) + @Override + public String getDepartureTimeText() { + return etDepartureDate.getText().toString().trim(); + } + + // displays custom bar with appropriate message received + @Override + public void showCustomSnackBar(String message) { + if (getActivity() != null) { + ToastLogSnackBarUtil.showSnackBar(context, getActivity().findViewById(android.R.id.content), message); + } + + } + + +} \ No newline at end of file diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/PlanTripPresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/PlanTripPresenter.java new file mode 100644 index 00000000..2a1d398f --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/PlanTripPresenter.java @@ -0,0 +1,194 @@ +package com.peacecorps.malaria.ui.trip_reminder; + +import android.content.Context; +import android.text.TextUtils; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.data.db.DbHelper; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.trip_reminder.PlanTripContract.PlanTripMvpPresenter; +import com.peacecorps.malaria.ui.trip_reminder.PlanTripContract.PlanTripMvpView; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +/** + * Created by Anamika Tripathi on 26/7/18. + */ +public class PlanTripPresenter extends BasePresenter implements PlanTripMvpPresenter { + + PlanTripPresenter(AppDataManager manager, Context context) { + super(manager, context); + } + + // get location history from db & calls createSelectLocationDialog if location is available else shows snack bar + @Override + public void setUpLocationDialog() { + getDataManager().getLocation(new DbHelper.loadListStringCallBack() { + @Override + public void onDataLoaded(List data) { + if(data.size()>0) { + getView().createSelectLocationDialog(data); + } else { + getView().showCustomSnackBar("No location history available"); + } + + } + }); + } + + /** + * @param hr : hour selected in @TimePickerFragment (24 hour format) + * @param mins : min selected in Fragment + */ + @Override + public String convertToTwelveHours(int hr, int mins) { + String timeSet; + int hour = 0; + if (hr > 12) { + hour = hr -12; + timeSet = "PM"; + } else if (hr == 0) { + hour += 12; + timeSet = "AM"; + } else if (hr == 12) { + timeSet = "PM"; + hour = hr; + } else { + timeSet = "AM"; + hour = hr; + } + + String minutes; + if (mins < 10) { + minutes = getContext().getResources().getString(R.string.add_zero_beginning, mins); + } else { + minutes = String.valueOf(mins); + } + // Append the time to a stringBuilder + return getContext().getResources().getString(R.string.time_picker, hour, minutes, timeSet); + } + + // util function for testing text is empty of not + @Override + public boolean testIsEmpty(String text) { + return TextUtils.isEmpty(text); + } + + /** + * @param s : date in string format, received by getText().toString() on edit Text + * @return : Date object by parsing the parameter received + */ + @Override + public Date getDateObj(String s) { + Date dateObj = null; + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()); + try { + dateObj = sdf.parse(s); + } catch (ParseException e) { + ToastLogSnackBarUtil.showErrorLog(s + "PlanTripPresenter: Parsing error in SimpleDateFormat"); + } + return dateObj; + } + + /** + * @param date : date is converted to time using toTime() + * @return : toTime() give long time in mili + */ + @Override + public long convertDateToTime(Date date) { + return date.getTime(); + } + + /** + * @param dateArr : arrival date + * @param dateDepart : departure date + */ + @Override + public void checkDateValidity(String dateArr, String dateDepart) { + if (testIsEmpty(dateDepart)) { + ToastLogSnackBarUtil.showToast(getContext(), "Select Departure date first"); + } else if (testIsEmpty(dateArr)) { + ToastLogSnackBarUtil.showToast(getContext(), "Select Arrival date first"); + } else { + String currDateString = new SimpleDateFormat("dd/MM/yy", Locale.getDefault()).format(new Date()); + Date currDate = getDateObj(currDateString); + Date deptDate = getDateObj(dateDepart); + Date arrDate = getDateObj(dateArr); + + if (currDate != null && deptDate != null && arrDate != null) { + long arrLong = convertDateToTime(arrDate); + long dptrLong = convertDateToTime(deptDate); + long currLong = convertDateToTime(currDate); + + if (dptrLong < currLong) { + ToastLogSnackBarUtil.showToast(getContext(), getContext().getResources().getString(R.string.departuredate_currentdate)); + } else if (arrLong < dptrLong) { + ToastLogSnackBarUtil.showToast(getContext(), getContext().getResources().getString(R.string.arrivaldate_departuredate)); + } else if (arrLong >= dptrLong) { + // ask Fragment to start fragment, parameter is no of medicines calculated + getView().startSelectItemFragment(calculateNumOfMedicine(arrLong, dptrLong)); + } + } + } + } + + /** + * @param a : arrival time - converted in checkDateValidity() + * @param d : departure time + * @return : no of medicine to pack - displayed in select item fragment + */ + @Override + public long calculateNumOfMedicine(long a, long d) { + int oneDay = 24 * 60 * 60 * 1000; + + return (a - d) / oneDay + 1; + } + + /** + * reminderMessage : saved in preferences + * location selected/added : added in database (if old location selected, time: gets increased (no of time trip planned) + */ + @Override + public void saveTripDetails() { + String reminderMessage = "Trip to " + getView().getLocationText() + + " is scheduled for " + getView().getDepartureTimeText() + + ".\n" + "Stay safe, don't forget to take your pills."; + getDataManager().setReminderMessageForTrip(reminderMessage); + getDataManager().insertLocation(getView().getLocationText()); + ToastLogSnackBarUtil.showToast(getContext(), "Trip Saved"); + } + + /** + * validates all edit text, if all returns true, calls saveTripDetails() + */ + @Override + public void validationGenerateButton() { + if (!getView().validateTripLocation()) { + return; + } + + if (!getView().validateDepartureDate()) { + return; + } + + if (!getView().validateArrivalDate()) { + return; + } + + if (!getView().validateSelectItem()) { + return; + } + + if (!getView().validateReminderTime()) { + return; + } + + saveTripDetails(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemAdapter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemAdapter.java new file mode 100644 index 00000000..6d1263ab --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemAdapter.java @@ -0,0 +1,115 @@ +package com.peacecorps.malaria.ui.trip_reminder.trip_select_item; + +import android.support.annotation.NonNull; +import android.support.v7.widget.AppCompatCheckBox; +import android.support.v7.widget.RecyclerView; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import com.peacecorps.malaria.R; + +/** + * Created by Anamika Tripathi on 1/8/18. + */ +public class ItemAdapter extends RecyclerView.Adapter { + private ItemDialogPresenter presenter; + private ItemOnClickListener listener; + + ItemAdapter(ItemDialogPresenter presenter, ItemOnClickListener listener) { + this.presenter = presenter; + this.listener = listener; + } + + @NonNull + @Override + public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + // create a view + View view = LayoutInflater.from(parent.getContext()) + .inflate(R.layout.item_selected, parent, false); + + return new ItemViewHolder(view); + } + + /** + * @param holder : holds the views for recycling + * @param position : row number + */ + @Override + public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) { + /* set text on packing item for row - position + get function are being checking inside presenter, refer ItemDialogPresenter + */ + holder.selectedItem.setText(presenter.getItemList().get(position).getPackingItem()); + holder.bind(position); + } + + /** + * @return : size of presenter's item list, if null - returns 0 + */ + @Override + public int getItemCount() { + if (presenter.getItemList() == null) + return 0; + return presenter.getItemList().size(); + } + + class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { + + private TextView selectedItem; + private ImageView deleteView; + private AppCompatCheckBox checkBox; + + ItemViewHolder(View itemView) { + super(itemView); + // initialize row's views + selectedItem = itemView.findViewById(R.id.tv_packing_item); + deleteView = itemView.findViewById(R.id.img_delete_row); + checkBox = itemView.findViewById(R.id.packing_item_check_box); + deleteView.setOnClickListener(this); + checkBox.setOnClickListener(this); + } + + /** + * @param v : view on which click event occurred, either delete button click or checkbox status changed + */ + @Override + public void onClick(View v) { + // checking id of view & position in list + int id = v.getId(); + int pos = getAdapterPosition(); + + if (id == R.id.img_delete_row) { + // call delete row listener - implemented in ItemDialogFragment + listener.onDeleteRowListener(pos); + } else if (id == R.id.packing_item_check_box) { + /* + * checking current status of checkbox at adapter's position from model arraylist + * inverse status of checkbox & status in array list + */ + if (presenter.getItemList().get(pos).getPackingStatus()) { + checkBox.setChecked(false); + presenter.updatePackingStatus(pos, false); + } else { + checkBox.setChecked(true); + presenter.updatePackingStatus(pos, true); + } + } + + } + + public void bind(int position) { + if (presenter.getItemList().get(position).getPackingStatus()) { + checkBox.setChecked(true); + } else { + checkBox.setChecked(false); + } + } + } + + interface ItemOnClickListener { + void onDeleteRowListener(int position); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemDialogContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemDialogContract.java new file mode 100644 index 00000000..e6e16866 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemDialogContract.java @@ -0,0 +1,27 @@ +package com.peacecorps.malaria.ui.trip_reminder.trip_select_item; + +import com.peacecorps.malaria.data.db.entities.Packing; +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +/** + * Created by Anamika Tripathi on 1/8/18. + */ +public interface ItemDialogContract { + interface ItemDialogMvpView extends MvpView { + void notifyAdapterForUpdate(); + void setDrugQuantity(int quantity); + void closeDialog(Packing packing); + } + + interface ItemDialogMvpPresenter extends MvpPresenter { + boolean testIsEmpty(String text); + void addToPackingList(String item); + void calculateDrugQuantity(int num, long q); + void replaceMedicineName(String med, int quantity); + void updatePackingStatus(int pos, boolean status); + void deletePackingRow(int pos); + void addCashToPacking(int total); + void getMedDetailsAndCloseDialog(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemDialogFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemDialogFragment.java new file mode 100644 index 00000000..6c0df03a --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemDialogFragment.java @@ -0,0 +1,403 @@ +package com.peacecorps.malaria.ui.trip_reminder.trip_select_item; + +import android.annotation.SuppressLint; +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.v4.app.DialogFragment; +import android.support.v7.app.ActionBar; +import android.support.v7.app.AlertDialog; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.support.v7.widget.Toolbar; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewGroup; +import android.widget.EditText; +import android.widget.TextView; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.data.db.entities.Packing; +import com.peacecorps.malaria.ui.trip_reminder.trip_select_item.ItemAdapter.ItemOnClickListener; +import com.peacecorps.malaria.ui.trip_reminder.trip_select_item.ItemDialogContract.ItemDialogMvpView; +import com.peacecorps.malaria.utils.InjectionClass; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import butterknife.BindView; +import butterknife.ButterKnife; +import butterknife.OnClick; + +/** + * Created by Anamika Tripathi on 31/7/18. + */ +public class ItemDialogFragment extends DialogFragment implements ItemDialogMvpView, ItemOnClickListener { + private ItemDialogPresenter presenter; + private Context context; + private ItemAdapter itemAdapter; + private OnSaveDialogListener listener; + + private long medQuantity; + + @BindView(R.id.select_drug_name) + EditText etSelectDrug; + @BindView(R.id.et_packing_item) + EditText etPackingItem; + @BindView(R.id.tv_drug_quantity) + TextView tvMedicineQuantity; + @BindView(R.id.et_total_cash) + EditText etTotalCash; + + /** + * @param num : medicine quantity calculated by departure & arrival date + * @return : instance of this fragment + */ + public static ItemDialogFragment newInstance(long num) { + ItemDialogFragment f = new ItemDialogFragment(); + + // Supply num input as an argument. + Bundle args = new Bundle(); + args.putLong("MED_QUANTITY", num); + f.setArguments(args); + + return f; + } + + @Override + public void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + // take medQuantity if available in bundle + if (getArguments() != null) { + medQuantity = getArguments().getLong("MED_QUANTITY"); + } else { + ToastLogSnackBarUtil.showErrorLog("ItemDialogFragment: getArguments is null"); + } + } + + @Override + public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + // Inflate the layout to use as dialog or embedded fragment + View view = inflater.inflate(R.layout.fragment_select_trip_item, container, false); + + setUpToolBar(view); + ButterKnife.bind(this, view); + return view; + } + + /** + * The system calls this only when creating the layout in a dialog. + */ + @NonNull + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + Dialog dialog = super.onCreateDialog(savedInstanceState); + if (dialog.getWindow() != null) { + + int width = ViewGroup.LayoutParams.MATCH_PARENT; + int height = ViewGroup.LayoutParams.MATCH_PARENT; + dialog.getWindow().setLayout(width, height); + + } + setStyle(DialogFragment.STYLE_NORMAL, R.style.MyFullScreenDialogTheme); + return dialog; + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + + // instantiate presenter and attach view + context = getContext(); + presenter = new ItemDialogPresenter<>(InjectionClass.provideDataManager(context), context); + presenter.attachView(this); + + if (presenter.isViewAttached()) { + init(view); + } else { + ToastLogSnackBarUtil.showErrorLog("ItemDialogFragment: View not attached"); + } + + } + + @Override + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + menu.clear(); + // clear activity's menu and attach menu_ok_cancel + if (getActivity() != null) { + getActivity().getMenuInflater().inflate(R.menu.menu_ok_cancel, menu); + } else { + ToastLogSnackBarUtil.showErrorLog("ItemDialogFragment: getActivity() is null"); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + + if (id == R.id.action_save) { + // save menu button clicked + saveButtonListener(); + return true; + } else if (id == android.R.id.home) { + // close dialog fragment + dismiss(); + return true; + } + + return super.onOptionsItemSelected(item); + } + + // Container Activity i.e MainActivity must implement this interface + @Override + public void onAttach(Context context) { + super.onAttach(context); + // This makes sure that the container activity has implemented + // the callback interface. If not, it throws an exception - showing message via Error log + if (context instanceof OnSaveDialogListener) { + listener = (OnSaveDialogListener) context; + } else { + // Show error Log for debugging & display snackbar to user + ToastLogSnackBarUtil.showErrorLog(context.toString() + " must implement OnSaveDialogListener"); + if (getActivity() != null) { + ToastLogSnackBarUtil.showSnackBar(context, getActivity().findViewById(android.R.id.content), + "Something went wrong!"); + } + } + } + + // called when data changed in recycler view + @Override + public void notifyAdapterForUpdate() { + itemAdapter.notifyDataSetChanged(); + } + + /** + * @param quantity : calculated no of drugs to be packed + */ + @Override + public void setDrugQuantity(int quantity) { + tvMedicineQuantity.setText(context.getString(R.string.blank_text, quantity)); + } + + // passes value via callback and dismisses fragment + @Override + public void closeDialog(Packing packing) { + listener.passMedicineSelected(packing); + dismiss(); + } + + // called if delete button is clicked in recycler view - deletes rows except first row i.e medicines & notifies adapter + @Override + public void onDeleteRowListener(int position) { + + if (position > 0) { + presenter.deletePackingRow(position); + itemAdapter.notifyItemRemoved(position); + itemAdapter.notifyItemRangeChanged(position, presenter.getItemList().size()); + } else { + if (getActivity() != null) { + ToastLogSnackBarUtil.showSnackBar(context, getActivity().findViewById(android.R.id.content), "Pills are compulsory selection!"); + } else { + ToastLogSnackBarUtil.showErrorLog("ItemDialogFragment: getActivity() is null"); + } + } + + } + + @Override + public boolean isNetworkConnected() { + // not required to check here + return false; + } + + private void init(View view) { + // starts single select dialog for medicine + addDrugSelectDialog(); + // setup recycler view which contains item list + setUpRecyclerView(view); + } + + /** + * sets on touch listener on drop-down button, calls @showMedicineSelectDialog if touched + */ + @SuppressLint("ClickableViewAccessibility") + private void addDrugSelectDialog() { + + etSelectDrug.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View v, MotionEvent event) { + final int DRAWABLE_RIGHT = 2; + + if (event.getAction() == MotionEvent.ACTION_UP && + (event.getRawX() >= (etSelectDrug.getRight() - etSelectDrug.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width()))) { + // creating a single item select dialog with medicine names + showMedicineSelectDialog(); + return true; + } + return false; + } + + + }); + } + + // sets up custom tool bar for dialog fragment + private void setUpToolBar(View view) { + Toolbar toolbar = view.findViewById(R.id.select_item_toolbar); + ActionBar actionBar; + + toolbar.setTitle("Select Trip Item"); + if (getActivity() != null) { + ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar); + actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); + if (actionBar != null) { + actionBar.setDisplayHomeAsUpEnabled(true); + actionBar.setHomeButtonEnabled(true); + actionBar.setHomeAsUpIndicator(R.drawable.action_cancel); + } + } + setHasOptionsMenu(true); + } + + private void setUpRecyclerView(View view) { + ToastLogSnackBarUtil.showDebugLog("set up recycler view"); + RecyclerView itemRecyclerView = view.findViewById(R.id.trip_packing_list); + + // use this setting to improve performance of the RecyclerView + itemRecyclerView.setHasFixedSize(true); + + // use a linear layout manager + LinearLayoutManager mLayoutManager = new LinearLayoutManager(context); + itemRecyclerView.setLayoutManager(mLayoutManager); + + SimpleItemDividerDecoration mDividerItemDecoration = new SimpleItemDividerDecoration(itemRecyclerView.getContext()); + itemRecyclerView.addItemDecoration(mDividerItemDecoration); + + // specify an adapter (see also next example) + itemAdapter = new ItemAdapter(presenter, this); + itemRecyclerView.setAdapter(itemAdapter); + } + + private void showMedicineSelectDialog() { + AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.MyDialogTheme); + builder.setTitle(R.string.label_medicine_selector); + + //list of items + final String[] items = getResources().getStringArray(R.array.array_drugs); + builder.setSingleChoiceItems(items, 2, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // item selected logic + if (checkViewNotNull(etSelectDrug)) { + etSelectDrug.setText(items[which]); + presenter.calculateDrugQuantity(which, medQuantity); + } else { + ToastLogSnackBarUtil.showErrorLog("ItemDialogFragment: Edit text is null"); + } + } + }); + + String positiveText = getString(android.R.string.ok); + builder.setPositiveButton(positiveText, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + //Todo which is -1 here no matter which item is selected, resolve the problem + + if (checkViewNotNull(etSelectDrug) && checkViewNotNull(tvMedicineQuantity)) { + String item = etSelectDrug.getText().toString(); + if (!presenter.testIsEmpty(item)) { + /* + * tvMedicineQuantity can't be empty as etSelectDrug is not empty + */ + int quantity = Integer.parseInt(tvMedicineQuantity.getText().toString()); + presenter.replaceMedicineName(item, quantity); + } else { + etPackingItem.setError("Add Item"); + } + } else { + ToastLogSnackBarUtil.showErrorLog("ItemDialogFragment: etSelectDrug/tvMedicineQuantity is null"); + } + + dialog.dismiss(); + } + }); + + String negativeText = getString(android.R.string.cancel); + builder.setNegativeButton(negativeText, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // negative button logic + dialog.dismiss(); + } + }); + + AlertDialog dialog = builder.create(); + // display dialog + dialog.show(); + } + + @OnClick(R.id.btn_add_item) + public void btnAddItemListener() { + if (checkViewNotNull(etPackingItem)) { + String item = etPackingItem.getText().toString(); + if (!presenter.testIsEmpty(item)) { + // adds value to list & refresh list, clear the edit text + presenter.addToPackingList(item); + ToastLogSnackBarUtil.showDebugLog("Adding item"); + etPackingItem.getText().clear(); + } else { + etPackingItem.setError("Add Item"); + } + } else { + ToastLogSnackBarUtil.showErrorLog("ItemDialogFragment: etPackingItem is null"); + } + + + } + + private boolean checkViewNotNull(View view) { + return view != null; + } + + private void saveButtonListener() { + boolean isValid = checkCashValidity(); + if (isValid) { + /* + * input type is number, can parse string without exception + * add valid cash amount to db + */ + presenter.addCashToPacking(Integer.parseInt(etTotalCash.getText().toString())); + ToastLogSnackBarUtil.showToast(context, "saved"); + + } + presenter.getMedDetailsAndCloseDialog(); + } + + // returns false if etTotalCash is null or empty else returns false + private boolean checkCashValidity() { + if (checkViewNotNull(etTotalCash)) { + String cashText = etTotalCash.getText().toString(); + return !presenter.testIsEmpty(cashText); + } else { + ToastLogSnackBarUtil.showErrorLog("ItemDialogFragment: etTotalCash is null"); + } + return false; + } + + // implemented by MainActivity - used for callback to pass packing details - used in PlanTripFragment + public interface OnSaveDialogListener { + void passMedicineSelected(Packing packing); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemDialogPresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemDialogPresenter.java new file mode 100644 index 00000000..4115e28f --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/ItemDialogPresenter.java @@ -0,0 +1,175 @@ +package com.peacecorps.malaria.ui.trip_reminder.trip_select_item; + +import android.content.Context; +import android.text.TextUtils; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.data.db.DbHelper; +import com.peacecorps.malaria.data.db.entities.Packing; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.trip_reminder.trip_select_item.ItemDialogContract.ItemDialogMvpPresenter; +import com.peacecorps.malaria.ui.trip_reminder.trip_select_item.ItemDialogContract.ItemDialogMvpView; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import java.util.List; + +/** + * Created by Anamika Tripathi on 1/8/18. + */ +public class ItemDialogPresenter extends BasePresenter implements ItemDialogMvpPresenter { + + private List itemList; + + ItemDialogPresenter(AppDataManager manager, Context context) { + super(manager, context); + setUpItemList(); + } + + private void setUpItemList() { + getDataManager().getPackingItem(new DbHelper.LoadListPackingCallback() { + @Override + public void onDataLoaded(List packingList) { + itemList = packingList; + if (packingList.size() == 0) { + ToastLogSnackBarUtil.showDebugLog("no packing list in db"); + String drug = getDataManager().getDrugPicked(); + itemList.add(new Packing(drug, 0, false)); + getDataManager().insertPackingItem(drug, 0, false); + } + } + }); + + getDataManager().getPackingItemChecked(new DbHelper.LoadListPackingCallback() { + @Override + public void onDataLoaded(List packingList) { + ToastLogSnackBarUtil.showDebugLog(packingList.size() + ""); + } + }); + + + } + + public List getItemList() { + return itemList; + } + + // util function for testing text is empty of not + @Override + public boolean testIsEmpty(String text) { + return TextUtils.isEmpty(text); + } + + @Override + public void addToPackingList(String item) { + // insert or update (if item already exists) to database + getDataManager().insertPackingItem(item, 1, false); + // get update packing list for recycler view (makes sure that no duplication exist in list) + getDataManager().getPackingItem(new DbHelper.LoadListPackingCallback() { + @Override + public void onDataLoaded(List packingList) { + itemList = packingList; + getView().notifyAdapterForUpdate(); + } + }); + } + + /** + * @param pos : medicine selected in alert dialog + * 0-Malarone(Daily), 1-Doxycycline(Daily), 2-Melfoquine(Weekly) + * @param qty : total quantity passed to fragment + */ + @Override + public void calculateDrugQuantity(int pos, long qty) { + int quantity = 0; + switch (pos) { + case 0: + quantity = (int) qty; + break; + case 1: + quantity = (int) qty; + break; + case 2: + quantity = (int) ((qty % 7 == 0) ? qty / 7 : (qty / 7) + 1); + break; + default: + ToastLogSnackBarUtil.showErrorLog("ItemDialogPresenter: invalid option selected"); + } + getView().setDrugQuantity(quantity); + } + + /** + * @param med : changed medicine - selected from alert dialog + * @param quantity : calculated quantity of medicine + */ + @Override + public void replaceMedicineName(String med, int quantity) { + // updating db with selected medicine & updating item list + getDataManager().updateMedicinePacking(med, quantity); + // get update packing list for recycler view (makes sure that no duplication exist in list) + getDataManager().getPackingItem(new DbHelper.LoadListPackingCallback() { + @Override + public void onDataLoaded(List packingList) { + itemList = packingList; + } + }); + itemList.set(0, new Packing(med + ": " + quantity, quantity, false)); + getView().notifyAdapterForUpdate(); + } + + /** + * @param pos : row number of list + * @param status : status of checkbox + */ + @Override + public void updatePackingStatus(int pos, boolean status) { + itemList.get(pos).setPackingStatus(status); + getDataManager().updatePackingStatus(status, itemList.get(pos).getPackingId()); + // get update packing list for recycler view (makes sure list is updated for delete & checkbox changes) + getDataManager().getPackingItem(new DbHelper.LoadListPackingCallback() { + @Override + public void onDataLoaded(List packingList) { + itemList = packingList; + } + }); + } + + /** + * @param pos : row number to be deleted + */ + @Override + public void deletePackingRow(int pos) { + getDataManager().deletePackingById(itemList.get(pos).getPackingId()); + itemList.remove(pos); + + // get update packing list for recycler view (makes sure list is updated for delete & checkbox changes) + getDataManager().getPackingItem(new DbHelper.LoadListPackingCallback() { + @Override + public void onDataLoaded(List packingList) { + itemList = packingList; + } + }); + + ToastLogSnackBarUtil.showDebugLog("deleting row " + pos); + } + + @Override + public void addCashToPacking(int total) { + // adding valid cash quantity to be packed + if (getContext() != null) { + getDataManager().insertPackingItem(getContext().getString(R.string.label_cash) + ": $" + total, + total, false); + } + } + + @Override + public void getMedDetailsAndCloseDialog() { + // passing selected medicine to fragment + getDataManager().getPackedMedDetails(new DbHelper.LoadPackingCallback() { + @Override + public void onDataLoaded(Packing packing) { + getView().closeDialog(packing); + } + }); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/SimpleItemDividerDecoration.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/SimpleItemDividerDecoration.java new file mode 100644 index 00000000..81533917 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/trip_reminder/trip_select_item/SimpleItemDividerDecoration.java @@ -0,0 +1,49 @@ +package com.peacecorps.malaria.ui.trip_reminder.trip_select_item; + +import android.content.Context; +import android.content.res.Resources; +import android.graphics.Canvas; +import android.graphics.drawable.Drawable; +import android.support.v7.widget.RecyclerView; +import android.util.TypedValue; +import android.view.View; + +import com.peacecorps.malaria.R; + +/** + * Created by Anamika Tripathi on 1/8/18. + */ +public class SimpleItemDividerDecoration extends RecyclerView.ItemDecoration { + + private Drawable mDivider; + private Context context; + + SimpleItemDividerDecoration(Context context) { + this.context = context; + mDivider = context.getResources().getDrawable(R.drawable.divider); + } + + @Override + public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { + c.save(); + final int leftWithMargin = getMarginInPixel(64); + int right = parent.getWidth() - getMarginInPixel(8); + + int childCount = parent.getChildCount(); + for (int i = 0; i < childCount; i++) { + View child = parent.getChildAt(i); + + RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); + + int top = child.getBottom() + params.bottomMargin; + int bottom = top + mDivider.getIntrinsicHeight(); + mDivider.setBounds(leftWithMargin, top, right, bottom); + mDivider.draw(c); + } + } + + private int getMarginInPixel(int i) { + Resources r = context.getResources(); + return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, i, r.getDisplayMetrics()); + } +} diff --git a/src/com/peacecorps/malaria/DrugArrayAdapter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/DrugArrayAdapter.java similarity index 72% rename from src/com/peacecorps/malaria/DrugArrayAdapter.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/DrugArrayAdapter.java index 9c7cb57c..d4ee1758 100644 --- a/src/com/peacecorps/malaria/DrugArrayAdapter.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/DrugArrayAdapter.java @@ -1,29 +1,29 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.ui.user_medicine_setting; /** * Created by Ankita on 8/13/2015. */ -import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; +import android.support.annotation.NonNull; import android.view.LayoutInflater; -import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; -import android.widget.TableLayout; import android.widget.TextView; +import com.peacecorps.malaria.R; + public class DrugArrayAdapter extends ArrayAdapter{ /**Customized List Adapter with an Image View on Left and Text View on Right**/ private final Activity context; private final String[] dname; private final Integer[] imageId; private final String[] drugDescriptions; - public DrugArrayAdapter(Activity context, - String[] dname, Integer[] imageId, String[] drugDescriptions) { + DrugArrayAdapter(Activity context, + String[] dname, Integer[] imageId, String[] drugDescriptions) { super(context, R.layout.trip_drug_item, dname); this.context = context; this.dname = dname; @@ -31,14 +31,15 @@ public DrugArrayAdapter(Activity context, this.drugDescriptions = drugDescriptions; } + @NonNull @Override - public View getView(int position, View view, ViewGroup parent) { + public View getView(int position, View view, @NonNull ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); //inflating the customized view View rowView= inflater.inflate(R.layout.trip_drug_item, null, true); - TextView txtTitle = (TextView) rowView.findViewById(R.id.drugItem); + TextView txtTitle = rowView.findViewById(R.id.drugItem); - ImageView imageView = (ImageView) rowView.findViewById(R.id.imgDrug); + ImageView imageView = rowView.findViewById(R.id.imgDrug); txtTitle.setText(dname[position]); imageView.setImageResource(imageId[position]); @@ -46,12 +47,12 @@ public View getView(int position, View view, ViewGroup parent) { } @Override - public View getDropDownView(int position, View View, ViewGroup parent) { + public View getDropDownView(int position, View View, @NonNull ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); //inflating the customized view View rowView= inflater.inflate(R.layout.trip_drug_info, null, true); - final TextView txtTitle = (TextView) rowView.findViewById(R.id.nameDrug); - Button infoButton = (Button) rowView.findViewById(R.id.infoDrug); + final TextView txtTitle = rowView.findViewById(R.id.nameDrug); + Button infoButton = rowView.findViewById(R.id.infoDrug); txtTitle.setText(dname[position]); addClickListener(position, infoButton); @@ -59,7 +60,7 @@ public View getDropDownView(int position, View View, ViewGroup parent) { return rowView; } //When the info button is clicked for the drug, an alert dialog will show its description - public void addClickListener(final int position, Button infoButton) { + private void addClickListener(final int position, Button infoButton) { infoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/MedicineSettingContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/MedicineSettingContract.java new file mode 100644 index 00000000..2c43630d --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/MedicineSettingContract.java @@ -0,0 +1,18 @@ +package com.peacecorps.malaria.ui.user_medicine_setting; + +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +public interface MedicineSettingContract { + interface SettingMvpView extends MvpView { + void startMainActivity(); + void setSelectedTime(String theTime); + void enableDoneButton(int h, int min); + } + + interface Presenter extends MvpPresenter { + void checkInitialAppInstall(); + void setUserAndMedicationPreference(int hour, int minute, int drugPickedNo); + void convertToTwelveHours(int hours, int mins); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/MedicineSettingPresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/MedicineSettingPresenter.java new file mode 100644 index 00000000..31827bb4 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/MedicineSettingPresenter.java @@ -0,0 +1,122 @@ +package com.peacecorps.malaria.ui.user_medicine_setting; + +import android.content.Context; +import android.content.Intent; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.data.db.entities.AlarmTime; +import com.peacecorps.malaria.notifications.service.AlarmService; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import java.util.Calendar; +import java.util.Date; + +import static com.peacecorps.malaria.ui.user_medicine_setting.MedicineSettingContract.*; + +public class MedicineSettingPresenter extends BasePresenter implements Presenter { + + MedicineSettingPresenter(AppDataManager manager, Context context) { + super(manager, context); + } + + @Override + public void attachView(V view) { + super.attachView(view); + } + + @Override + public void detachView() { + super.detachView(); + } + + + @Override + public void checkInitialAppInstall() { + if (getDataManager().hasUserSetPreferences()) { + getView().startMainActivity(); + } + } + + /* + *What all it sets? + * drug--------------->INTEGER------------>0-Malarone,1-Doxycycline,2-Melfoquine + * isWeekly----------->BOOLEAN------------>Tells whether the drug chosen was weekly or not + * drugPicked ----> String --> Drug name + * weeklyDate--------->LONG--------------->App registers the weekly date of Melfoquine, now this will be reminded weekly. + * firstRunTime------->LONG--------------->First time the drug was taken. + */ + @Override + public void setUserAndMedicationPreference(int hour, int minute, int mDrugPicked) { + Calendar calendar = Calendar.getInstance(); + int checkDay = calendar.get(Calendar.DAY_OF_WEEK); + int month = calendar.get(Calendar.MONTH); + int year = calendar.get(Calendar.YEAR); + ToastLogSnackBarUtil.showDebugLog("day "+ checkDay + "month " + month + "year " + year + " " + hour + " " + minute ); + // inserted the alarm timing and days + getDataManager().insertAlarmData(new AlarmTime(hour, minute, month, year, checkDay)); + + switch (mDrugPicked) { + case 0: + getDataManager().setDoseWeekly(false); + getDataManager().setDrugPicked(getContext().getString(R.string.med_option_one)); + break; + case 1: + getDataManager().setDoseWeekly(false); + getDataManager().setDrugPicked(getContext().getString(R.string.med_option_two)); + break; + case 2: + getDataManager().setDoseWeekly(true); + getDataManager().setDrugPicked(getContext().getString(R.string.med_option_three)); + break; + default: + getDataManager().setDoseWeekly(false); + getDataManager().setDrugPicked(getContext().getString(R.string.med_option_one)); + } + if (getDataManager().isFirstRun()) { + getDataManager().setFirstRunTime(new Date().getTime()); + getDataManager().setFirstRun(false); + } + getDataManager().setDrugTaken(false); + getDataManager().setUserPreferences(true); + // starting alarm service for reminding user for medicine + getContext().startService(new Intent(getContext(), AlarmService.class)); + } + + /** + * @param hr : hour selected in @TimePickerFragment (24 hour format) + * @param mins : min selected in Fragment + */ + @Override + public void convertToTwelveHours(int hr, int mins) { + ToastLogSnackBarUtil.showDebugLog("" + hr + mins); + String timeSet; + int hour = 0; + if (hr > 12) { + hour = hr -12; + timeSet = "PM"; + } else if (hr == 0) { + hour += 12; + timeSet = "AM"; + } else if (hr == 12) { + timeSet = "PM"; + hour = hr; + } else { + timeSet = "AM"; + hour = hr; + } + + String minutes; + if (mins < 10) { + minutes = getContext().getResources().getString(R.string.add_zero_beginning, mins); + } else { + minutes = String.valueOf(mins); + } + // Append the time to a stringBuilder + String theTime = getContext().getResources().getString(R.string.time_picker, hour, minutes, timeSet); + + getView().setSelectedTime(theTime); + getView().enableDoneButton(hr, mins); + } +} \ No newline at end of file diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/MedicineSettingsActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/MedicineSettingsActivity.java new file mode 100755 index 00000000..2ab19b19 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_medicine_setting/MedicineSettingsActivity.java @@ -0,0 +1,196 @@ +package com.peacecorps.malaria.ui.user_medicine_setting; + +/* + * Created by Anamika on 12/7/2018. + */ + +import android.app.TimePickerDialog; +import android.content.Intent; +import android.graphics.Typeface; +import android.os.Bundle; +import android.view.View; +import android.widget.AdapterView; +import android.widget.Button; +import android.widget.Spinner; +import android.widget.TextView; +import android.widget.TimePicker; +import android.widget.Toast; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.main.MainActivity; +import com.peacecorps.malaria.ui.base.BaseActivity; +import com.peacecorps.malaria.utils.Constants; +import com.peacecorps.malaria.utils.InjectionClass; +import com.peacecorps.malaria.utils.TimePickerFragment; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import butterknife.BindView; +import butterknife.ButterKnife; +import butterknife.OnClick; + + +public class MedicineSettingsActivity extends BaseActivity + implements AdapterView.OnItemSelectedListener, MedicineSettingContract.SettingMvpView { + + @BindView(R.id.setup_label) + TextView mSetupLabel; + @BindView(R.id.drug_take_label) + TextView mDrugTakeLabel; + @BindView(R.id.time_pick_label) + TextView mTimePickLabel; + @BindView(R.id.if_forget_label) + TextView mIfForgetLabel; + @BindView(R.id.drug_select_spinner) + Spinner mDrugSelectSpinner; + + // need to make it static as TimePickerFragment class is static & it's using both buttons + private Button mDoneButton; + private TextView timePickButton; + + private static int drugPickedNo; + private int mHour; + private int mMinute; + + private MedicineSettingPresenter presenter; + + /*User Medicine Settings Fragment Activity is for the Setup Screen of the Malaria App*/ + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setContentView(R.layout.fragment_user_medicine_settings); + +// // set up title of activity +// this.setTitle(R.string.user_medicine_settings_fragment_activity_title); + ButterKnife.bind(this); + + // setting up presenter and views + presenter = new MedicineSettingPresenter<>(InjectionClass.provideDataManager(this), this); + presenter.attachView(this); + init(); + } + + /*OnClicking the done button what all 'll happen? + * All the user settings will be saved. + * Start the Main Activity which shows the Home Screen + */ + @OnClick(R.id.done_button) + public void doneButtonListener(View view) { + if (mDoneButton.isEnabled()) { + // saving alarm timings, setting user preference to true and saving drug picked in preferences + presenter.setUserAndMedicationPreference(mHour, mMinute, drugPickedNo); + + startMainActivity(); + } else { + Toast.makeText(MedicineSettingsActivity.this, "Select time first", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void init() { + // setting different fonts on labels & buttons + Typeface cb = Typeface.createFromAsset(getAssets(), "fonts/garbold.ttf"); + mSetupLabel.setTypeface(cb); + + mDoneButton = findViewById(R.id.done_button); + timePickButton = findViewById(R.id.time_pick_button); + + Typeface cf = Typeface.createFromAsset(getAssets(), "fonts/garreg.ttf"); + timePickButton.setTypeface(cf); + mIfForgetLabel.setTypeface(cb); + mTimePickLabel.setTypeface(cb); + mDrugTakeLabel.setTypeface(cb); + + // check if user has set preferences already + presenter.checkInitialAppInstall(); + + // set up spinner for selecting medicine + createDrugSelectionSpinner(); + } + + /*Method is for working with the Spinner to make selection of drugs work + *It allows selection between three of the drugs- + * Malarone- Daily + * Doxycycline- Daily + * Melofquine- Weekly + */ + private void createDrugSelectionSpinner() { + + DrugArrayAdapter adapter = new DrugArrayAdapter(this, getResources().getStringArray(R.array.array_drugs), + Constants.imageID, getResources().getStringArray(R.array.array_medicine_description)); + + adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); + mDrugSelectSpinner.setAdapter(adapter); + mDrugSelectSpinner.setOnItemSelectedListener(this); + } + + /*Method is for picking time for the Alarm Notifications*/ + @OnClick(R.id.time_pick_button) + public void timePickButtonListener(View v) { + showTimePickerDialog(); + } + + private void showTimePickerDialog() { + TimePickerFragment timePickerFragment = new TimePickerFragment(); + if (getFragmentManager() != null) { + timePickerFragment.show(getFragmentManager(), "Time Picker in MedicineSettingActivity"); + } else { + ToastLogSnackBarUtil.showErrorLog("getFragmentManager is null in MedicineSettingActivity"); + } + + TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() { + @Override + public void onTimeSet(TimePicker view, int hourOfDay, int minute) { + presenter.convertToTwelveHours(hourOfDay, minute); + } + }; + /* + * Set Call back to capture selected date + */ + timePickerFragment.setCallBack(listener); + } + + @Override + public void startMainActivity() { + startActivity(new Intent(MedicineSettingsActivity.this, + MainActivity.class)); + finish(); + } + + /** + * @param time : time selected in Picker in 12 hours format + */ + @Override + public void setSelectedTime(String time) { + timePickButton.setText(time); + } + + /*Method to enable the done Button + *Done button is enabled if the user have setup a time + */ + @Override + public void enableDoneButton(int hr, int min) { + mDoneButton.setEnabled(true); + mHour = hr; + mMinute = min; + } + + /*Overrided Method called by the create Drug Selection Spinner to check which drug was chosen */ + @Override + public void onItemSelected(AdapterView parent, View view, int position, + long id) { + drugPickedNo = position; + parent.setSelection(parent.getSelectedItemPosition()); + } + + @Override + public void onNothingSelected(AdapterView parent) { + } + + @Override + protected void onDestroy() { + super.onDestroy(); + presenter.detachView(); + presenter = null; + } +} \ No newline at end of file diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/ProfileFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/ProfileFragment.java new file mode 100644 index 00000000..ca88a9d3 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/ProfileFragment.java @@ -0,0 +1,126 @@ +package com.peacecorps.malaria.ui.user_profile; + +import android.content.Intent; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.design.widget.TabLayout; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentPagerAdapter; +import android.support.v4.view.ViewPager; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.ui.user_profile.first_ananlysis.FirstAnalysisFragment; +import com.peacecorps.malaria.ui.user_profile.second_analysis.SecondAnalysisFragment; +import com.peacecorps.malaria.ui.user_profile.badge_screen.BadgeScreenFragment; +import com.peacecorps.malaria.ui.user_profile.edit_profile.EditProfileActivity; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by Anamika Tripathi on 8/8/18. + */ +public class ProfileFragment extends BaseFragment { + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setHasOptionsMenu(true); + } + + @Override + public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + + View view = inflater.inflate(R.layout.fragment_tabs_profile, container, false); + // Setting ViewPager for each Tabs + ViewPager viewPager = view.findViewById(R.id.viewpager); + setupViewPager(viewPager); + // Set Tabs inside Toolbar + TabLayout tabs = view.findViewById(R.id.result_tabs); + tabs.setTabGravity(TabLayout.GRAVITY_FILL); + tabs.setupWithViewPager(viewPager); + return view; + + } + + @Override + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + inflater.inflate(R.menu.menu_profile, menu); + super.onCreateOptionsMenu(menu, inflater); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle item selection + switch (item.getItemId()) { + case R.id.action_edit_profile: + startActivity(new Intent(getActivity(), EditProfileActivity.class)); + return true; + default: + return super.onOptionsItemSelected(item); + } + } + + // Add Fragments to Tabs + private void setupViewPager(ViewPager viewPager) { + Adapter adapter = new Adapter(getChildFragmentManager()); + adapter.addFragment(new FirstAnalysisFragment(), "First"); + adapter.addFragment(new SecondAnalysisFragment(), "Second"); + adapter.addFragment(new BadgeScreenFragment(), "Badge"); + viewPager.setAdapter(adapter); + } + + static class Adapter extends FragmentPagerAdapter { + private final List mFragmentList = new ArrayList<>(); + private final List mFragmentTitleList = new ArrayList<>(); + + Adapter(FragmentManager manager) { + super(manager); + } + + @Override + public Fragment getItem(int position) { + return mFragmentList.get(position); + } + + @Override + public int getCount() { + return mFragmentList.size(); + } + + void addFragment(Fragment fragment, String title) { + mFragmentList.add(fragment); + mFragmentTitleList.add(title); + } + + @Override + public CharSequence getPageTitle(int position) { + return mFragmentTitleList.get(position); + } + } + + + @Override + protected int getContentResource() { + return R.layout.fragment_tabs_profile; + } + + @Override + protected void init() { + // not needed here now, over-ridden method + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/badge_screen/BadgeScreenContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/badge_screen/BadgeScreenContract.java new file mode 100644 index 00000000..a1d96694 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/badge_screen/BadgeScreenContract.java @@ -0,0 +1,22 @@ +package com.peacecorps.malaria.ui.user_profile.badge_screen; + +import android.graphics.drawable.Drawable; + +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +/** + * Created by Anamika Tripathi on 25/7/18. + */ +public interface BadgeScreenContract { + interface BadgeMvpView extends MvpView{ + void startCategoryMedicineDialog(Drawable badgeDrawable); + void startCategoryQADialog(Drawable badgeDrawable); + } + interface BadgeMvpPresenter extends MvpPresenter { + int getUserScore(); + String getUserName(); + void selectUserBadge(); + void selectGameBadge(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/badge_screen/BadgeScreenFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/badge_screen/BadgeScreenFragment.java new file mode 100644 index 00000000..ec54dc11 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/badge_screen/BadgeScreenFragment.java @@ -0,0 +1,118 @@ +package com.peacecorps.malaria.ui.user_profile.badge_screen; + +import android.app.Dialog; +import android.content.Context; +import android.content.Intent; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.utils.InjectionClass; + +import butterknife.BindView; +import butterknife.ButterKnife; +import butterknife.OnClick; + +import static com.peacecorps.malaria.ui.user_profile.badge_screen.BadgeScreenContract.*; + +/** + * Created by Anamika Tripathi on 24/7/18. + */ +public class BadgeScreenFragment extends BaseFragment implements BadgeMvpView { + + private Dialog achievementDialog; + private Context context; + + private TextView badgeText; + private ImageView badgeImage; + @BindView(R.id.btn_achievement_medicine) + TextView achievementCatTv; + private BadgeScreenPresenter presenter; + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.badge_room, container, false); + ButterKnife.bind(this, view); + context = getContext(); + presenter = new BadgeScreenPresenter<>(InjectionClass.provideDataManager(context), context); + presenter.attachView(this); + return view; + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + init(); + } + + @Override + protected int getContentResource() { + return R.layout.badge_room; + } + + @Override + protected void init() { + setUpDialog(); + } + + //open dialog to display the current badge + private void setUpDialog() { + achievementDialog = new Dialog(context, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar); + achievementDialog.setContentView(R.layout.badge_room_dialog); + badgeText = achievementDialog.findViewById(R.id.badge_text); + badgeImage = achievementDialog.findViewById(R.id.badge_image); + achievementCatTv = achievementDialog.findViewById(R.id.achievement_category); + } + + @OnClick(R.id.btn_share_button) + public void shareButtonListener(View view) { + Intent sendIntent = new Intent(); + sendIntent.setAction(Intent.ACTION_SEND); + sendIntent.putExtra(Intent.EXTRA_TEXT, + presenter.getUserName() + " unlocked a new badge 'Champ'!! Score : " + presenter.getUserScore()); + sendIntent.setType("text/plain"); + startActivity(Intent.createChooser(sendIntent, "Share Via...")); + } + + @OnClick(R.id.btn_achievement_medicine) + public void achievementMedicineListener(View view) { + presenter.selectUserBadge(); + } + + @OnClick(R.id.btn_achievement_qa) + public void achievementQAListener(View view) { + presenter.selectGameBadge(); + } + + @Override + public void startCategoryMedicineDialog(Drawable badgeDrawable) { + achievementCatTv.setText(R.string.heading_achievement_one); + badgeText.setText(R.string.label_first_achievement); + badgeImage.setImageDrawable(badgeDrawable); + achievementDialog.show(); + } + + @Override + public void startCategoryQADialog(Drawable badgeDrawable) { + achievementCatTv.setText(R.string.heading_achievement_two); + badgeImage.setImageDrawable(badgeDrawable); + badgeText.setText(R.string.label_achievement_two); + achievementDialog.show(); + } + + @Override + public void onDestroy() { + super.onDestroy(); + presenter.detachView(); + presenter = null; + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/badge_screen/BadgeScreenPresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/badge_screen/BadgeScreenPresenter.java new file mode 100644 index 00000000..41590820 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/badge_screen/BadgeScreenPresenter.java @@ -0,0 +1,84 @@ +package com.peacecorps.malaria.ui.user_profile.badge_screen; + +import android.content.Context; +import android.graphics.drawable.Drawable; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.user_profile.badge_screen.BadgeScreenContract.BadgeMvpPresenter; +import com.peacecorps.malaria.ui.user_profile.badge_screen.BadgeScreenContract.BadgeMvpView; + +/** + * Created by Anamika Tripathi on 24/7/18. + */ +public class BadgeScreenPresenter extends BasePresenter implements BadgeMvpPresenter { + BadgeScreenPresenter(AppDataManager manager, Context context) { + super(manager, context); + } + + @Override + public void attachView(V view) { + super.attachView(view); + } + + @Override + public void detachView() { + super.detachView(); + } + + @Override + public int getUserScore() { + return getDataManager().getUserScore(); + } + + @Override + public String getUserName() { + return getDataManager().getUserName(); + } + + //get badge based on medication score + @Override + public void selectUserBadge() { + Drawable badgeDrawable; + int userScore = getDataManager().getUserScore(); + //set badge according to score + if(userScore<2){ + badgeDrawable=getContext().getResources().getDrawable(R.drawable.y_b1); + } else if(userScore<4){ + badgeDrawable=getContext().getResources().getDrawable(R.drawable.y_b3); + }else if(userScore<6){ + badgeDrawable=getContext().getResources().getDrawable(R.drawable.y_b5); + }else if(userScore<7){ + badgeDrawable=getContext().getResources().getDrawable(R.drawable.y_b6); + }else if(userScore<8){ + badgeDrawable=getContext().getResources().getDrawable(R.drawable.y_newbie); + }else { + badgeDrawable = getContext().getResources().getDrawable(R.drawable.y_hat); + } + // start the category medication dialog by setting drawable + getView().startCategoryMedicineDialog(badgeDrawable); + } + + //get badge based on game score + @Override + public void selectGameBadge() { + int gameScore = getDataManager().getGameScore(); + Drawable badgeDrawable; + //set badge according to score + if(gameScore<2){ + badgeDrawable=getContext().getResources().getDrawable(R.drawable.y_b1); + } else if(gameScore<4){ + badgeDrawable=getContext().getResources().getDrawable(R.drawable.y_b3); + }else if(gameScore<6){ + badgeDrawable=getContext().getResources().getDrawable(R.drawable.y_b5); + }else if(gameScore<8){ + badgeDrawable=getContext().getResources().getDrawable(R.drawable.y_b6); + }else if(gameScore<10){ + badgeDrawable=getContext().getResources().getDrawable(R.drawable.y_newbie); + }else{ + badgeDrawable=getContext().getResources().getDrawable(R.drawable.y_hat); + } + getView().startCategoryQADialog(badgeDrawable); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/EditProfileActivity.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/EditProfileActivity.java new file mode 100644 index 00000000..6cdd6690 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/EditProfileActivity.java @@ -0,0 +1,72 @@ +package com.peacecorps.malaria.ui.user_profile.edit_profile; + +import android.os.Bundle; +import android.support.annotation.Nullable; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentTransaction; +import android.support.v7.widget.Toolbar; +import android.view.MenuItem; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseActivity; + +/** + * Created by Anamika Tripathi on 8/8/18. + */ +public class EditProfileActivity extends BaseActivity implements UserProfileFragment.OnUserFragmentListener { + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_edit_profile); + init(); + } + + @Override + protected void init() { + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + toolbar.setTitle("Edit Profile"); + if (getSupportActionBar() != null) { + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + + Fragment fragment = new UserProfileFragment(); + loadFragment(fragment); + } + + /** + * @param fragment : replaces frame layout with parameter received in main activity + */ + private void loadFragment(Fragment fragment) { + // load fragment + FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); + transaction.replace(R.id.edit_profile_container, fragment, ""); + transaction.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK); + transaction.addToBackStack(null); + transaction.commit(); + } + + @Override + public void startHomeFragment() { + finish(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == android.R.id.home) { + // close activity + finish(); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onBackPressed() { + super.onBackPressed(); + finish(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/UserProfileContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/UserProfileContract.java new file mode 100644 index 00000000..ffc9159e --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/UserProfileContract.java @@ -0,0 +1,29 @@ +package com.peacecorps.malaria.ui.user_profile.edit_profile; + +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +/** + * Created by Anamika Tripathi on 13/7/18. + */ + +public interface UserProfileContract { + interface UserProfileMvpView extends MvpView { + void setInitialValuesIfAvailable(String name, String email, int age, String medicine); + String getUserName(); + String getUserEmail(); + String getUserAge(); + boolean checkAgeError(); + boolean checkNameError(); + boolean checkEmailError(); + } + + interface UserProfileMvpPresenter extends MvpPresenter { + void setPreviousDetails(); + void setNewDetails(String name, String email, int age); + boolean testIsEmpty(String text); + boolean isAgeValid(); + boolean isEmailValid(); + boolean checkError(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/UserProfileFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/UserProfileFragment.java new file mode 100644 index 00000000..0b8b0925 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/UserProfileFragment.java @@ -0,0 +1,202 @@ +package com.peacecorps.malaria.ui.user_profile.edit_profile; + +/* + * Created by Anamika Tripathi on 13/7/18. + */ + +import android.content.Context; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.EditText; +import android.widget.Toast; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.utils.InjectionClass; +import com.peacecorps.malaria.utils.ToastLogSnackBarUtil; + +import butterknife.BindView; +import butterknife.ButterKnife; +import butterknife.OnClick; + +public class UserProfileFragment extends BaseFragment implements UserProfileContract.UserProfileMvpView { + + private OnUserFragmentListener mListener; + private Context context; + //Butterknife variables + @BindView(R.id.edit_text_user_name) + EditText userName; + @BindView(R.id.edit_text_user_email) + EditText userEmail; + @BindView(R.id.edit_text_user_age) + EditText userAge; + @BindView(R.id.edit_text_user_medicine_type) + EditText userMedicationType; + + private UserProfilePresenter presenter; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + } + + @Override + public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + // Inflate the layout for this fragment + View view = inflater.inflate(R.layout.fragment_user_profile, container, false); + context = getContext(); + // butterknife binding + ButterKnife.bind(this, view); + // instantiating presenter, passing datamanger, view & attaching view to the presenter + presenter = new UserProfilePresenter<>(InjectionClass.provideDataManager(context), context); + presenter.attachView(this); + return view; + } + + @Override + protected int getContentResource() { + return R.layout.fragment_user_profile; + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + // initial set up for fragment after views are created + init(); + } + + // setup previous details from shared preferences + @Override + protected void init() { + presenter.setPreviousDetails(); + } + + // Container Activity must implement this interface + @Override + public void onAttach(Context context) { + super.onAttach(context); + // This makes sure that the container activity has implemented + // the callback interface. If not, it throws an exception + if (context instanceof OnUserFragmentListener) { + mListener = (OnUserFragmentListener) context; + } else { + // Show error Log for debugging & display snackbar to user + ToastLogSnackBarUtil.showErrorLog(context.toString() + " must implement OnUserFragmentListener"); + if (getActivity() != null) { + ToastLogSnackBarUtil.showSnackBar(context, getActivity().findViewById(android.R.id.content), + "Something went wrong!"); + } + } + } + + // setting null values to the listener, presenter + @Override + public void onDetach() { + super.onDetach(); + mListener = null; + presenter.detachView(); + presenter = null; + } + + // set initial details from shared preferences + @Override + public void setInitialValuesIfAvailable(String name, String email, int age, String medicine) { + if (!"".equals(name)) + userName.setText(name); + if (!"".equals(email)) + userEmail.setText(email); + if (age > 0) + userAge.setText(String.valueOf(age)); + userMedicationType.setText(medicine); + } + + // checks if edit-text is null or not, returns empty string or returns the trimmed name + @Override + public String getUserName() { + if (userName == null) { + return ""; + } else { + return userName.getText().toString().trim(); + } + } + + // checks if edit-text is null or not, returns empty string or returns the trimmed email + @Override + public String getUserEmail() { + if (userEmail == null) { + return ""; + } else { + return userEmail.getText().toString().trim(); + } + } + + // checks if edit-text is null or not, returns empty string or returns the trimmed age + @Override + public String getUserAge() { + if (userAge == null) { + return ""; + } else { + return userAge.getText().toString().trim(); + } + } + + // checks if age is valid(it is not empty & age is >0 & <=100), returns true else set error & return false + @Override + public boolean checkAgeError() { + if (presenter.isAgeValid()) { + return true; + } else { + userAge.setError(userAge.getHint()); + return false; + } + } + + // if name is not empty, return true else false & Set error message + @Override + public boolean checkNameError() { + if (presenter.testIsEmpty(getUserName())) { + userName.setError(userName.getHint()); + return false; + } + return true; + } + + // checks email validity and return true else set error message + @Override + public boolean checkEmailError() { + if (presenter.isEmailValid()) { + return true; + } else { + userEmail.setError(userEmail.getHint()); + return false; + } + } + + // save button listener + @OnClick(R.id.save_button) + public void saveButtonListener(View view) { + if (presenter.checkError()) { + // save value in preferences + presenter.setNewDetails(getUserName(), getUserEmail(), Integer.parseInt(getUserAge())); + Toast.makeText(context, "Values Saved!", Toast.LENGTH_SHORT).show(); + mListener.startHomeFragment(); + } else { + Toast.makeText(context, "Enter details again!", Toast.LENGTH_SHORT).show(); + } + } + + /** + * This interface must be implemented by activities that contain this + * fragment to allow an interaction in this fragment to be communicated + * to the activity and potentially other fragments contained in that + * activity. + */ + public interface OnUserFragmentListener { + void startHomeFragment(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/UserProfilePresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/UserProfilePresenter.java new file mode 100644 index 00000000..3c315c22 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/edit_profile/UserProfilePresenter.java @@ -0,0 +1,75 @@ +package com.peacecorps.malaria.ui.user_profile.edit_profile; + +import android.content.Context; +import android.text.TextUtils; + +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.user_profile.edit_profile.UserProfileContract.UserProfileMvpPresenter; +import com.peacecorps.malaria.ui.user_profile.edit_profile.UserProfileContract.UserProfileMvpView; + +/** + * Created by Anamika Tripathi on 13/7/18. + */ +public class UserProfilePresenter extends BasePresenter implements UserProfileMvpPresenter { + + UserProfilePresenter(AppDataManager manager, Context context) { + super(manager, context); + } + + // sets values from preferences to the edit texts + @Override + public void setPreviousDetails() { + getView().setInitialValuesIfAvailable( + getDataManager().getUserName(), + getDataManager().getUserEmail(), + getDataManager().getUserAge(), + getDataManager().getDrugPicked() + ); + } + @Override + public void attachView(V view) { + super.attachView(view); + } + + @Override + public void detachView() { + super.detachView(); + } + + // called if values are valid on done button click, saves in shared preferences + @Override + public void setNewDetails(String name, String email, int age) { + getDataManager().setUserName(name); + getDataManager().setUserEmail(email); + getDataManager().setUserAge(age); + } + + // util function for testing text is empty of not + @Override + public boolean testIsEmpty(String text) { + return TextUtils.isEmpty(text); + } + + // if age is not empty & is >0 + <=100 return true else false + @Override + public boolean isAgeValid() { + if(testIsEmpty(getView().getUserAge())) + return false; + // user age can either be empty or a number (input type is number in edit text) + int age = Integer.valueOf(getView().getUserAge()); + return age > 0 && age <= 100; + } + + // if email is not empty & matches email address pattern, return true else false + @Override + public boolean isEmailValid() { + return !testIsEmpty(getView().getUserEmail()) && android.util.Patterns.EMAIL_ADDRESS.matcher(getView().getUserEmail()).matches(); + } + + // called when save button clicked, returns true only if age, name & error are valid. + @Override + public boolean checkError() { + return getView().checkAgeError() && getView().checkNameError() && getView().checkEmailError(); + } +} \ No newline at end of file diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/first_ananlysis/FirstAnalysisContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/first_ananlysis/FirstAnalysisContract.java new file mode 100644 index 00000000..84dcac97 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/first_ananlysis/FirstAnalysisContract.java @@ -0,0 +1,25 @@ +package com.peacecorps.malaria.ui.user_profile.first_ananlysis; + +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +/** + * Created by Anamika Tripathi on 7/8/18. + */ +public interface FirstAnalysisContract { + interface FirstAnalysisMvpView extends MvpView { + void setLastTakenTime(String data); + + void setDosesText(int data); + + void setAdherenceRate(String data); + } + + interface FirstAnalysisMvpPresenter extends MvpPresenter { + void updateMediLastTime(); + + void updateDoses(); + + void getAdherenceData(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/first_ananlysis/FirstAnalysisFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/first_ananlysis/FirstAnalysisFragment.java new file mode 100644 index 00000000..b4d042aa --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/first_ananlysis/FirstAnalysisFragment.java @@ -0,0 +1,90 @@ +package com.peacecorps.malaria.ui.user_profile.first_ananlysis; + +import android.content.Context; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.ui.user_profile.first_ananlysis.FirstAnalysisContract.FirstAnalysisMvpView; +import com.peacecorps.malaria.utils.InjectionClass; + +import butterknife.BindView; +import butterknife.ButterKnife; + +/** + * Created by Anamika Tripathi on 7/8/18. + */ +public class FirstAnalysisFragment extends BaseFragment implements FirstAnalysisMvpView { + + private FirstAnalysisPresenter presenter; + + @BindView(R.id.tv_check_last_time) + TextView tvCheckMediLastTakenTime; + @BindView(R.id.tv_doses_in_row) + TextView tvDoses; + @BindView(R.id.tv_adherence) + TextView adherence; + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, + @Nullable Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_first_analytic_screen, container, false); + ButterKnife.bind(this, view); + Context context = getContext(); + presenter = new FirstAnalysisPresenter<>(InjectionClass.provideDataManager(context), context); + presenter.attachView(this); + return view; + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + init(); + } + + @Override + protected int getContentResource() { + return R.layout.fragment_first_analytic_screen; + } + + /** + * initialize everyTime this fragment's onViewCreated gets called + * calls presenter's function which further calls setter method to set data for Textview + */ + @Override + protected void init() { + presenter.updateMediLastTime(); + presenter.updateDoses(); + presenter.getAdherenceData(); + } + + /** + * @param data : string value of last time medicine was taken + * desc: sets value to checkMediLastTakenTime + */ + @Override + public void setLastTakenTime(String data) { + tvCheckMediLastTakenTime.setText(data); + } + + /** + * @param data : doses in a row value (checked before if it's weekly or daily) + * desc: sets data to doses textView + */ + @Override + public void setDosesText(int data) { + tvDoses.setText(getString(R.string.blank_text, data)); + } + + @Override + public void setAdherenceRate(String data) { + adherence.setText(data); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/first_ananlysis/FirstAnalysisPresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/first_ananlysis/FirstAnalysisPresenter.java new file mode 100644 index 00000000..97f7548f --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/first_ananlysis/FirstAnalysisPresenter.java @@ -0,0 +1,114 @@ +package com.peacecorps.malaria.ui.user_profile.first_ananlysis; + +import android.content.Context; + +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.data.db.DbHelper; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.user_profile.first_ananlysis.FirstAnalysisContract.FirstAnalysisMvpPresenter; +import com.peacecorps.malaria.ui.user_profile.first_ananlysis.FirstAnalysisContract.FirstAnalysisMvpView; +import com.peacecorps.malaria.utils.CalendarFunction; + +import java.text.DecimalFormat; +import java.util.Calendar; +import java.util.Date; + +/** + * Created by Anamika Tripathi on 7/8/18. + */ +public class FirstAnalysisPresenter extends BasePresenter implements FirstAnalysisMvpPresenter { + + FirstAnalysisPresenter(AppDataManager manager, Context context) { + super(manager, context); + } + + /** + * gets data from db, calls view's setLastTakenTime method to set on text + */ + @Override + public void updateMediLastTime() { + getDataManager().getLastTaken(new DbHelper.LoadStringCallback() { + @Override + public void onDataLoaded(String data) { + getView().setLastTakenTime(data); + } + }); + } + + /** + * Updating Doses in a Row for Weekly and Daily Pill separately + */ + @Override + public void updateDoses() { + boolean isWeekly = getDataManager().isDosesWeekly(); + if (isWeekly) { + getDataManager().getDosesInaRowWeekly(new DbHelper.LoadIntegerCallback() { + @Override + public void onDataLoaded(int value) { + getDataManager().setDosesWeekly(value); + getView().setDosesText(value); + } + }); + } else { + getDataManager().getDosesInaRowDaily(new DbHelper.LoadIntegerCallback() { + @Override + public void onDataLoaded(int value) { + getDataManager().setDosesDaily(value); + getView().setDosesText(value); + } + }); + } + } + + // Calculating Adherence & calls setAdherenceText + @Override + public void getAdherenceData() { + + //finding the interval of time between today and the 'time' + long today = new Date().getTime(); + final Date date = Calendar.getInstance().getTime(); + date.setTime(today); + + getDataManager().getFirstTimeByTimeStamp(new DbHelper.LoadLongCallback() { + @Override + public void onDataLoaded(Long takenDate) { + // calculate interval first on the basis of weekly or daily + final long interval; + if (takenDate != 0) { + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(takenDate); + + cal.add(Calendar.MONTH, 1); + Date start = cal.getTime(); + int weekDay = cal.get(Calendar.DAY_OF_WEEK); + + //calculating no. of weekdays for weekly drug + boolean isWeekly = getDataManager().isDosesWeekly(); + if (isWeekly) { + interval = CalendarFunction.getIntervalWeekly(start, date, weekDay); + } else { + //for daily drug only the no. of days + interval = CalendarFunction.getIntervalDaily(start, date); + } + getDataManager().setFirstRunTime(takenDate); + + } else { + interval = 1; + } + getDataManager().getMedicineCountTaken(new DbHelper.LoadIntegerCallback() { + @Override + public void onDataLoaded(int count) { + double adherence; + if (interval != 1) { + adherence = ((double) count / (double) interval) * 100; + } else { + adherence = 100; + } + String adherenceText = String.valueOf((new DecimalFormat("#.##").format(adherence))); + getView().setAdherenceRate(adherenceText); + } + }); + } + }); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/AnalysisModel.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/AnalysisModel.java new file mode 100644 index 00000000..1d6cb66c --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/AnalysisModel.java @@ -0,0 +1,30 @@ +package com.peacecorps.malaria.ui.user_profile.second_analysis; + +/** + * Created by Anamika Tripathi on 8/8/18. + */ +public class AnalysisModel { + private String month; + private String percentage; + + public AnalysisModel(String month, String percentage) { + this.month = month; + this.percentage = percentage; + } + + public String getMonth() { + return month; + } + + public void setMonth(String month) { + this.month = month; + } + + public String getPercentage() { + return percentage; + } + + public void setPercentage(String percentage) { + this.percentage = percentage; + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/SecondAnalysisContract.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/SecondAnalysisContract.java new file mode 100644 index 00000000..84fe20e1 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/SecondAnalysisContract.java @@ -0,0 +1,18 @@ +package com.peacecorps.malaria.ui.user_profile.second_analysis; + +import com.peacecorps.malaria.ui.base.MvpPresenter; +import com.peacecorps.malaria.ui.base.MvpView; + +/** + * Created by Anamika Tripathi on 7/8/18. + */ +public interface SecondAnalysisContract { + interface SecondAnalysisMvpView extends MvpView { + void startRecyclerView(); + } + + interface SecondAnalysisMvpPresenter extends MvpPresenter { + void getDataForProgressBar(); + + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/SecondAnalysisFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/SecondAnalysisFragment.java new file mode 100644 index 00000000..faef922a --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/SecondAnalysisFragment.java @@ -0,0 +1,64 @@ +package com.peacecorps.malaria.ui.user_profile.second_analysis; + +import android.content.Context; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.ui.base.BaseFragment; +import com.peacecorps.malaria.ui.user_profile.second_analysis.SecondAnalysisContract.SecondAnalysisMvpView; +import com.peacecorps.malaria.utils.InjectionClass; + +import butterknife.BindView; +import butterknife.ButterKnife; + +/** + * Created by Anamika Tripathi on 7/8/18. + */ +public class SecondAnalysisFragment extends BaseFragment implements SecondAnalysisMvpView { + private SecondAnalysisPresenter presenter; + @BindView(R.id.rv_timeline) + RecyclerView recyclerView; + private Context context; + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, + @Nullable Bundle savedInstanceState) { + View view = inflater.inflate(R.layout.fragment_second_analytic_screen, container, false); + ButterKnife.bind(this, view); + context = getContext(); + presenter = new SecondAnalysisPresenter<>(InjectionClass.provideDataManager(context), context); + presenter.attachView(this); + return view; + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + init(); + } + + @Override + protected int getContentResource() { + return R.layout.fragment_second_analytic_screen; + } + + @Override + protected void init() { + presenter.getDataForProgressBar(); + } + + @Override + public void startRecyclerView() { + recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); + TimelineAdapter adapter = new TimelineAdapter(presenter, context); + recyclerView.setAdapter(adapter); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/SecondAnalysisPresenter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/SecondAnalysisPresenter.java new file mode 100644 index 00000000..1e22f92c --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/SecondAnalysisPresenter.java @@ -0,0 +1,190 @@ +package com.peacecorps.malaria.ui.user_profile.second_analysis; + +import android.content.Context; + +import com.peacecorps.malaria.R; +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.data.db.DbHelper; +import com.peacecorps.malaria.data.db.entities.AlarmTime; +import com.peacecorps.malaria.ui.base.BasePresenter; +import com.peacecorps.malaria.ui.user_profile.second_analysis.SecondAnalysisContract.SecondAnalysisMvpPresenter; +import com.peacecorps.malaria.ui.user_profile.second_analysis.SecondAnalysisContract.SecondAnalysisMvpView; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +/** + * Created by Anamika Tripathi on 7/8/18. + */ +public class SecondAnalysisPresenter extends BasePresenter implements SecondAnalysisMvpPresenter { + private int mDate; + private int mYear; + private final int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, + 31, 30, 31}; + private String[] monthList; + + private List dataList; + + SecondAnalysisPresenter(AppDataManager manager, Context context) { + super(manager, context); + dataList = new ArrayList<>(); + monthList = getContext().getResources().getStringArray(R.array.array_month); + } + + @Override + public void getDataForProgressBar() { + + getDataManager().getAlarmData(new DbHelper.LoadAlarmDataCallback() { + @Override + public void onDataLoaded(AlarmTime time) { + final int setUpMonth = time.getMonth(); + final int setUpYear = time.getYear(); + getAnalysisData(setUpMonth, setUpYear); + } + }); + } + + private void getAnalysisData(final int setUpMonth, final int setUpYear) { + final int date = Calendar.getInstance().get(Calendar.MONTH); + final String choice; + final boolean isWeekly = getDataManager().isDosesWeekly(); + //checking choice of pill whether weekly or daily + if (isWeekly) { + choice = "weekly"; + } else { + choice = "daily"; + } + + fourthMonthData(setUpMonth, setUpYear, date, choice, isWeekly); + thirdMonthData(setUpMonth, setUpYear, date, choice, isWeekly); + secondMonthData(setUpMonth, setUpYear, date, choice, isWeekly); + firstMonthData(setUpMonth, setUpYear, date, choice, isWeekly); + + } + + private void fourthMonthData(final int setUpMonth, final int setUpYear, final int date, String choice, final boolean isWeekly) { + final String fourthMonth = getMonth(date); + getDataManager().getCountForProgressBar(mDate, mYear, "yes", choice, new DbHelper.LoadIntegerCallback() { + @Override + public void onDataLoaded(int count) { + float progressPercentage; + if (!isWeekly) { + progressPercentage = (float) count / getNumberOfDaysInMonth(mDate) * 100; + } else { + progressPercentage = count * 25; + } + String fourthPer; + if ((date - 1) >= setUpMonth || mYear != setUpYear || progressPercentage != 0) { + fourthPer = "" + (int) progressPercentage + "%"; + } else { + fourthPer = "N.A"; + } + dataList.add(new AnalysisModel(fourthMonth, fourthPer)); + } + }); + } + + private void thirdMonthData(final int setUpMonth, final int setUpYear, final int date, final String choice, final boolean isWeekly) { + final String thirdMonth = getMonth(date - 1); + getDataManager().getCountForProgressBar(mDate, mYear, "yes", choice, new DbHelper.LoadIntegerCallback() { + @Override + public void onDataLoaded(int count) { + float progressPercentage; + if (!isWeekly) { + progressPercentage = (float) count / getNumberOfDaysInMonth(mDate) * 100; + } else { + progressPercentage = count * 25; + } + String thirdPer; + if ((date - 1) >= setUpMonth || mYear != setUpYear || progressPercentage != 0) { + thirdPer = "" + (int) progressPercentage; + } else { + thirdPer = "N.A"; + } + dataList.add(new AnalysisModel(thirdMonth, thirdPer)); + } + }); + } + + private void secondMonthData(final int setUpMonth, final int setUpYear, final int date, final String choice, final boolean isWeekly) { + final String secondMonth = getMonth(date - 2); + getDataManager().getCountForProgressBar(mDate, mYear, "yes", choice, new DbHelper.LoadIntegerCallback() { + @Override + public void onDataLoaded(int count) { + float progressPercentage; + if (!isWeekly) { + progressPercentage = (float) count / getNumberOfDaysInMonth(mDate) * 100; + } else { + progressPercentage = count * 25; + } + String secondPer; + if ((date - 2) >= setUpMonth || mYear != setUpYear || progressPercentage != 0) { + secondPer = "" + (int) progressPercentage; + } else { + secondPer = "N.A"; + } + dataList.add(new AnalysisModel(secondMonth, secondPer)); + } + }); + } + + private void firstMonthData(final int setUpMonth, final int setUpYear, final int date, final String choice, final boolean isWeekly) { + final String firstMonth = getMonth(date - 3); + + getDataManager().getCountForProgressBar(mDate, mYear, "yes", choice, + new DbHelper.LoadIntegerCallback() { + @Override + public void onDataLoaded(int count) { + float progressPercentage; + if (!isWeekly) { + progressPercentage = (float) count / getNumberOfDaysInMonth(mDate) * 100; + } else { + progressPercentage = count * 25; + } + String firstPer; + if ((date - 3) >= setUpMonth || mYear != setUpYear || progressPercentage != 0) { + firstPer = "" + (int) progressPercentage; + } else { + firstPer = "N.A"; + } + dataList.add(new AnalysisModel(firstMonth, firstPer)); + getView().startRecyclerView(); + + } + }); + } + + //finding month from its integer + private String getMonth(int date) { + int d; + if (date == -1) { + d = 11; + mYear = Calendar.getInstance().get(Calendar.YEAR) - 1; + } else if (date == -2) { + d = 10; + mYear = Calendar.getInstance().get(Calendar.YEAR) - 1; + } else if (date == -3) { + d = 9; + mYear = Calendar.getInstance().get(Calendar.YEAR) - 1; + } else { + d = date; + mYear = Calendar.getInstance().get(Calendar.YEAR); + mDate = date; + } + return monthList[d]; + } + + /*Finding No. of Days in Month*/ + private int getNumberOfDaysInMonth(int month) { + return daysOfMonth[month]; + } + + public List getDataList() { + return dataList; + } + + public void setDataList(List dataList) { + this.dataList = dataList; + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/TimelineAdapter.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/TimelineAdapter.java new file mode 100644 index 00000000..d4d272c8 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/ui/user_profile/second_analysis/TimelineAdapter.java @@ -0,0 +1,67 @@ +package com.peacecorps.malaria.ui.user_profile.second_analysis; + +import android.content.Context; +import android.support.annotation.NonNull; +import android.support.v7.widget.RecyclerView; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.github.vipulasri.timelineview.TimelineView; +import com.peacecorps.malaria.R; + +/** + * Created by Anamika Tripathi on 11/8/18. + */ +public class TimelineAdapter extends RecyclerView.Adapter { + + private SecondAnalysisPresenter presenter; + private Context context; + + TimelineAdapter(SecondAnalysisPresenter presenter, Context context) { + this.presenter = presenter; + this.context = context; + } + + @NonNull + @Override + public TimelineHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View view; + view = View.inflate(context, R.layout.item_analysis_timeline, null); + return new TimelineHolder(view, viewType); + } + + @Override + public void onBindViewHolder(@NonNull TimelineHolder holder, int position) { + holder.description.setText(presenter.getDataList().get(position).getPercentage()); + holder.title.setText(presenter.getDataList().get(position).getMonth()); + } + + + @Override + public int getItemCount() { + if (presenter.getDataList() == null) + return 0; + return presenter.getDataList().size(); + } + + @Override + public int getItemViewType(int position) { + return TimelineView.getTimeLineViewType(position,getItemCount()); + } + + class TimelineHolder extends RecyclerView.ViewHolder { + + private TimelineView timelineView; + private TextView title, description; + + TimelineHolder(View itemView, int viewType) { + super(itemView); + timelineView = itemView.findViewById(R.id.time_marker); + title = itemView.findViewById(R.id.text_timeline_title); + description = itemView.findViewById(R.id.text_timeline_description); + timelineView.initLine(viewType); + } + + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/AppExecutors.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/AppExecutors.java new file mode 100644 index 00000000..d0c72fa3 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/AppExecutors.java @@ -0,0 +1,61 @@ +package com.peacecorps.malaria.utils; + +import android.os.Handler; +import android.os.Looper; +import android.support.annotation.NonNull; +import android.support.annotation.VisibleForTesting; + +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +public class AppExecutors implements Executor { + private final Executor mDiskIO; + private final Executor mainThreadExecutor; + @Override + public void execute(@NonNull Runnable command) { + mDiskIO.execute(command); + + } + + @VisibleForTesting + private AppExecutors(Executor diskIO, Executor mainThread) { + this.mDiskIO = diskIO; + this.mainThreadExecutor = mainThread; + } + + AppExecutors() { + this(new DiskIOThreadExecutor(),new MainThreadExecutor()); + } + + + public Executor diskIO() { + return mDiskIO; + } + + public Executor mainThread() { + return mainThreadExecutor; + } + + private static class MainThreadExecutor implements Executor { + private Handler mainThreadHandler = new Handler(Looper.getMainLooper()); + + @Override + public void execute(@NonNull Runnable command) { + mainThreadHandler.post(command); + } + } + + private static class DiskIOThreadExecutor implements Executor { + + private final Executor mDiskIO; + + DiskIOThreadExecutor() { + mDiskIO = Executors.newSingleThreadExecutor(); + } + + @Override + public void execute(@NonNull Runnable command) { + mDiskIO.execute(command); + } + } +} diff --git a/src/com/peacecorps/malaria/AuthJSONObjectRequest.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/AuthJSONObjectRequest.java similarity index 96% rename from src/com/peacecorps/malaria/AuthJSONObjectRequest.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/utils/AuthJSONObjectRequest.java index 8a27d5ce..db0e2f79 100644 --- a/src/com/peacecorps/malaria/AuthJSONObjectRequest.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/AuthJSONObjectRequest.java @@ -1,4 +1,4 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.utils; /** * Created by Ankita on 6/8/2015. diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/BottomNavigationViewHelper.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/BottomNavigationViewHelper.java new file mode 100644 index 00000000..6b4821d8 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/BottomNavigationViewHelper.java @@ -0,0 +1,37 @@ +package com.peacecorps.malaria.utils; + +import android.annotation.SuppressLint; +import android.support.design.internal.BottomNavigationItemView; +import android.support.design.internal.BottomNavigationMenuView; +import android.support.design.widget.BottomNavigationView; +import android.util.Log; + +import java.lang.reflect.Field; + +/** + * Created by Anamika Tripathi on 13/7/18. + */ +public class BottomNavigationViewHelper { + @SuppressLint("RestrictedApi") + public static void disableShiftMode(BottomNavigationView view) { + BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0); + try { + Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode"); + shiftingMode.setAccessible(true); + shiftingMode.setBoolean(menuView, false); + shiftingMode.setAccessible(false); + for (int i = 0; i < menuView.getChildCount(); i++) { + BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i); + //noinspection RestrictedApi + item.setShiftingMode(false); + // set once again checked value, so view will be updated + //noinspection RestrictedApi + item.setChecked(item.getItemData().isChecked()); + } + } catch (NoSuchFieldException e) { + Log.e("BNVHelper", "Unable to get shift mode field", e); + } catch (IllegalAccessException e) { + Log.e("BNVHelper", "Unable to change value of shift mode", e); + } + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/CalendarFunction.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/CalendarFunction.java new file mode 100644 index 00000000..2eebba0e --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/CalendarFunction.java @@ -0,0 +1,129 @@ +package com.peacecorps.malaria.utils; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +public class CalendarFunction { + + private static final int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, + 31, 30, 31}; + private static final int[] daysOfMonthLeap = {31, 29, 31, 30, 31, 30, 31, 31, 30, + 31, 30, 31}; + + /** + * Method to give no. of days in month. + */ + public static int getNumberOfDaysInMonth(int month, int year) { + if (isLeapYear(year)) { + return daysOfMonthLeap[month]; + } else { + return daysOfMonth[month]; + } + } + + /** + * Check whether it is a leap layer + **/ + private static boolean isLeapYear(int year) { + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.YEAR, year); + return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365; + } + + /*Setting the Date Object to Human Readable Format**/ + public static String getHumanDateFormat(String ats, int aMonth) { + String aYear = ats.substring(0, 4); + String aDate = ats.substring(Math.max(ats.length() - 2, 0)); + return aYear + "-" + aMonth + "-" + aDate; + } + + /*Getting the Date Object from the String**/ + public static Date getDateObject(String s) { + Date dobj = null; + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()); + try { + dobj = sdf.parse(s); + } catch (ParseException e) { + ToastLogSnackBarUtil.showErrorLog("CalendarFunction: Simple Date Format exception"); + } + return dobj; + } + + /*Getting the Day of Week from the String**/ + public static int getDayofWeek(Date d) { + Calendar cal = Calendar.getInstance(); + cal.setTime(d); + return cal.get(Calendar.DAY_OF_WEEK); + } + + /*Getting no. of Days between two interval**/ + public static long getNumberOfDays(Date d1, Date d2) { + long interval = 0; + Calendar c = Calendar.getInstance(); + c.setTime(d1); + long ld1 = c.getTimeInMillis(); + c.setTime(d2); + long ld2 = c.getTimeInMillis(); + long oneDay = 1000 * 60 * 60 * 24; + interval = (ld2 - ld1) / oneDay; + return interval; + } + + /** + * Finding the No. of weekly days between two dates for calculating Adherence + **/ + public static int getIntervalWeekly(Date s, Date e, int weekday) { + Calendar startCal; + Calendar endCal; + startCal = Calendar.getInstance(); + startCal.setTime(s); + endCal = Calendar.getInstance(); + endCal.setTime(e); + int medDays = 0; + //If working dates are same,then checking what is the day on that date. + if ((startCal.getTimeInMillis() == endCal.getTimeInMillis()) && (startCal.get(Calendar.DAY_OF_WEEK) == weekday)) { + ++medDays; + return medDays; + } + /*If start date is coming after end date, Then shuffling Dates and storing dates + by incrementing upto end date in do-while part.*/ + if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) { + startCal.setTime(e); + endCal.setTime(s); + } + + do { + + if (startCal.get(Calendar.DAY_OF_WEEK) == weekday) { + ++medDays; + } + startCal.add(Calendar.DAY_OF_MONTH, 1); + } while (startCal.getTimeInMillis() <= endCal.getTimeInMillis()); + + if (startCal.get(Calendar.DAY_OF_WEEK) == endCal.get(Calendar.DAY_OF_WEEK) && (startCal.get(Calendar.DAY_OF_WEEK) == weekday)) + ++medDays; + + return medDays; + } + + /** + * Finding the No. of days between two dates for calculating adherence of daily drugs + **/ + public static int getIntervalDaily(Date s, Date e) { + long sLong = s.getTime(); + long eLong = e.getTime(); + + long oneDay = 24 * 60 * 60 * 1000; + + long interval = (eLong - sLong) / oneDay; + + return (int) interval + 1; + + } + + +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/Constants.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/Constants.java new file mode 100644 index 00000000..622afc50 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/Constants.java @@ -0,0 +1,7 @@ +package com.peacecorps.malaria.utils; + +import com.peacecorps.malaria.R; + +public class Constants { + public static Integer[] imageID = {R.drawable.mal, R.drawable.doxy, R.drawable.mef}; +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/DatePickerFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/DatePickerFragment.java new file mode 100644 index 00000000..9bfbcc95 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/DatePickerFragment.java @@ -0,0 +1,42 @@ +package com.peacecorps.malaria.utils; + +import android.app.DatePickerDialog; +import android.app.Dialog; +import android.os.Bundle; +import android.support.annotation.NonNull; +import android.support.v4.app.DialogFragment; + +import com.peacecorps.malaria.R; + +import java.util.Calendar; + +/** + * Created by Anamika Tripathi on 28/7/18. + */ +public class DatePickerFragment extends DialogFragment { + private DatePickerDialog.OnDateSetListener ondateSet; + + public void setCallBack(DatePickerDialog.OnDateSetListener ondate) { + ondateSet = ondate; + } + + @NonNull + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + /* + * Set Up Current Date Into dialog + */ + Calendar calender = Calendar.getInstance(); + int year = calender.get(Calendar.YEAR); + int month = calender.get(Calendar.MONTH); + int day = calender.get(Calendar.DAY_OF_MONTH); + + if (getActivity() != null) { + return new DatePickerDialog(getActivity(), R.style.MyDatePicker, ondateSet, year, month, day); + } else { + ToastLogSnackBarUtil.showToast(getContext(), "Something went wrong! Please try again"); + ToastLogSnackBarUtil.showErrorLog("getActivity is null"); + return null; + } + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/InjectionClass.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/InjectionClass.java new file mode 100644 index 00000000..0de173f0 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/InjectionClass.java @@ -0,0 +1,25 @@ +package com.peacecorps.malaria.utils; + +import android.content.Context; + +import com.peacecorps.malaria.data.AppDataManager; +import com.peacecorps.malaria.data.db.AppDatabase; +import com.peacecorps.malaria.data.db.AppDbHelper; +import com.peacecorps.malaria.data.prefs.AppPreferencesHelper; + + +public class InjectionClass { + + private static AppDbHelper provideSqliteHelper(Context context) { + AppDatabase database = AppDatabase.getAppDatabase(context); + return AppDbHelper.getInstance(new AppExecutors(), database.appSettingDao(), database.locationDao(), database.packingDao(), + database.userMedicineDao(), database.alarmDao()); + } + + public static AppDataManager provideDataManager(Context context) { + return new AppDataManager(provideSqliteHelper(context), + new AppPreferencesHelper(context, "malairia-pref-file")); + } + + +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/TimePickerFragment.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/TimePickerFragment.java new file mode 100644 index 00000000..bbbec07f --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/TimePickerFragment.java @@ -0,0 +1,42 @@ +package com.peacecorps.malaria.utils; + +import android.app.Dialog; +import android.app.DialogFragment; +import android.app.TimePickerDialog; +import android.os.Bundle; +import android.text.format.DateFormat; + +import com.peacecorps.malaria.R; + +import java.util.Calendar; + + +/** + * Created by Anamika Tripathi on 27/7/18. + */ +public class TimePickerFragment extends DialogFragment { + + private TimePickerDialog.OnTimeSetListener listener; + + public void setCallBack(TimePickerDialog.OnTimeSetListener timeSetListener) { + listener = timeSetListener; + } + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + /* + * Set Up Current Date Into dialog + */ + Calendar calender = Calendar.getInstance(); + int hour = calender.get(Calendar.HOUR_OF_DAY); + int minute = calender.get(Calendar.MINUTE); + + if (getActivity() != null) { + return new TimePickerDialog(getActivity(), R.style.MyTimePicker, listener, hour, minute, + DateFormat.is24HourFormat(getActivity())); + } else { + ToastLogSnackBarUtil.showErrorLog("getActivity is null"); + return null; + } + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/ToastLogSnackBarUtil.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/ToastLogSnackBarUtil.java new file mode 100644 index 00000000..52cce603 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/ToastLogSnackBarUtil.java @@ -0,0 +1,40 @@ +package com.peacecorps.malaria.utils; + +import android.content.Context; +import android.support.design.widget.Snackbar; +import android.support.v4.content.ContextCompat; +import android.util.Log; +import android.view.View; +import android.widget.TextView; +import android.widget.Toast; + +import com.peacecorps.malaria.R; + +/** + * Created by Anamika Tripathi on 18/7/18. + */ +public class ToastLogSnackBarUtil { + + private static final String TAG = "myTag"; + + public static void showToast(Context context, String message) { + Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); + } + + public static void showDebugLog(String message) { + Log.d(TAG, message); + } + + public static void showErrorLog(String message) { + Log.e(TAG, message); + } + + public static void showSnackBar(Context context, View view, String s) { + Snackbar snack = Snackbar.make(view, s, Snackbar.LENGTH_SHORT); + View sbview = snack.getView(); + sbview.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary)); + TextView textView = sbview.findViewById(android.support.design.R.id.snackbar_text); + textView.setTextColor(ContextCompat.getColor(context, R.color.textColorPrimary)); + snack.show(); + } +} diff --git a/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/TypefaceUtil.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/TypefaceUtil.java new file mode 100644 index 00000000..eb974189 --- /dev/null +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/TypefaceUtil.java @@ -0,0 +1,29 @@ +package com.peacecorps.malaria.utils; + +import android.content.Context; +import android.graphics.Typeface; + +import java.lang.reflect.Field; + +/** + * Created by Anamika Tripathi on 7/8/18. + */ +public class TypefaceUtil { + + /** + * @param context to work with assets + * @param defaultFontNameToOverride for example "serif" + * @param customFontFileNameInAssets file name of the font from assets + */ + public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) { + try { + final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets); + + final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride); + defaultFontTypefaceField.setAccessible(true); + defaultFontTypefaceField.set(null, customFontTypeface); + } catch (Exception e) { + ToastLogSnackBarUtil.showErrorLog("Can't set custom font instead!"); + } + } +} \ No newline at end of file diff --git a/src/com/peacecorps/malaria/VolleyApplication.java b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/VolleyApplication.java similarity index 97% rename from src/com/peacecorps/malaria/VolleyApplication.java rename to malaria-app-android/src/main/java/com/peacecorps/malaria/utils/VolleyApplication.java index fec8fab0..c55ee961 100644 --- a/src/com/peacecorps/malaria/VolleyApplication.java +++ b/malaria-app-android/src/main/java/com/peacecorps/malaria/utils/VolleyApplication.java @@ -1,4 +1,4 @@ -package com.peacecorps.malaria; +package com.peacecorps.malaria.utils; /** * Created by Ankita on 6/8/2015. diff --git a/malaria-app-android/src/main/res/color/bnv_tab_item_foreground.xml b/malaria-app-android/src/main/res/color/bnv_tab_item_foreground.xml new file mode 100644 index 00000000..387aa320 --- /dev/null +++ b/malaria-app-android/src/main/res/color/bnv_tab_item_foreground.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/malaria-app-android/src/main/res/drawable-hdpi/action_cancel.png b/malaria-app-android/src/main/res/drawable-hdpi/action_cancel.png new file mode 100644 index 00000000..99a18c6a Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-hdpi/action_cancel.png differ diff --git a/malaria-app-android/src/main/res/drawable-hdpi/action_edit_account.png b/malaria-app-android/src/main/res/drawable-hdpi/action_edit_account.png new file mode 100644 index 00000000..be070986 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-hdpi/action_edit_account.png differ diff --git a/malaria-app-android/src/main/res/drawable-hdpi/action_medicine_store.png b/malaria-app-android/src/main/res/drawable-hdpi/action_medicine_store.png new file mode 100644 index 00000000..f667c003 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-hdpi/action_medicine_store.png differ diff --git a/malaria-app-android/src/main/res/drawable-hdpi/action_save.png b/malaria-app-android/src/main/res/drawable-hdpi/action_save.png new file mode 100644 index 00000000..0b1fc4dc Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-hdpi/action_save.png differ diff --git a/malaria-app-android/src/main/res/drawable-hdpi/btn_reset.png b/malaria-app-android/src/main/res/drawable-hdpi/btn_reset.png new file mode 100644 index 00000000..3b5f4e3e Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-hdpi/btn_reset.png differ diff --git a/malaria-app-android/src/main/res/drawable-hdpi/ic_action_volume_on.png b/malaria-app-android/src/main/res/drawable-hdpi/ic_action_volume_on.png new file mode 100644 index 00000000..1beedb6e Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-hdpi/ic_action_volume_on.png differ diff --git a/malaria-app-android/src/main/res/drawable-hdpi/ic_cancel_black_18dp.png b/malaria-app-android/src/main/res/drawable-hdpi/ic_cancel_black_18dp.png new file mode 100644 index 00000000..39af2767 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-hdpi/ic_cancel_black_18dp.png differ diff --git a/malaria-app-android/src/main/res/drawable-hdpi/ic_done_black_18dp.png b/malaria-app-android/src/main/res/drawable-hdpi/ic_done_black_18dp.png new file mode 100644 index 00000000..e530a1f1 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-hdpi/ic_done_black_18dp.png differ diff --git a/malaria-app-android/src/main/res/drawable-hdpi/ic_snooze_black_18dp.png b/malaria-app-android/src/main/res/drawable-hdpi/ic_snooze_black_18dp.png new file mode 100644 index 00000000..4cf8841c Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-hdpi/ic_snooze_black_18dp.png differ diff --git a/res/drawable-hdpi/pc_logo.png b/malaria-app-android/src/main/res/drawable-hdpi/pc_logo.png similarity index 100% rename from res/drawable-hdpi/pc_logo.png rename to malaria-app-android/src/main/res/drawable-hdpi/pc_logo.png diff --git a/res/drawable-ldpi/pc_logo.png b/malaria-app-android/src/main/res/drawable-ldpi/pc_logo.png similarity index 100% rename from res/drawable-ldpi/pc_logo.png rename to malaria-app-android/src/main/res/drawable-ldpi/pc_logo.png diff --git a/malaria-app-android/src/main/res/drawable-mdpi/action_cancel.png b/malaria-app-android/src/main/res/drawable-mdpi/action_cancel.png new file mode 100644 index 00000000..4022c104 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/action_cancel.png differ diff --git a/malaria-app-android/src/main/res/drawable-mdpi/action_edit_account.png b/malaria-app-android/src/main/res/drawable-mdpi/action_edit_account.png new file mode 100644 index 00000000..29fa671e Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/action_edit_account.png differ diff --git a/malaria-app-android/src/main/res/drawable-mdpi/action_medicine_store.png b/malaria-app-android/src/main/res/drawable-mdpi/action_medicine_store.png new file mode 100644 index 00000000..87c9364c Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/action_medicine_store.png differ diff --git a/malaria-app-android/src/main/res/drawable-mdpi/action_save.png b/malaria-app-android/src/main/res/drawable-mdpi/action_save.png new file mode 100644 index 00000000..c63e481c Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/action_save.png differ diff --git a/malaria-app-android/src/main/res/drawable-mdpi/btn_add.png b/malaria-app-android/src/main/res/drawable-mdpi/btn_add.png new file mode 100644 index 00000000..a7f943eb Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/btn_add.png differ diff --git a/malaria-app-android/src/main/res/drawable-mdpi/btn_delete.png b/malaria-app-android/src/main/res/drawable-mdpi/btn_delete.png new file mode 100644 index 00000000..046243fa Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/btn_delete.png differ diff --git a/malaria-app-android/src/main/res/drawable-mdpi/btn_drop_down.png b/malaria-app-android/src/main/res/drawable-mdpi/btn_drop_down.png new file mode 100644 index 00000000..f97bb580 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/btn_drop_down.png differ diff --git a/malaria-app-android/src/main/res/drawable-mdpi/btn_reset.png b/malaria-app-android/src/main/res/drawable-mdpi/btn_reset.png new file mode 100644 index 00000000..b58f0fb0 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/btn_reset.png differ diff --git a/res/drawable-mdpi/custom_line_border.xml b/malaria-app-android/src/main/res/drawable-mdpi/custom_line_border.xml similarity index 100% rename from res/drawable-mdpi/custom_line_border.xml rename to malaria-app-android/src/main/res/drawable-mdpi/custom_line_border.xml diff --git a/malaria-app-android/src/main/res/drawable-mdpi/ic_action_volume_on.png b/malaria-app-android/src/main/res/drawable-mdpi/ic_action_volume_on.png new file mode 100644 index 00000000..1beedb6e Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/ic_action_volume_on.png differ diff --git a/malaria-app-android/src/main/res/drawable-mdpi/ic_cancel.png b/malaria-app-android/src/main/res/drawable-mdpi/ic_cancel.png new file mode 100644 index 00000000..ac867073 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/ic_cancel.png differ diff --git a/malaria-app-android/src/main/res/drawable-mdpi/ic_cancel_black_18dp.png b/malaria-app-android/src/main/res/drawable-mdpi/ic_cancel_black_18dp.png new file mode 100644 index 00000000..a57ec6f0 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/ic_cancel_black_18dp.png differ diff --git a/malaria-app-android/src/main/res/drawable-mdpi/ic_done_black_18dp.png b/malaria-app-android/src/main/res/drawable-mdpi/ic_done_black_18dp.png new file mode 100644 index 00000000..72fd5732 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/ic_done_black_18dp.png differ diff --git a/malaria-app-android/src/main/res/drawable-mdpi/ic_snooze_black_18dp.png b/malaria-app-android/src/main/res/drawable-mdpi/ic_snooze_black_18dp.png new file mode 100644 index 00000000..c5ee7389 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-mdpi/ic_snooze_black_18dp.png differ diff --git a/res/drawable-mdpi/pc_logo.png b/malaria-app-android/src/main/res/drawable-mdpi/pc_logo.png similarity index 100% rename from res/drawable-mdpi/pc_logo.png rename to malaria-app-android/src/main/res/drawable-mdpi/pc_logo.png diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/account_circle.png b/malaria-app-android/src/main/res/drawable-xhdpi/account_circle.png new file mode 100644 index 00000000..e413a2ed Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/account_circle.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/action_cancel.png b/malaria-app-android/src/main/res/drawable-xhdpi/action_cancel.png new file mode 100644 index 00000000..2408b9a4 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/action_cancel.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/action_edit_account.png b/malaria-app-android/src/main/res/drawable-xhdpi/action_edit_account.png new file mode 100644 index 00000000..a12a9151 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/action_edit_account.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/action_medicine_store.png b/malaria-app-android/src/main/res/drawable-xhdpi/action_medicine_store.png new file mode 100644 index 00000000..7f115676 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/action_medicine_store.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/action_save.png b/malaria-app-android/src/main/res/drawable-xhdpi/action_save.png new file mode 100644 index 00000000..abc3201a Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/action_save.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/bnv_home.png b/malaria-app-android/src/main/res/drawable-xhdpi/bnv_home.png new file mode 100644 index 00000000..202a3ae2 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/bnv_home.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/bnv_info_button.png b/malaria-app-android/src/main/res/drawable-xhdpi/bnv_info_button.png new file mode 100644 index 00000000..a2a91619 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/bnv_info_button.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/bnv_play_button.png b/malaria-app-android/src/main/res/drawable-xhdpi/bnv_play_button.png new file mode 100644 index 00000000..4d3da16e Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/bnv_play_button.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/bnv_trip_button.png b/malaria-app-android/src/main/res/drawable-xhdpi/bnv_trip_button.png new file mode 100644 index 00000000..957ede91 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/bnv_trip_button.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/btn_calendar.png b/malaria-app-android/src/main/res/drawable-xhdpi/btn_calendar.png new file mode 100644 index 00000000..9ec955ba Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/btn_calendar.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/btn_location_history.png b/malaria-app-android/src/main/res/drawable-xhdpi/btn_location_history.png new file mode 100644 index 00000000..75990bc0 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/btn_location_history.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/btn_reset.png b/malaria-app-android/src/main/res/drawable-xhdpi/btn_reset.png new file mode 100644 index 00000000..fd1d45d2 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/btn_reset.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/btn_share.png b/malaria-app-android/src/main/res/drawable-xhdpi/btn_share.png new file mode 100644 index 00000000..8736c74e Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/btn_share.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/calendar.png b/malaria-app-android/src/main/res/drawable-xhdpi/calendar.png new file mode 100644 index 00000000..ab5a61d1 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/calendar.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/clock.png b/malaria-app-android/src/main/res/drawable-xhdpi/clock.png new file mode 100644 index 00000000..65e390f2 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/clock.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/ic_action_volume_on.png b/malaria-app-android/src/main/res/drawable-xhdpi/ic_action_volume_on.png new file mode 100644 index 00000000..1beedb6e Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/ic_action_volume_on.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/ic_cancel_black_18dp.png b/malaria-app-android/src/main/res/drawable-xhdpi/ic_cancel_black_18dp.png new file mode 100644 index 00000000..1669ea3d Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/ic_cancel_black_18dp.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/ic_done_black_18dp.png b/malaria-app-android/src/main/res/drawable-xhdpi/ic_done_black_18dp.png new file mode 100644 index 00000000..f663b107 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/ic_done_black_18dp.png differ diff --git a/malaria-app-android/src/main/res/drawable-xhdpi/ic_snooze_black_18dp.png b/malaria-app-android/src/main/res/drawable-xhdpi/ic_snooze_black_18dp.png new file mode 100644 index 00000000..1a8ec6ce Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xhdpi/ic_snooze_black_18dp.png differ diff --git a/res/drawable-xhdpi/pc_logo.png b/malaria-app-android/src/main/res/drawable-xhdpi/pc_logo.png similarity index 100% rename from res/drawable-xhdpi/pc_logo.png rename to malaria-app-android/src/main/res/drawable-xhdpi/pc_logo.png diff --git a/malaria-app-android/src/main/res/drawable-xxhdpi/action_cancel.png b/malaria-app-android/src/main/res/drawable-xxhdpi/action_cancel.png new file mode 100644 index 00000000..6f7c1fba Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxhdpi/action_cancel.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxhdpi/action_edit_account.png b/malaria-app-android/src/main/res/drawable-xxhdpi/action_edit_account.png new file mode 100644 index 00000000..19b61453 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxhdpi/action_edit_account.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxhdpi/action_medicine_store.png b/malaria-app-android/src/main/res/drawable-xxhdpi/action_medicine_store.png new file mode 100644 index 00000000..7b062392 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxhdpi/action_medicine_store.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxhdpi/action_save.png b/malaria-app-android/src/main/res/drawable-xxhdpi/action_save.png new file mode 100644 index 00000000..1d038f62 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxhdpi/action_save.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxhdpi/btn_reset.png b/malaria-app-android/src/main/res/drawable-xxhdpi/btn_reset.png new file mode 100644 index 00000000..34f75606 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxhdpi/btn_reset.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxhdpi/ic_action_volume_on.png b/malaria-app-android/src/main/res/drawable-xxhdpi/ic_action_volume_on.png new file mode 100644 index 00000000..1beedb6e Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxhdpi/ic_action_volume_on.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxhdpi/ic_cancel_black_18dp.png b/malaria-app-android/src/main/res/drawable-xxhdpi/ic_cancel_black_18dp.png new file mode 100644 index 00000000..07b20d36 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxhdpi/ic_cancel_black_18dp.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxhdpi/ic_done_black_18dp.png b/malaria-app-android/src/main/res/drawable-xxhdpi/ic_done_black_18dp.png new file mode 100644 index 00000000..f054c308 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxhdpi/ic_done_black_18dp.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxhdpi/ic_snooze_black_18dp.png b/malaria-app-android/src/main/res/drawable-xxhdpi/ic_snooze_black_18dp.png new file mode 100644 index 00000000..7083c5c0 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxhdpi/ic_snooze_black_18dp.png differ diff --git a/res/drawable-xxhdpi/pc_logo.png b/malaria-app-android/src/main/res/drawable-xxhdpi/pc_logo.png similarity index 100% rename from res/drawable-xxhdpi/pc_logo.png rename to malaria-app-android/src/main/res/drawable-xxhdpi/pc_logo.png diff --git a/malaria-app-android/src/main/res/drawable-xxxhdpi/btn_add_medicine.png b/malaria-app-android/src/main/res/drawable-xxxhdpi/btn_add_medicine.png new file mode 100644 index 00000000..1090af56 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxxhdpi/btn_add_medicine.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxxhdpi/btn_medicine_reminder.png b/malaria-app-android/src/main/res/drawable-xxxhdpi/btn_medicine_reminder.png new file mode 100644 index 00000000..cd8e9a5f Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxxhdpi/btn_medicine_reminder.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxxhdpi/ic_cancel_black_18dp.png b/malaria-app-android/src/main/res/drawable-xxxhdpi/ic_cancel_black_18dp.png new file mode 100644 index 00000000..892d07c9 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxxhdpi/ic_cancel_black_18dp.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxxhdpi/ic_done_black_18dp.png b/malaria-app-android/src/main/res/drawable-xxxhdpi/ic_done_black_18dp.png new file mode 100644 index 00000000..f9e4e125 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxxhdpi/ic_done_black_18dp.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxxhdpi/ic_snooze_black_18dp.png b/malaria-app-android/src/main/res/drawable-xxxhdpi/ic_snooze_black_18dp.png new file mode 100644 index 00000000..9bc32d34 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxxhdpi/ic_snooze_black_18dp.png differ diff --git a/malaria-app-android/src/main/res/drawable-xxxhdpi/warning.png b/malaria-app-android/src/main/res/drawable-xxxhdpi/warning.png new file mode 100644 index 00000000..404ae22e Binary files /dev/null and b/malaria-app-android/src/main/res/drawable-xxxhdpi/warning.png differ diff --git a/res/drawable/accept_medi_checked_.png b/malaria-app-android/src/main/res/drawable/accept_medi_checked_.png similarity index 100% rename from res/drawable/accept_medi_checked_.png rename to malaria-app-android/src/main/res/drawable/accept_medi_checked_.png diff --git a/res/drawable/accept_medi_checked_tiny.png b/malaria-app-android/src/main/res/drawable/accept_medi_checked_tiny.png similarity index 100% rename from res/drawable/accept_medi_checked_tiny.png rename to malaria-app-android/src/main/res/drawable/accept_medi_checked_tiny.png diff --git a/res/drawable/accept_medi_grayscale.png b/malaria-app-android/src/main/res/drawable/accept_medi_grayscale.png similarity index 100% rename from res/drawable/accept_medi_grayscale.png rename to malaria-app-android/src/main/res/drawable/accept_medi_grayscale.png diff --git a/res/drawable/accept_medi_normal.png b/malaria-app-android/src/main/res/drawable/accept_medicine_normal.png similarity index 100% rename from res/drawable/accept_medi_normal.png rename to malaria-app-android/src/main/res/drawable/accept_medicine_normal.png diff --git a/malaria-app-android/src/main/res/drawable/achievement_button.xml b/malaria-app-android/src/main/res/drawable/achievement_button.xml new file mode 100644 index 00000000..44822010 --- /dev/null +++ b/malaria-app-android/src/main/res/drawable/achievement_button.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/drawable/appicon_themed.png b/malaria-app-android/src/main/res/drawable/app_icon.png similarity index 100% rename from res/drawable/appicon_themed.png rename to malaria-app-android/src/main/res/drawable/app_icon.png diff --git a/res/drawable/arrow_down.png b/malaria-app-android/src/main/res/drawable/arrow_down.png similarity index 100% rename from res/drawable/arrow_down.png rename to malaria-app-android/src/main/res/drawable/arrow_down.png diff --git a/res/drawable/background.png b/malaria-app-android/src/main/res/drawable/background.png similarity index 100% rename from res/drawable/background.png rename to malaria-app-android/src/main/res/drawable/background.png diff --git a/res/drawable/info_hub_button.xml b/malaria-app-android/src/main/res/drawable/button_background.xml similarity index 81% rename from res/drawable/info_hub_button.xml rename to malaria-app-android/src/main/res/drawable/button_background.xml index 8e5ddd43..cd9bb378 100644 --- a/res/drawable/info_hub_button.xml +++ b/malaria-app-android/src/main/res/drawable/button_background.xml @@ -5,13 +5,13 @@ + android:color="@color/colorPrimary" > + android:width="1dp" + android:color="@color/colorPrimaryDark" > diff --git a/res/drawable/cal_left_arrow_brown.png b/malaria-app-android/src/main/res/drawable/cal_left_arrow_brown.png similarity index 100% rename from res/drawable/cal_left_arrow_brown.png rename to malaria-app-android/src/main/res/drawable/cal_left_arrow_brown.png diff --git a/res/drawable/cal_left_arrow_off.png b/malaria-app-android/src/main/res/drawable/cal_left_arrow_off.png similarity index 100% rename from res/drawable/cal_left_arrow_off.png rename to malaria-app-android/src/main/res/drawable/cal_left_arrow_off.png diff --git a/res/drawable/cal_right_arrow_brown.png b/malaria-app-android/src/main/res/drawable/cal_right_arrow_brown.png similarity index 100% rename from res/drawable/cal_right_arrow_brown.png rename to malaria-app-android/src/main/res/drawable/cal_right_arrow_brown.png diff --git a/res/drawable/cal_right_arrow_off.png b/malaria-app-android/src/main/res/drawable/cal_right_arrow_off.png similarity index 100% rename from res/drawable/cal_right_arrow_off.png rename to malaria-app-android/src/main/res/drawable/cal_right_arrow_off.png diff --git a/res/drawable/calendar_bg_orange.png b/malaria-app-android/src/main/res/drawable/calendar_bg_orange.png similarity index 100% rename from res/drawable/calendar_bg_orange.png rename to malaria-app-android/src/main/res/drawable/calendar_bg_orange.png diff --git a/res/drawable/calendar_button_selector.xml b/malaria-app-android/src/main/res/drawable/calendar_button_selector.xml similarity index 100% rename from res/drawable/calendar_button_selector.xml rename to malaria-app-android/src/main/res/drawable/calendar_button_selector.xml diff --git a/res/drawable/calendar_left_arrow_selector.xml b/malaria-app-android/src/main/res/drawable/calendar_left_arrow_selector.xml similarity index 100% rename from res/drawable/calendar_left_arrow_selector.xml rename to malaria-app-android/src/main/res/drawable/calendar_left_arrow_selector.xml diff --git a/res/drawable/calendar_right_arrow_selector.xml b/malaria-app-android/src/main/res/drawable/calendar_right_arrow_selector.xml similarity index 100% rename from res/drawable/calendar_right_arrow_selector.xml rename to malaria-app-android/src/main/res/drawable/calendar_right_arrow_selector.xml diff --git a/res/drawable/calendar_tile_small.png b/malaria-app-android/src/main/res/drawable/calendar_tile_small.png similarity index 100% rename from res/drawable/calendar_tile_small.png rename to malaria-app-android/src/main/res/drawable/calendar_tile_small.png diff --git a/malaria-app-android/src/main/res/drawable/calender_header_vertorizedy.png b/malaria-app-android/src/main/res/drawable/calender_header_vertorizedy.png new file mode 100644 index 00000000..5285b316 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/calender_header_vertorizedy.png differ diff --git a/res/drawable/cash.png b/malaria-app-android/src/main/res/drawable/cash.png similarity index 100% rename from res/drawable/cash.png rename to malaria-app-android/src/main/res/drawable/cash.png diff --git a/res/drawable/checked.png b/malaria-app-android/src/main/res/drawable/checked.png similarity index 100% rename from res/drawable/checked.png rename to malaria-app-android/src/main/res/drawable/checked.png diff --git a/malaria-app-android/src/main/res/drawable/chest.png b/malaria-app-android/src/main/res/drawable/chest.png new file mode 100644 index 00000000..cb711137 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/chest.png differ diff --git a/malaria-app-android/src/main/res/drawable/dark_button_background.xml b/malaria-app-android/src/main/res/drawable/dark_button_background.xml new file mode 100644 index 00000000..98023e9a --- /dev/null +++ b/malaria-app-android/src/main/res/drawable/dark_button_background.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/drawable/delete.png b/malaria-app-android/src/main/res/drawable/delete.png similarity index 100% rename from res/drawable/delete.png rename to malaria-app-android/src/main/res/drawable/delete.png diff --git a/res/drawable/dialog_background.xml b/malaria-app-android/src/main/res/drawable/dialog_background.xml similarity index 88% rename from res/drawable/dialog_background.xml rename to malaria-app-android/src/main/res/drawable/dialog_background.xml index 06cd0f0c..a6abe198 100644 --- a/res/drawable/dialog_background.xml +++ b/malaria-app-android/src/main/res/drawable/dialog_background.xml @@ -12,8 +12,8 @@ + android:width="2dp" + android:color="@color/colorPrimaryDark" > diff --git a/malaria-app-android/src/main/res/drawable/divider.xml b/malaria-app-android/src/main/res/drawable/divider.xml new file mode 100644 index 00000000..aff4096a --- /dev/null +++ b/malaria-app-android/src/main/res/drawable/divider.xml @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/res/drawable/doses_missing_image_normal.png b/malaria-app-android/src/main/res/drawable/doses_missing_image_normal.png similarity index 100% rename from res/drawable/doses_missing_image_normal.png rename to malaria-app-android/src/main/res/drawable/doses_missing_image_normal.png diff --git a/res/drawable/doxy.png b/malaria-app-android/src/main/res/drawable/doxy.png similarity index 100% rename from res/drawable/doxy.png rename to malaria-app-android/src/main/res/drawable/doxy.png diff --git a/res/drawable/drug_normal.png b/malaria-app-android/src/main/res/drawable/drug_normal.png similarity index 100% rename from res/drawable/drug_normal.png rename to malaria-app-android/src/main/res/drawable/drug_normal.png diff --git a/res/drawable/edit_pure_white.png b/malaria-app-android/src/main/res/drawable/edit_pure_white.png similarity index 100% rename from res/drawable/edit_pure_white.png rename to malaria-app-android/src/main/res/drawable/edit_pure_white.png diff --git a/res/drawable/enter.png b/malaria-app-android/src/main/res/drawable/enter.png similarity index 100% rename from res/drawable/enter.png rename to malaria-app-android/src/main/res/drawable/enter.png diff --git a/res/drawable/graph_bg.xml b/malaria-app-android/src/main/res/drawable/graph_bg.xml similarity index 100% rename from res/drawable/graph_bg.xml rename to malaria-app-android/src/main/res/drawable/graph_bg.xml diff --git a/res/drawable/home_icon_normal.png b/malaria-app-android/src/main/res/drawable/home_icon_normal.png similarity index 100% rename from res/drawable/home_icon_normal.png rename to malaria-app-android/src/main/res/drawable/home_icon_normal.png diff --git a/malaria-app-android/src/main/res/drawable/ic_action_volume_on.png b/malaria-app-android/src/main/res/drawable/ic_action_volume_on.png new file mode 100644 index 00000000..1beedb6e Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/ic_action_volume_on.png differ diff --git a/malaria-app-android/src/main/res/drawable/ic_edit_action.png b/malaria-app-android/src/main/res/drawable/ic_edit_action.png new file mode 100644 index 00000000..d08f93b3 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/ic_edit_action.png differ diff --git a/malaria-app-android/src/main/res/drawable/info_hub_button_grayed.xml b/malaria-app-android/src/main/res/drawable/info_hub_button_grayed.xml new file mode 100644 index 00000000..a669b9ad --- /dev/null +++ b/malaria-app-android/src/main/res/drawable/info_hub_button_grayed.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/drawable/info_hub_normal.png b/malaria-app-android/src/main/res/drawable/info_hub_normal.png similarity index 100% rename from res/drawable/info_hub_normal.png rename to malaria-app-android/src/main/res/drawable/info_hub_normal.png diff --git a/res/drawable/location_trip.png b/malaria-app-android/src/main/res/drawable/location_trip.png similarity index 100% rename from res/drawable/location_trip.png rename to malaria-app-android/src/main/res/drawable/location_trip.png diff --git a/res/drawable/mal.png b/malaria-app-android/src/main/res/drawable/mal.png similarity index 100% rename from res/drawable/mal.png rename to malaria-app-android/src/main/res/drawable/mal.png diff --git a/res/drawable/medication_last_normal.png b/malaria-app-android/src/main/res/drawable/medication_last_normal.png similarity index 100% rename from res/drawable/medication_last_normal.png rename to malaria-app-android/src/main/res/drawable/medication_last_normal.png diff --git a/res/drawable/medicine_adhere_normal.png b/malaria-app-android/src/main/res/drawable/medicine_adhere_normal.png similarity index 100% rename from res/drawable/medicine_adhere_normal.png rename to malaria-app-android/src/main/res/drawable/medicine_adhere_normal.png diff --git a/res/drawable/mef.png b/malaria-app-android/src/main/res/drawable/mef.png similarity index 100% rename from res/drawable/mef.png rename to malaria-app-android/src/main/res/drawable/mef.png diff --git a/res/drawable/packing_bag.png b/malaria-app-android/src/main/res/drawable/packing_bag.png similarity index 100% rename from res/drawable/packing_bag.png rename to malaria-app-android/src/main/res/drawable/packing_bag.png diff --git a/res/drawable/peace_corps_logo_normal.png b/malaria-app-android/src/main/res/drawable/peace_corps_logo_normal.png similarity index 100% rename from res/drawable/peace_corps_logo_normal.png rename to malaria-app-android/src/main/res/drawable/peace_corps_logo_normal.png diff --git a/malaria-app-android/src/main/res/drawable/peacecorps_small.png b/malaria-app-android/src/main/res/drawable/peacecorps_small.png new file mode 100644 index 00000000..46004f04 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/peacecorps_small.png differ diff --git a/res/drawable/plus.png b/malaria-app-android/src/main/res/drawable/plus.png similarity index 100% rename from res/drawable/plus.png rename to malaria-app-android/src/main/res/drawable/plus.png diff --git a/res/drawable/progress_bg.xml b/malaria-app-android/src/main/res/drawable/progress_bg.xml similarity index 100% rename from res/drawable/progress_bg.xml rename to malaria-app-android/src/main/res/drawable/progress_bg.xml diff --git a/res/drawable/progress_bg_green.xml b/malaria-app-android/src/main/res/drawable/progress_bg_green.xml similarity index 100% rename from res/drawable/progress_bg_green.xml rename to malaria-app-android/src/main/res/drawable/progress_bg_green.xml diff --git a/res/drawable/reject_medi_checked.png b/malaria-app-android/src/main/res/drawable/reject_medi_checked.png similarity index 100% rename from res/drawable/reject_medi_checked.png rename to malaria-app-android/src/main/res/drawable/reject_medi_checked.png diff --git a/res/drawable/reject_medi_checked_tiny.png b/malaria-app-android/src/main/res/drawable/reject_medi_checked_tiny.png similarity index 100% rename from res/drawable/reject_medi_checked_tiny.png rename to malaria-app-android/src/main/res/drawable/reject_medi_checked_tiny.png diff --git a/res/drawable/reject_medi_grayscale.png b/malaria-app-android/src/main/res/drawable/reject_medi_grayscale.png similarity index 100% rename from res/drawable/reject_medi_grayscale.png rename to malaria-app-android/src/main/res/drawable/reject_medi_grayscale.png diff --git a/res/drawable/reject_medi_normal.png b/malaria-app-android/src/main/res/drawable/reject_medicine_normal.png similarity index 100% rename from res/drawable/reject_medi_normal.png rename to malaria-app-android/src/main/res/drawable/reject_medicine_normal.png diff --git a/res/drawable/roundedbutton.xml b/malaria-app-android/src/main/res/drawable/roundedbutton.xml similarity index 100% rename from res/drawable/roundedbutton.xml rename to malaria-app-android/src/main/res/drawable/roundedbutton.xml diff --git a/malaria-app-android/src/main/res/drawable/roundedbutton_grey.xml b/malaria-app-android/src/main/res/drawable/roundedbutton_grey.xml new file mode 100644 index 00000000..501c7f31 --- /dev/null +++ b/malaria-app-android/src/main/res/drawable/roundedbutton_grey.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/drawable/saf_progress_bar.xml b/malaria-app-android/src/main/res/drawable/saf_progress_bar.xml similarity index 100% rename from res/drawable/saf_progress_bar.xml rename to malaria-app-android/src/main/res/drawable/saf_progress_bar.xml diff --git a/res/drawable/saf_progress_bar_green.xml b/malaria-app-android/src/main/res/drawable/saf_progress_bar_green.xml similarity index 100% rename from res/drawable/saf_progress_bar_green.xml rename to malaria-app-android/src/main/res/drawable/saf_progress_bar_green.xml diff --git a/res/drawable/settings_normal.png b/malaria-app-android/src/main/res/drawable/settings_normal.png similarity index 100% rename from res/drawable/settings_normal.png rename to malaria-app-android/src/main/res/drawable/settings_normal.png diff --git a/malaria-app-android/src/main/res/drawable/timeline_marker.xml b/malaria-app-android/src/main/res/drawable/timeline_marker.xml new file mode 100644 index 00000000..4d558049 --- /dev/null +++ b/malaria-app-android/src/main/res/drawable/timeline_marker.xml @@ -0,0 +1,8 @@ + + + + + + \ No newline at end of file diff --git a/malaria-app-android/src/main/res/drawable/trash.png b/malaria-app-android/src/main/res/drawable/trash.png new file mode 100644 index 00000000..0ea74ae4 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/trash.png differ diff --git a/malaria-app-android/src/main/res/drawable/trip_cash_editext.xml b/malaria-app-android/src/main/res/drawable/trip_cash_editext.xml new file mode 100644 index 00000000..dcd472ba --- /dev/null +++ b/malaria-app-android/src/main/res/drawable/trip_cash_editext.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/res/drawable/trip_check.xml b/malaria-app-android/src/main/res/drawable/trip_check.xml similarity index 100% rename from res/drawable/trip_check.xml rename to malaria-app-android/src/main/res/drawable/trip_check.xml diff --git a/res/drawable/unchecked.png b/malaria-app-android/src/main/res/drawable/unchecked.png similarity index 100% rename from res/drawable/unchecked.png rename to malaria-app-android/src/main/res/drawable/unchecked.png diff --git a/malaria-app-android/src/main/res/drawable/y_b1.png b/malaria-app-android/src/main/res/drawable/y_b1.png new file mode 100644 index 00000000..293d2b4f Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/y_b1.png differ diff --git a/malaria-app-android/src/main/res/drawable/y_b3.png b/malaria-app-android/src/main/res/drawable/y_b3.png new file mode 100644 index 00000000..e8944db3 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/y_b3.png differ diff --git a/malaria-app-android/src/main/res/drawable/y_b5.png b/malaria-app-android/src/main/res/drawable/y_b5.png new file mode 100644 index 00000000..09404b0d Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/y_b5.png differ diff --git a/malaria-app-android/src/main/res/drawable/y_b6.png b/malaria-app-android/src/main/res/drawable/y_b6.png new file mode 100644 index 00000000..d3bbb01c Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/y_b6.png differ diff --git a/malaria-app-android/src/main/res/drawable/y_hat.png b/malaria-app-android/src/main/res/drawable/y_hat.png new file mode 100644 index 00000000..ce99b2f5 Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/y_hat.png differ diff --git a/malaria-app-android/src/main/res/drawable/y_newbie.png b/malaria-app-android/src/main/res/drawable/y_newbie.png new file mode 100644 index 00000000..60cc0a3c Binary files /dev/null and b/malaria-app-android/src/main/res/drawable/y_newbie.png differ diff --git a/malaria-app-android/src/main/res/layout-land/fragment_second_analytic_screen.xml b/malaria-app-android/src/main/res/layout-land/fragment_second_analytic_screen.xml new file mode 100644 index 00000000..4992010d --- /dev/null +++ b/malaria-app-android/src/main/res/layout-land/fragment_second_analytic_screen.xml @@ -0,0 +1,43 @@ + + + + + android:textColor="@color/black"/> - + android:layout_width="@dimen/size_10dp" + android:layout_height="@dimen/size_10dp" + android:layout_gravity="right"/> \ No newline at end of file diff --git a/res/layout/screen_gridcell.xml b/malaria-app-android/src/main/res/layout/screen_gridcell.xml similarity index 72% rename from res/layout/screen_gridcell.xml rename to malaria-app-android/src/main/res/layout/screen_gridcell.xml index f28a61a8..7a7b223f 100644 --- a/res/layout/screen_gridcell.xml +++ b/malaria-app-android/src/main/res/layout/screen_gridcell.xml @@ -3,7 +3,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/calendar_button_selector" - android:orientation="vertical" > + android:orientation="vertical"> + android:textColor="#FFFFFF"/> - + android:layout_width="@dimen/size_10dp" + android:layout_height="@dimen/size_10dp" + android:layout_gravity="right"/> diff --git a/res/layout/screen_gridcell_green.xml b/malaria-app-android/src/main/res/layout/screen_gridcell_green.xml similarity index 75% rename from res/layout/screen_gridcell_green.xml rename to malaria-app-android/src/main/res/layout/screen_gridcell_green.xml index 91cd160a..29d394ca 100644 --- a/res/layout/screen_gridcell_green.xml +++ b/malaria-app-android/src/main/res/layout/screen_gridcell_green.xml @@ -3,7 +3,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/calendar_button_selector" - android:orientation="vertical" > + android:orientation="vertical"> + android:textColor="@color/black"/> - + android:layout_width="@dimen/size_10dp" + android:layout_height="@dimen/margin_20dp" + android:layout_gravity="right"/> \ No newline at end of file diff --git a/res/layout/side_effects_npcv_fragment.xml b/malaria-app-android/src/main/res/layout/side_effects_npcv_fragment.xml similarity index 52% rename from res/layout/side_effects_npcv_fragment.xml rename to malaria-app-android/src/main/res/layout/side_effects_npcv_fragment.xml index db8d798b..3d9459f4 100644 --- a/res/layout/side_effects_npcv_fragment.xml +++ b/malaria-app-android/src/main/res/layout/side_effects_npcv_fragment.xml @@ -1,48 +1,44 @@ - - - - - + android:layout_height="match_parent" + android:layout_gravity="center_horizontal" + android:background="@drawable/background" + android:orientation="vertical" + android:padding="@dimen/padding_2dp"> - - /> - + android:background="@color/black" /> - + - + android:textSize="@dimen/text_size_20sp" /> - \ No newline at end of file + diff --git a/res/layout/side_effects_pcv_fragment.xml b/malaria-app-android/src/main/res/layout/side_effects_pcv_fragment.xml similarity index 52% rename from res/layout/side_effects_pcv_fragment.xml rename to malaria-app-android/src/main/res/layout/side_effects_pcv_fragment.xml index 2f6512c4..db9e4f9e 100644 --- a/res/layout/side_effects_pcv_fragment.xml +++ b/malaria-app-android/src/main/res/layout/side_effects_pcv_fragment.xml @@ -1,48 +1,44 @@ - - - - - + android:layout_height="match_parent" + android:layout_gravity="center_horizontal" + android:background="@drawable/background" + android:orientation="vertical" + android:padding="@dimen/padding_10dp"> - - /> - + android:background="@color/black" /> - + - + android:textSize="@dimen/text_size_20sp" /> - \ No newline at end of file + diff --git a/malaria-app-android/src/main/res/layout/side_effects_percentage_fragment.xml b/malaria-app-android/src/main/res/layout/side_effects_percentage_fragment.xml new file mode 100644 index 00000000..3b5faed7 --- /dev/null +++ b/malaria-app-android/src/main/res/layout/side_effects_percentage_fragment.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/malaria-app-android/src/main/res/layout/statusappwidget.xml b/malaria-app-android/src/main/res/layout/statusappwidget.xml new file mode 100644 index 00000000..b5eda1bb --- /dev/null +++ b/malaria-app-android/src/main/res/layout/statusappwidget.xml @@ -0,0 +1,13 @@ + + + + + \ No newline at end of file diff --git a/malaria-app-android/src/main/res/layout/toolbar.xml b/malaria-app-android/src/main/res/layout/toolbar.xml new file mode 100644 index 00000000..8540220d --- /dev/null +++ b/malaria-app-android/src/main/res/layout/toolbar.xml @@ -0,0 +1,13 @@ + + \ No newline at end of file diff --git a/res/layout/trip_alarm_layout.xml b/malaria-app-android/src/main/res/layout/trip_alarm_layout.xml similarity index 51% rename from res/layout/trip_alarm_layout.xml rename to malaria-app-android/src/main/res/layout/trip_alarm_layout.xml index e5e14010..ba6ec1c3 100644 --- a/res/layout/trip_alarm_layout.xml +++ b/malaria-app-android/src/main/res/layout/trip_alarm_layout.xml @@ -1,85 +1,87 @@ + android:background="@drawable/dialog_background"> + android:orientation="vertical"> + android:gravity="center" + android:padding="@dimen/padding_10dp" + android:text="@string/heading_trip_checklist_reminder" + android:textColor="@color/textColorPrimary" + android:textSize="@dimen/text_size_25sp" /> + android:text="@string/label_sample_text" + android:textColor="@color/textColorPrimary" + android:textSize="@dimen/text_size_20sp" /> + android:layout_centerHorizontal="true" + android:layout_gravity="center_horizontal" + android:gravity="center_horizontal">