diff --git a/Y3Proj File Structure.txt b/Y3Proj File Structure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1640e64a55bdb8b45147926a054f635e7ccce56c --- /dev/null +++ b/Y3Proj File Structure.txt @@ -0,0 +1,114 @@ +Y3Proj +|-- LICENSE [General License agreement for anyone accessing the git repository] +|-- README.md [A readme for explaining the project for the git repository] +|-- XBFramework.iml [A project based dictionairy (including any gradle / project settings files)] +|-- app [The folder that contains all the code for the project] +| |-- app.iml [Another app based dictionairy (only for the code)] +| |-- build [An automatically generated build folder that holds temporary files during the build process] +| |-- build.gradle [An automatically generated build settings gradle file] +| |-- libs [An automatically generated library folder] +| |-- proguard-rules.pro [A project settings file] +| `-- src [The source code folder] +| |-- androidTest [An automatically generated test folder] +| |-- main [The main source code folder] +| | |-- AndroidManifest.xml [A file containing the manifest for all the pages and permissions in the applicaiton] +| | |-- ic_launcher-web.png [The raw .png for the app logo] +| | |-- java +| | | `-- com +| | | `-- yearthreeproject +| | | `-- xbframework [The actual java code (where all the dynamic features are written) anything with "Activity" is the pages code] +| | | |-- AboutActivity.java +| | | |-- BoxesActivity.java +| | | |-- ExperimentActivity.java +| | | |-- ExperimentSurveyCreatorActivity.java +| | | |-- LoginActivity.java +| | | |-- MainActivity.java +| | | |-- MyNotificationPublisher.java [A backend page used to push notifications even when the application is not running] +| | | |-- NewBoxActivity.java +| | | |-- ProgressActivity.java +| | | |-- ProjectMacros.java [A project defined library that holds functions used commonly throughout the project] +| | | |-- ShopActivity.java +| | | |-- SurveyResponseActivity.java +| | | `-- TestingActivity.java [A page only used in debugging phase, is not longer used in the final product] +| | `-- res [The resouce folder] +| | |-- drawable [Automatically generated XMLs for the launcher icon] +| | | |-- ic_action_right.xml +| | | `-- ic_launcher_background.xml +| | |-- drawable-anydpi [Automatically generated XMLs for the launcher icon for different formats] +| | |-- drawable-hdpi +| | |-- drawable-mdpi +| | |-- drawable-xhdpi +| | |-- drawable-xxhdpi +| | |-- layout [The layout folder for each different page, it is common practice to have an activity_ and content_ page file] +| | | |-- activity_about.xml +| | | |-- activity_boxes.xml +| | | |-- activity_experiment.xml +| | | |-- activity_experiment_survey_creator.xml +| | | |-- activity_login.xml +| | | |-- activity_main.xml +| | | |-- activity_new_box.xml +| | | |-- activity_progress.xml +| | | |-- activity_shop.xml +| | | |-- activity_survey_response.xml +| | | |-- activity_testing.xml [No longer used in final product] +| | | |-- content_about.xml +| | | |-- content_boxes.xml +| | | |-- content_experiment.xml +| | | |-- content_experiment_survey_creator.xml +| | | |-- content_login.xml +| | | |-- content_main.xml +| | | |-- content_new_box.xml +| | | |-- content_progress.xml +| | | |-- content_shop.xml +| | | |-- content_survey_response.xml +| | | `-- content_testing.xml [No longer used in final product] +| | |-- mipmap [Automatically generated .pngs for icon launcher] +| | | |-- ic_launcher.png +| | | |-- ic_launcher_foreground.png +| | | `-- ic_launcher_round.png +| | |-- mipmap +| | |-- raw [Raw files used for initialising different objects within the application] +| | | |-- box.json [The original local box data structure, no longer used] +| | | |-- box_outline.png [A two bit image of the logo for notifications] +| | | |-- local_user_data.json [The original local user data data structure, no longer used] +| | | |-- logo.png [The complete logo for the application] +| | | `-- shop.json [The shop data structure, used to generate the display in the shop page] +| | `-- values [Project wide files for static resource] +| | |-- arrays.xml [Contains a MEECS array, used for a spinner and data verification] +| | |-- colors.xml [The defined colour scheme for the project] +| | |-- strings.xml [A list of static strings to use, the standard way to code GUI in android] +| | `-- styles.xml [A description of the default look of GUI elements within the applicaiton] +| `-- test [An automatically generated folder] +|-- build.gradle [A project wide description of the libraries used and build settings] +|-- gradle [An automatically generated folder for project settings] +| `-- wrapper +| |-- gradle-wrapper.jar +| `-- gradle-wrapper.properties +|-- gradle.properties [More project settings] +|-- gradlew +|-- gradlew.bat +|-- local.properties +|-- settings.gradle +|-- planning [A folder containing all the supplementary planning documentation for this project] +| |-- Bill of Materials.xlsx +| |-- Daily progress.xlsx +| |-- Gantt.xlsx +| |-- Logbook.pdf [A scanned copy of the logbook entries used for this project] +| `-- Risk analysis.xlsx +|-- reports [A folder containing the two reports written for this project] +| |-- final [A folder contianing the final report] +| | |-- Project Report Body.docx +| | |-- Project Report Body.pdf +| | |-- Project Report.docx +| | `-- Project Report.pdf +| |-- project brief [A folder contianing the initial project brief] +| | `-- Project Brief.docx +| `-- progress [A folder containing the progress report] +| |-- Progress Report Body.docx +| |-- Progress Report.docx +| |-- Progress Report.pdf +| `-- ShorterReportBody.pdf +|-- Y3Proj File Structure.txt [This file] +`-- designs [A folder containing the design files relating to this project] + `-- saltshaker.png + \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 53647ef03e9dd6ec39aa99750ba81b8a5a1e3bca..fe0491354bf6b1989807efc4debedb76272b19b1 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -14,12 +14,15 @@ android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.Light.NoActionBar" + android:screenOrientation="portrait" tools:ignore="GoogleAppIndexingWarning"> <activity android:name=".MainActivity" + android:screenOrientation="portrait" tools:overrideLibrary="com.mongodb.stitch.android.services.mongodb.remote" android:label="@string/app_name" - android:theme="@style/AppTheme.NoActionBar"> + android:theme="@style/AppTheme.NoActionBar" + tools:ignore="LockedOrientationActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> @@ -28,56 +31,78 @@ <activity android:name=".AboutActivity" + android:screenOrientation="portrait" android:label="About" - android:theme="@style/AppTheme.NoActionBar"/> + android:theme="@style/AppTheme.NoActionBar" + tools:ignore="LockedOrientationActivity" /> <activity android:name=".TestingActivity" + android:screenOrientation="portrait" android:label="Testing" - android:theme="@style/AppTheme.NoActionBar"/> + android:theme="@style/AppTheme.NoActionBar" + tools:ignore="LockedOrientationActivity" /> <activity android:name=".LoginActivity" + android:screenOrientation="portrait" android:label="Login" - android:theme="@style/AppTheme.NoActionBar"/> + android:theme="@style/AppTheme.NoActionBar" + tools:ignore="LockedOrientationActivity" /> <activity android:name=".BoxesActivity" + android:screenOrientation="portrait" android:label="Boxes" - android:theme="@style/AppTheme.NoActionBar"/> + android:theme="@style/AppTheme.NoActionBar" + tools:ignore="LockedOrientationActivity" /> <activity android:name=".ExperimentActivity" + android:screenOrientation="portrait" android:label="Experiment" - android:theme="@style/AppTheme.NoActionBar"/> + android:theme="@style/AppTheme.NoActionBar" + tools:ignore="LockedOrientationActivity" /> <activity android:name=".ShopActivity" + android:screenOrientation="portrait" android:label="Shop" - android:theme="@style/AppTheme.NoActionBar"/> + android:theme="@style/AppTheme.NoActionBar" + tools:ignore="LockedOrientationActivity" /> <activity android:name=".ProgressActivity" + android:screenOrientation="portrait" android:label="Progress" - android:theme="@style/AppTheme.NoActionBar"/> + android:theme="@style/AppTheme.NoActionBar" + tools:ignore="LockedOrientationActivity" /> <activity - android:name=".NewBox" + android:name=".NewBoxActivity" + android:screenOrientation="portrait" android:label="NewBox" - android:theme="@style/AppTheme.NoActionBar"/> + android:theme="@style/AppTheme.NoActionBar" + tools:ignore="LockedOrientationActivity" /> <activity android:name=".ExperimentSurveyCreatorActivity" + android:screenOrientation="portrait" android:label="ExperimentSurveyCreator" - android:theme="@style/AppTheme.NoActionBar"/> + android:theme="@style/AppTheme.NoActionBar" + tools:ignore="LockedOrientationActivity" /> <activity android:name=".SurveyResponseActivity" + android:screenOrientation="portrait" android:label="Survey Response" - android:theme="@style/AppTheme.NoActionBar"/> + android:theme="@style/AppTheme.NoActionBar" + tools:ignore="LockedOrientationActivity" /> <activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity" - android:theme="@style/Base.Theme.AppCompat"/> + android:screenOrientation="portrait" + android:theme="@style/Base.Theme.AppCompat" + tools:ignore="LockedOrientationActivity" /> <receiver android:name=".MyNotificationPublisher" /> diff --git a/app/src/main/java/com/yearthreeproject/xbframework/BoxesActivity.java b/app/src/main/java/com/yearthreeproject/xbframework/BoxesActivity.java index c0c07515eb12a6c64b68d60c03ab7fafdd70b519..d52cb00726582e26b2b2b04f3351728aa8fba2b0 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/BoxesActivity.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/BoxesActivity.java @@ -49,7 +49,7 @@ public class BoxesActivity extends AppCompatActivity { getSupportActionBar().setDisplayShowHomeEnabled(true); FloatingActionButton createBox = findViewById(R.id.CreateNewBoxFab); - createBox.setOnClickListener(v -> startActivity(new Intent(BoxesActivity.this, NewBox.class))); + createBox.setOnClickListener(v -> startActivity(new Intent(BoxesActivity.this, NewBoxActivity.class))); loadAndDisplayJSON(); } @@ -91,10 +91,13 @@ public class BoxesActivity extends AppCompatActivity { inFiveLayoutArray[i].addView(hr); + boolean currentMatch = false; + for (int j = 0; j < boxes.length(); j++) { final JSONObject box = boxes.getJSONObject(j); if (box.getString("Group").matches(inFive[i])) { + currentMatch = true; inFiveAvailableBoxes[j] = new LinearLayout(this); inFiveAvailableBoxes[j].setOrientation(LinearLayout.HORIZONTAL); inFiveAvailableBoxes[j].setPadding(0, 8, 0, 8); @@ -106,15 +109,8 @@ public class BoxesActivity extends AppCompatActivity { TextView titleOfBox = new TextView(this); titleOfBox.setText(box.getString("Name")); titleOfBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - titleOfBox.setTextColor(getColor(R.color.colorPrimary)); - } TextView descriptionOfBox = new TextView(this); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - descriptionOfBox.setTextColor(getColor(R.color.colorPrimary)); - } - descriptionOfBox.setText(box.getString("Blurb")); boxLayout.addView(titleOfBox); @@ -143,6 +139,29 @@ public class BoxesActivity extends AppCompatActivity { inFiveLayoutArray[i].addView(inFiveAvailableBoxes[j]); } } + + if (!currentMatch) { + LinearLayout InFiveTempLayout = new LinearLayout(this); + InFiveTempLayout.setOrientation(LinearLayout.HORIZONTAL); + InFiveTempLayout.setPadding(0, 8, 0, 8); + + LinearLayout boxLayout = new LinearLayout(this); + boxLayout.setOrientation(LinearLayout.VERTICAL); + boxLayout.setPadding(16, 0, 0, 0); + + TextView titleOfBox = new TextView(this); + titleOfBox.setText("No box available"); + titleOfBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28); + + TextView descriptionOfBox = new TextView(this); + descriptionOfBox.setText("There are no boxes available for " + inFiveTitle.getText()); + + boxLayout.addView(titleOfBox); + boxLayout.addView(descriptionOfBox); + + InFiveTempLayout.addView(boxLayout); + inFiveLayoutArray[i].addView(InFiveTempLayout); + } inFiveLayout.addView(inFiveLayoutArray[i]); } } catch (JSONException e) { diff --git a/app/src/main/java/com/yearthreeproject/xbframework/LoginActivity.java b/app/src/main/java/com/yearthreeproject/xbframework/LoginActivity.java index 25107609195ebf68a7af2147526e5962e1ea63a6..c7b3030135540ffd56c28d9c5bdaef13a54d4033 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/LoginActivity.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/LoginActivity.java @@ -25,6 +25,8 @@ import com.mongodb.stitch.core.auth.providers.userpassword.UserPasswordCredentia import com.mongodb.stitch.core.services.mongodb.remote.RemoteUpdateOptions; import org.bson.Document; +import org.json.JSONArray; +import org.json.JSONException; import org.json.JSONObject; import java.security.MessageDigest; @@ -133,13 +135,36 @@ public class LoginActivity extends AppCompatActivity { .append("archivedExperimentData", new ArrayList<DBObject>()), new RemoteUpdateOptions().upsert(true)).addOnCompleteListener(task2->{ if(task2.isSuccessful()){ - d("dbg_uploaded", "true"); + d("dbg_uploaded", task2.getResult().toString()); + try { + JSONObject newLocalUser = new JSONObject().put("owner_id", client.getAuth().getUser().getId()) + .put("dateUntil", null) + .put("locked", false) + .put("lockedExperiment", new JSONObject().toString()) + .put("journal", new JSONArray()) + .put("archivedExperimentData", new JSONArray()); + + ProjectMacros.saveFile(LoginActivity.this, "localUserData.json", newLocalUser.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + finish(); } else { task2.getException().printStackTrace(); + finish(); } - finish(); }); } else { + d("dbg_uploaded", task.getResult().get(0).toJson()); + try { + JSONObject newLocalUser = new JSONObject(task.getResult().get(0).toJson()); + + ProjectMacros.saveFile(LoginActivity.this, "localUserData.json", newLocalUser.toString()); + } catch (JSONException e) { + e.printStackTrace(); + } + + finish(); } } else{ diff --git a/app/src/main/java/com/yearthreeproject/xbframework/MainActivity.java b/app/src/main/java/com/yearthreeproject/xbframework/MainActivity.java index 16cd17c5bc0ca7ced896e4c43cafabc254a7b412..63740464ba8005e872ed70c24035c6c4e87a7559 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/MainActivity.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/MainActivity.java @@ -10,8 +10,6 @@ import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; -import android.view.Menu; -import android.view.MenuItem; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; @@ -27,6 +25,7 @@ import com.mongodb.stitch.android.core.Stitch; import com.mongodb.stitch.android.core.StitchAppClient; import com.mongodb.stitch.android.services.mongodb.remote.RemoteMongoClient; import com.mongodb.stitch.android.services.mongodb.remote.RemoteMongoCollection; +import com.mongodb.stitch.core.services.mongodb.remote.RemoteUpdateOptions; import org.bson.Document; import org.bson.internal.Base64; @@ -49,53 +48,6 @@ public class MainActivity extends AppCompatActivity { Intent recreateOnExitIntent = new Intent(); Toast submitToast; - @Override - public boolean onCreateOptionsMenu(Menu menu) { - MenuItem createBox = menu.add("Reset JSON!"); - MenuItem cancelNotif = menu.add("Cancel Notifications!"); - MenuItem logOut = menu.add("Log out!"); - - createBox.setOnMenuItemClickListener(item -> { - resetBoxJSON(); - return false; - }); - - cancelNotif.setOnMenuItemClickListener(item -> { - try { - JSONObject localDataJson = new JSONObject(ProjectMacros.readFile(MainActivity.this, "localUserData.json")); - for (int i = 0; i < localDataJson.getJSONObject("lockedExperiment").getJSONArray("Notification").length(); i++) { - JSONObject notificationObject = localDataJson.getJSONObject("lockedExperiment").getJSONArray("Notification").getJSONObject(i); - ProjectMacros.cancelNotification(notificationObject.getString("Title"), notificationObject.getString("Message"), MainActivity.this); - } - } catch (JSONException e) { - e.printStackTrace(); - } - return false; - }); - - logOut.setOnMenuItemClickListener(item -> { - SharedPreferences savedSettings = this.getSharedPreferences("com.yearthreeproject.xbframework.PREFERENCE_FILE_KEY", Context.MODE_PRIVATE); - SharedPreferences.Editor savedSettingsEditor = savedSettings.edit(); - - final StitchAppClient client; - if(Stitch.hasAppClient(getString(R.string.mongo_stitch_id))){ - client = Stitch.getDefaultAppClient(); - } else { - client = Stitch.initializeDefaultAppClient(getString(R.string.mongo_stitch_id)); - } - - client.getAuth().logout().addOnCompleteListener(task ->{ - if(task.isSuccessful()){ - savedSettingsEditor.putBoolean("loggedIn", false); - savedSettingsEditor.apply(); - recreate(); - } - }); - return false; - }); - return true; - } - @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { @@ -119,8 +71,28 @@ public class MainActivity extends AppCompatActivity { savedSettingsEditor.apply(); } startActivityToRecreateOnExit(LoginActivity.class); + } else { + final StitchAppClient client; + if(Stitch.hasAppClient(getString(R.string.mongo_stitch_id))){ + client = Stitch.getDefaultAppClient(); + } else { + client = Stitch.initializeDefaultAppClient(getString(R.string.mongo_stitch_id)); + } + + d("dbg_loggedIn", String.valueOf(client.getAuth().isLoggedIn())); + if(!client.getAuth().isLoggedIn()){ + d("dbg_loggin_out", "true"); + SharedPreferences.Editor savedSettingsEditor = savedSettings.edit(); + savedSettingsEditor.putBoolean("loggedIn", false); + savedSettingsEditor.apply(); + recreate(); + } else { + d("dbg_loggedIn", String.valueOf(client.getAuth().getUser().getId())); + } } + + submitToast = new Toast(this); Toolbar toolbar = findViewById(R.id.toolbar); @@ -129,6 +101,8 @@ public class MainActivity extends AppCompatActivity { Objects.requireNonNull(getSupportActionBar()).setLogo(R.mipmap.ic_launcher); Objects.requireNonNull(getSupportActionBar()).setDisplayUseLogoEnabled(true); + checkReleaseFromExperiment(); + checkNotifications(); LinearLayout homeActLay = findViewById(R.id.HomeActivityLayout); @@ -147,10 +121,9 @@ public class MainActivity extends AppCompatActivity { client = Stitch.initializeDefaultAppClient(getString(R.string.mongo_stitch_id)); } - d("dbg_test_user_login", client.getAuth().getUser().getId()); - client.getAuth().logout().addOnCompleteListener(task ->{ if(task.isSuccessful()){ + ProjectMacros.saveFile(this, "localUserData.json", ""); savedSettingsEditor.putBoolean("loggedIn", false); savedSettingsEditor.apply(); recreate(); @@ -199,7 +172,7 @@ public class MainActivity extends AppCompatActivity { JSONObject localUserJSON = new JSONObject(ProjectMacros.readFile(this, "localUserData.json")); d("dbg_testing", Objects.requireNonNull(localUserJSON).toString()); - if (localUserJSON.opt("locked") != JSONObject.NULL && localUserJSON.optBoolean("locked")) { + if (localUserJSON.get("locked") != JSONObject.NULL && localUserJSON.optBoolean("locked")) { homeActLay.removeView(experimentsButton); } else { homeActLay.removeView(surveyButton); @@ -209,6 +182,56 @@ public class MainActivity extends AppCompatActivity { } } + @RequiresApi(api = Build.VERSION_CODES.N) + private void checkReleaseFromExperiment() { + try { + JSONObject localDataJson = new JSONObject(ProjectMacros.readFile(this, "localUserData.json")); + if(ProjectMacros.checkDateLimit(localDataJson.getString("dateUntil"))){ + for(int i = 0; i < localDataJson.getJSONObject("lockedExperiment").getJSONArray("Notification").length(); i++){ + JSONObject notificationObject = localDataJson.getJSONObject("lockedExperiment").getJSONArray("Notification").getJSONObject(i); + ProjectMacros.cancelNotification(notificationObject.getString("Title"), notificationObject.getString("Message"), MainActivity.this); + } + + JSONArray archivedData = localDataJson.getJSONArray("archivedExperimentData"); + + for(int i = 0; i < localDataJson.getJSONObject("lockedExperiment").getJSONArray("UserData").length(); i++){ + archivedData.put(localDataJson.getJSONObject("lockedExperiment").getJSONArray("UserData").get(i)); + } + + localDataJson.put("archivedExperimentData", archivedData); + localDataJson.put("locked", false); + localDataJson.put("lockedExperiment", new JSONObject()); + d("dbg_localDataJson", localDataJson.toString()); + ProjectMacros.saveFile(this, "localUserData.json", localDataJson.toString()); + + + final StitchAppClient client; + if(Stitch.hasAppClient(getString(R.string.mongo_stitch_id))){ + client = Stitch.getDefaultAppClient(); + } else { + client = Stitch.initializeDefaultAppClient(getString(R.string.mongo_stitch_id)); + } + final RemoteMongoClient mongoClient = client.getServiceClient(RemoteMongoClient.factory, "XBF"); + final RemoteMongoCollection<Document> coll = mongoClient.getDatabase("IPServer").getCollection("UserData"); + + client.getAuth().addAuthListener(auth -> { + if(auth.isLoggedIn()){ + coll.updateOne( + new Document("owner_id", auth.getUser().getId()), + Document.parse(localDataJson.toString()) + .append("owner_id", auth.getUser().getId()), + new RemoteUpdateOptions().upsert(true)).addOnCompleteListener(task1->{ + d("dbg_uploaded", "success"); + }); + } + }); + } + + } catch (JSONException e) { + e.printStackTrace(); + } + } + private void startActivityToRecreateOnExit(Class activity){ recreateOnExitIntent = new Intent(MainActivity.this, activity); startActivityForResult(recreateOnExitIntent, 0); @@ -237,10 +260,12 @@ public class MainActivity extends AppCompatActivity { ProjectMacros.createNotification(notificationObject.getString("Title"), notificationObject.getString("Message"), MainActivity.this, start, repeat); } } else { - for(int i = 0; i < localDataJson.getJSONObject("lockedExperiment").getJSONArray("Notification").length(); i++){ - JSONObject notificationObject = localDataJson.getJSONObject("lockedExperiment").getJSONArray("Notification").getJSONObject(i); + if(localDataJson.getJSONObject("lockedExperiment") != JSONObject.NULL && localDataJson.getJSONObject("lockedExperiment").getJSONArray("Notification") != null) { + for (int i = 0; i < localDataJson.getJSONObject("lockedExperiment").optJSONArray("Notification").length(); i++) { + JSONObject notificationObject = localDataJson.getJSONObject("lockedExperiment").getJSONArray("Notification").getJSONObject(i); - ProjectMacros.cancelNotification(notificationObject.getString("Title"), notificationObject.getString("Message"), MainActivity.this); + ProjectMacros.cancelNotification(notificationObject.getString("Title"), notificationObject.getString("Message"), MainActivity.this); + } } } } catch (JSONException e) { @@ -248,17 +273,6 @@ public class MainActivity extends AppCompatActivity { } } - @RequiresApi(api = Build.VERSION_CODES.KITKAT) - private void resetBoxJSON() { - String localUserData = ProjectMacros.readRaw(R.raw.local_user_data, this); - String boxData = ProjectMacros.readRaw(R.raw.box, this); - - ProjectMacros.saveFile(this, "localUserData.json", localUserData); - d("dbg_file", ProjectMacros.readFile(this, "localUserData.json")); - - recreate(); - } - @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); diff --git a/app/src/main/java/com/yearthreeproject/xbframework/NewBox.java b/app/src/main/java/com/yearthreeproject/xbframework/NewBoxActivity.java similarity index 89% rename from app/src/main/java/com/yearthreeproject/xbframework/NewBox.java rename to app/src/main/java/com/yearthreeproject/xbframework/NewBoxActivity.java index 6645f711be35e539888c8b7a9a65ac08af7af995..233a29782278da2c7077124208194b6a663aaaf0 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/NewBox.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/NewBoxActivity.java @@ -48,7 +48,7 @@ import java.util.Objects; import static android.util.Log.d; import static com.yearthreeproject.xbframework.ProjectMacros.showToast; -public class NewBox extends AppCompatActivity { +public class NewBoxActivity extends AppCompatActivity { private Uri imageUploadResultUri; @@ -56,6 +56,8 @@ public class NewBox extends AppCompatActivity { final private List<List<EditText>> experimentTitlesArray = new ArrayList<>(); final private List<List<EditText>> experimentDescriptionsArray = new ArrayList<>(); final private List<List<EditText>> experimentInstructionsArray = new ArrayList<>(); + final private List<List<TextView>> experimentNumberLabelArray = new ArrayList<>(); + final private List<TextView> groupTitleLabelArray = new ArrayList<>(); private ImageView uploadImageButton; private int globalGroupIndex = 0; @@ -232,7 +234,7 @@ public class NewBox extends AppCompatActivity { } box.put("Experiments", experimentGroups); - Intent openPage = new Intent(NewBox.this, ExperimentSurveyCreatorActivity.class); + Intent openPage = new Intent(NewBoxActivity.this, ExperimentSurveyCreatorActivity.class); openPage.putExtra("JSON", box.toString()); openPage.putExtra("ExperimentIndex", 0); openPage.putExtra("GroupIndex", 0); @@ -248,14 +250,14 @@ public class NewBox extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) private void imagePermissionCheckFunction() { - if (ContextCompat.checkSelfPermission(NewBox.this, + if (ContextCompat.checkSelfPermission(NewBoxActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { - if (ActivityCompat.shouldShowRequestPermissionRationale(NewBox.this, + if (ActivityCompat.shouldShowRequestPermissionRationale(NewBoxActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) { - AlertDialog.Builder builder = new AlertDialog.Builder(NewBox.this); + AlertDialog.Builder builder = new AlertDialog.Builder(NewBoxActivity.this); builder.setTitle("Permission Required") .setMessage("Permission to device storage is required for image upload.") .setPositiveButton("Ok", (dialog, which) -> { @@ -266,7 +268,7 @@ public class NewBox extends AppCompatActivity { }).setNegativeButton("Cancel", null).show(); } else { - ActivityCompat.requestPermissions(NewBox.this, + ActivityCompat.requestPermissions(NewBoxActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1); } @@ -282,31 +284,35 @@ public class NewBox extends AppCompatActivity { linearGroupLayout.setOrientation(LinearLayout.VERTICAL); linearGroupLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + experimentNumberLabelArray.add(new ArrayList<>()); + final RelativeLayout relativeGroupLayout = new RelativeLayout(this); - TextView titleTextView = new TextView(NewBox.this); - String textViewTempText = "Group Title:"; + TextView titleTextView = new TextView(NewBoxActivity.this); + String textViewTempText = "Group " + (globalGroupIndex+1) + " Title:"; titleTextView.setText(textViewTempText); titleTextView.setGravity(Gravity.CENTER_VERTICAL); titleTextView.setId(uniqueId++); + groupTitleLabelArray.add(titleTextView); - final EditText titleEditText = new EditText(NewBox.this); - titleEditText.setHint(textViewTempText.substring(0, 11)); + textViewTempText = "Group Title"; + final EditText titleEditText = new EditText(NewBoxActivity.this); + titleEditText.setHint(textViewTempText); titleEditText.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME); titleEditText.setId(uniqueId++); - Button deleteGroupButton = new Button(NewBox.this); + Button deleteGroupButton = new Button(NewBoxActivity.this); textViewTempText = "x"; deleteGroupButton.setText(textViewTempText); deleteGroupButton.setId(uniqueId++); - final TextView experimentsTextView = new TextView(NewBox.this); + final TextView experimentsTextView = new TextView(NewBoxActivity.this); textViewTempText = "Experiments:"; experimentsTextView.setText(textViewTempText); experimentsTextView.setGravity(Gravity.CENTER_VERTICAL); experimentsTextView.setId(uniqueId++); - final Button addExperimentToGroupButton = new Button(NewBox.this); + final Button addExperimentToGroupButton = new Button(NewBoxActivity.this); textViewTempText = "Add Experiment"; addExperimentToGroupButton.setText(textViewTempText); addExperimentToGroupButton.setId(uniqueId++); @@ -339,12 +345,12 @@ public class NewBox extends AppCompatActivity { addExperimentToGroupButton.setOnClickListener(v -> { LinearLayout parent = (LinearLayout) v.getParent(); parent.removeView(v); - linearGroupLayout.addView(addExperimentFunction(localGroupIndex)); + linearGroupLayout.addView(addExperimentFunction(localGroupIndex, 0, v, linearGroupLayout)); parent.addView(v); }); deleteGroupButton.setOnClickListener(v -> { - AlertDialog.Builder al = new AlertDialog.Builder(NewBox.this); + AlertDialog.Builder al = new AlertDialog.Builder(NewBoxActivity.this); al.setTitle("Are you sure?") .setMessage("Are you sure you want to delete this group?") .setPositiveButton("Yes", (dialog, which) -> { @@ -353,7 +359,12 @@ public class NewBox extends AppCompatActivity { experimentTitlesArray.remove(localGroupIndex); experimentDescriptionsArray.remove(localGroupIndex); experimentInstructionsArray.remove(localGroupIndex); + experimentNumberLabelArray.remove(localGroupIndex); + groupTitleLabelArray.remove(localGroupIndex); globalGroupIndex--; + for(int i = 0; i < groupTitlesArray.size(); i++){ + groupTitleLabelArray.get(i).setText("Group " + (i+1) + " Title:"); + } }).setNegativeButton("No", null) .show(); }); @@ -366,44 +377,45 @@ public class NewBox extends AppCompatActivity { } @SuppressLint("ResourceType") - private RelativeLayout addExperimentFunction(final int localGroupIndex) { + private RelativeLayout addExperimentFunction(final int localGroupIndex, final int experimentIndex, View v, LinearLayout linearGroupLayout) { final RelativeLayout experimentRelativeLayout = new RelativeLayout(this); TextView experimentNumberLabel = new TextView(this); - String textViewTempText = "Experiment " + (experimentTitlesArray.size() + 1) + ":"; + String textViewTempText = "Experiment " + (experimentIndex+1) + ":"; experimentNumberLabel.setText(textViewTempText); experimentNumberLabel.setId(uniqueId++); + experimentNumberLabelArray.get(localGroupIndex).add(experimentNumberLabel); - TextView experimentTitleTextView = new TextView(NewBox.this); + TextView experimentTitleTextView = new TextView(NewBoxActivity.this); textViewTempText = "Title:"; experimentTitleTextView.setText(textViewTempText); experimentTitleTextView.setId(uniqueId++); - TextView experimentDescriptionTextView = new TextView(NewBox.this); + TextView experimentDescriptionTextView = new TextView(NewBoxActivity.this); textViewTempText = "Description:"; experimentDescriptionTextView.setText(textViewTempText); experimentDescriptionTextView.setId(uniqueId++); - TextView experimentInstructionsTextView = new TextView(NewBox.this); + TextView experimentInstructionsTextView = new TextView(NewBoxActivity.this); textViewTempText = "Instructions:"; experimentInstructionsTextView.setText(textViewTempText); experimentInstructionsTextView.setId(uniqueId++); - final EditText experimentTitleEditText = new EditText(NewBox.this); + final EditText experimentTitleEditText = new EditText(NewBoxActivity.this); textViewTempText = "Title"; experimentTitleEditText.setHint(textViewTempText); experimentTitleEditText.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME); experimentTitleEditText.setId(uniqueId++); experimentTitlesArray.get(localGroupIndex).add(experimentTitleEditText); - final EditText experimentDescriptionEditText = new EditText(NewBox.this); + final EditText experimentDescriptionEditText = new EditText(NewBoxActivity.this); textViewTempText = "Description"; experimentDescriptionEditText.setHint(textViewTempText); experimentDescriptionEditText.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME); experimentDescriptionEditText.setId(uniqueId++); experimentDescriptionsArray.get(localGroupIndex).add(experimentDescriptionEditText); - final EditText experimentInstructionsEditText = new EditText(NewBox.this); + final EditText experimentInstructionsEditText = new EditText(NewBoxActivity.this); textViewTempText = "Instructions"; experimentInstructionsEditText.setHint(textViewTempText); experimentInstructionsEditText.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME); @@ -447,29 +459,44 @@ public class NewBox extends AppCompatActivity { experimentRelativeLayout.addView(experimentInstructionsTextView, experimentInstructionsTextViewAlignment); experimentRelativeLayout.addView(ProjectMacros.newHR(this, 2, getString(R.color.colorPrimary)), localHRAlignment); - Button deleteExperimentButton = new Button(NewBox.this); + Button deleteExperimentButton = new Button(NewBoxActivity.this); textViewTempText = "x"; deleteExperimentButton.setText(textViewTempText); - deleteExperimentButton.setOnClickListener(v -> { - ViewGroup deleteExperimentButtonParent = (ViewGroup) v.getParent(); + deleteExperimentButton.setOnClickListener(v2 -> { + v.setOnClickListener(view->{ + LinearLayout parent = (LinearLayout) v.getParent(); + parent.removeView(v); + linearGroupLayout.addView(addExperimentFunction(localGroupIndex, experimentTitlesArray.get(localGroupIndex).size(), v, linearGroupLayout)); + parent.addView(v); + }); + + experimentNumberLabelArray.get(localGroupIndex).remove(experimentNumberLabel); + + for(int i =0; i < experimentNumberLabelArray.get(localGroupIndex).size(); i++){ + experimentNumberLabelArray.get(localGroupIndex).get(i).setText("Experiment " + (i+1) + ":"); + } + + ViewGroup deleteExperimentButtonParent = (ViewGroup) v2.getParent(); experimentTitlesArray.get(localGroupIndex).remove(experimentTitleEditText); experimentDescriptionsArray.get(localGroupIndex).remove(experimentDescriptionEditText); experimentInstructionsArray.get(localGroupIndex).remove(experimentInstructionsEditText); experimentRelativeLayout.removeAllViews(); - deleteExperimentButtonParent.removeView(v); + deleteExperimentButtonParent.removeView(v2); }); - final Button addAnotherExperimentButton = new Button(NewBox.this); - textViewTempText = "Add Experiment"; - addAnotherExperimentButton.setText(textViewTempText); - addAnotherExperimentButton.setOnClickListener(v -> addExperimentFunction(localGroupIndex)); - RelativeLayout.LayoutParams deleteExperimentButtonAlignment = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); deleteExperimentButtonAlignment.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); deleteExperimentButtonAlignment.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); experimentRelativeLayout.addView(deleteExperimentButton, deleteExperimentButtonAlignment); + v.setOnClickListener(view->{ + LinearLayout parent = (LinearLayout) v.getParent(); + parent.removeView(v); + linearGroupLayout.addView(addExperimentFunction(localGroupIndex, experimentIndex+1, v, linearGroupLayout)); + parent.addView(v); + }); + return experimentRelativeLayout; } @@ -503,7 +530,7 @@ public class NewBox extends AppCompatActivity { d("dbg_Perm", "granted"); startImageUpload(); } else { - AlertDialog.Builder builder = new AlertDialog.Builder(NewBox.this); + AlertDialog.Builder builder = new AlertDialog.Builder(NewBoxActivity.this); builder.setTitle("Permission Required") .setMessage("Permission to device storage is required for image upload.") .setPositiveButton("Ok", (dialog, which) -> { @@ -521,6 +548,6 @@ public class NewBox extends AppCompatActivity { .setMinCropResultSize(100, 100) .setGuidelines(CropImageView.Guidelines.OFF) .setFixAspectRatio(true) - .start(NewBox.this); + .start(NewBoxActivity.this); } } diff --git a/app/src/main/java/com/yearthreeproject/xbframework/ProgressActivity.java b/app/src/main/java/com/yearthreeproject/xbframework/ProgressActivity.java index c3d469b88bb2e36be465cb770ec85d062be5a1d8..2501813ec52c768f8bd878bb4a26de59a1040d98 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/ProgressActivity.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/ProgressActivity.java @@ -1,15 +1,12 @@ package com.yearthreeproject.xbframework; -import android.content.Context; import android.content.DialogInterface; -import android.content.SharedPreferences; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.os.Bundle; import android.text.Html; -import android.util.Log; import android.view.ViewGroup; import android.widget.EditText; import android.widget.LinearLayout; @@ -37,7 +34,6 @@ import com.mongodb.stitch.android.core.Stitch; import com.mongodb.stitch.android.core.StitchAppClient; import com.mongodb.stitch.android.services.mongodb.remote.RemoteMongoClient; import com.mongodb.stitch.android.services.mongodb.remote.RemoteMongoCollection; -import com.mongodb.stitch.core.auth.providers.userpassword.UserPasswordCredential; import com.mongodb.stitch.core.services.mongodb.remote.RemoteUpdateOptions; import org.bson.Document; @@ -117,6 +113,9 @@ public class ProgressActivity extends AppCompatActivity { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); + oldDateGraph = new Date(); + oldDateJournal = new Date(); + toolbar.setOnClickListener(v -> findViewById(R.id.progressScrollObject).scrollTo(0,0)); final LinearLayout mainBody = findViewById(R.id.progressScrollLinLay); @@ -145,16 +144,20 @@ public class ProgressActivity extends AppCompatActivity { if(localUserData.getBoolean("locked")) generateCurrentExperimentGraph(calendarView); - String experimentName; + String experimentName = null; + String startDateString = null; + String highestDateString = null; if(currentExperimentData != null && archivedExperimentData != null){ if(currentExperimentData.length() != 0 || archivedExperimentData.length() != 0){ List<DataPoint> dataSeries; - if(localUserData.getBoolean("locked") && currentExperimentData.length() > 1){ + if(localUserData.getBoolean("locked") && currentExperimentData.length() >= 1){ experimentName = localUserData.getJSONObject("lockedExperiment").getString("Title"); dataSeries = loopJSONArrayForPoints(currentExperimentData, new ArrayList<DataPoint>()); lowest = loopJSONArrayForLowest(currentExperimentData, lowest); + startDateString = currentExperimentData.getJSONObject(0).getString("startDate"); + highestDateString = currentExperimentData.getJSONObject(currentExperimentData.length()-1).getString("Date"); } else { long highest = cal.getTime().getTime(); int highestIndex = 0; @@ -170,8 +173,14 @@ public class ProgressActivity extends AppCompatActivity { } } experimentName = archivedExperimentData.getJSONObject(highestIndex).getString("Experiment"); + startDateString = archivedExperimentData.getJSONObject(highestIndex).getString("startDate"); + highestDateString = archivedExperimentData.getJSONObject(highestIndex).getString("Date"); + + Calendar tempTime = Calendar.getInstance(); + tempTime.setTimeInMillis(highest); - dataSeries = arrayLoopForSelectedDateForData(archivedExperimentData, new ArrayList<DataPoint>(), experimentName); + long startDateLong = arrayLoopForSelectedDateStartDate(archivedExperimentData, tempTime.getTime()); + dataSeries = arrayLoopForSelectedDateForData(archivedExperimentData, new ArrayList<DataPoint>(), experimentName, startDateLong); lowest = arrayLoopForSelectedDateForLowest(archivedExperimentData, lowest, experimentName); oldDateGraph = new Date(highest); @@ -204,14 +213,12 @@ public class ProgressActivity extends AppCompatActivity { calendarView.addView(noDataMessage); } } else { - oldDateGraph = new Date(); - oldDateJournal = new Date(); TextView noDataMessage = new TextView(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { noDataMessage.setTextColor(getColor(R.color.colorPrimary)); } noDataMessage.setTextSize(30); - noDataMessage.setText(Html.fromHtml("There has been no experiment data to show yet!")); + noDataMessage.setText(Html.fromHtml("There has been no current experiment data to be shown yet!")); calendarView.addView(noDataMessage); } @@ -221,10 +228,9 @@ public class ProgressActivity extends AppCompatActivity { journalView.addView(ProjectMacros.newHR(this, 10,"#587B7F")); generateJournalTodaysEntry(journalView); journalView.addView(ProjectMacros.newHR(this, 10,"#587B7F")); - generateJournalSelectedEntry(journalView); + generateJournalSelectedEntry(journalView, experimentName, highestDateString); journalView.addView(ProjectMacros.newHR(this, 10,"#587B7F")); - generateJournalExperimentEntries(journalView, ""); - + generateJournalExperimentEntries(journalView, experimentName, startDateString); final FloatingActionButton journalFAB = findViewById(R.id.editCurrentJournal); final ViewGroup coordinateLayout = findViewById(R.id.mainScreen); @@ -246,146 +252,170 @@ public class ProgressActivity extends AppCompatActivity { input.setText(todaysEntryText.getText()); } - alert.setPositiveButton("Save", new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int whichButton) { - if(input.getText().toString().equals("")) { - todaysEntryText.setText(match); - try{ - JSONArray journalEntriesOut = new JSONArray(); - - Calendar cal1 = Calendar.getInstance(); - cal1.set(Calendar.MILLISECOND, 0); - cal1.set(Calendar.SECOND, 0); - cal1.set(Calendar.MINUTE, 0); - cal1.set(Calendar.HOUR, 0); - Date today = cal1.getTime(); - SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY", Locale.getDefault()); + alert.setPositiveButton("Save", (dialog, whichButton) -> { + if(input.getText().toString().equals("")) { + todaysEntryText.setText(match); + try{ + JSONArray journalEntriesOut = new JSONArray(); + + Calendar cal1 = Calendar.getInstance(); + cal1.set(Calendar.MILLISECOND, 0); + cal1.set(Calendar.SECOND, 0); + cal1.set(Calendar.MINUTE, 0); + cal1.set(Calendar.HOUR, 0); + Date today = cal1.getTime(); + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY", Locale.getDefault()); - for(int i = 0; i < journalArray.length(); i++){ - if(!sdf.format(today).equals(journalArray.getJSONObject(i).getString("Date"))){ - journalEntriesOut.put(journalArray.getJSONObject(i)); - } + for(int i = 0; i < journalArray.length(); i++){ + if(!sdf.format(today).equals(journalArray.getJSONObject(i).getString("Date"))){ + journalEntriesOut.put(journalArray.getJSONObject(i)); } + } - if(sdf.format(oldDateJournal).equals(sdf.format(today))){ - selectedEntryTitle.setText(Html.fromHtml(localUserData.getJSONObject("lockedExperiment").getString("Title") + " (" + sdf.format(today) + "):")); - selectedEntryText.setText(todaysEntryText.getText().toString()); + if(sdf.format(oldDateJournal).equals(sdf.format(today))){ + selectedEntryTitle.setText(Html.fromHtml(localUserData.getJSONObject("lockedExperiment").getString("Title") + " (" + sdf.format(today) + "):")); + selectedEntryText.setText(todaysEntryText.getText().toString()); + } - } + localUserData.put("journal", journalEntriesOut); + ProjectMacros.saveFile(ProgressActivity.this, "localUserData.json", localUserData.toString()); - localUserData.put("journal", journalEntriesOut); - ProjectMacros.saveFile(ProgressActivity.this, "localUserData.json", localUserData.toString()); + final StitchAppClient client; + if(Stitch.hasAppClient(getString(R.string.mongo_stitch_id))){ + client = Stitch.getDefaultAppClient(); + } else { + client = Stitch.initializeDefaultAppClient(getString(R.string.mongo_stitch_id)); + } - final StitchAppClient client; - if(Stitch.hasAppClient(getString(R.string.mongo_stitch_id))){ - client = Stitch.getDefaultAppClient(); - } else { - client = Stitch.initializeDefaultAppClient(getString(R.string.mongo_stitch_id)); + final RemoteMongoClient mongoClient = client.getServiceClient(RemoteMongoClient.factory, "XBF"); + final RemoteMongoCollection<Document> coll = mongoClient.getDatabase("IPServer").getCollection("UserData"); + + client.getAuth().addAuthListener(auth -> { + if (auth.isLoggedIn()) { + coll.updateOne( + new Document("owner_id", auth.getUser().getId()), + Document.parse(localUserData.toString()) + .append("owner_id", auth.getUser().getId()), + new RemoteUpdateOptions().upsert(true)).addOnCompleteListener(task1->{ + try { + calendarViewForJournal.addEvent(new Event(latestExperimentColor, cal1.getTimeInMillis(), localUserData.getJSONObject("lockedExperiment").getString("Title"))); + } catch (JSONException e) { + e.printStackTrace(); + } + d("dbg_was_succesful", String.valueOf(task1.isSuccessful())); + d("dbg_storedJSON", localUserData.toString()); + }); } + }); - final RemoteMongoClient mongoClient = client.getServiceClient(RemoteMongoClient.factory, "XBF"); - final RemoteMongoCollection<Document> coll = mongoClient.getDatabase("IPServer").getCollection("UserData"); - - client.getAuth().addAuthListener(auth -> { - if (auth.isLoggedIn()) { - coll.updateOne( - new Document("owner_id", auth.getUser().getId()), - Document.parse(localUserData.toString()) - .append("owner_id", auth.getUser().getId()), - new RemoteUpdateOptions().upsert(true)).addOnCompleteListener(task1->{ - try { - calendarViewForJournal.addEvent(new Event(latestExperimentColor, cal1.getTimeInMillis(), localUserData.getJSONObject("lockedExperiment").getString("Title"))); - } catch (JSONException e) { - e.printStackTrace(); - } - d("dbg_was_succesful", String.valueOf(task1.isSuccessful())); - d("dbg_storedJSON", localUserData.toString()); - }); - } - }); + } catch (JSONException e){ + e.printStackTrace(); + } + } else { + todaysEntryText.setText(input.getText().toString()); + try{ + JSONArray journalEntriesOut = new JSONArray(); + + Calendar cal1 = Calendar.getInstance(); + cal1.set(Calendar.MILLISECOND, 0); + cal1.set(Calendar.SECOND, 0); + cal1.set(Calendar.MINUTE, 0); + cal1.set(Calendar.HOUR, 0); + Date today = cal1.getTime(); + + Calendar startDateCal = Calendar.getInstance(); + startDateCal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(localUserData.getString("dateUntil").substring(0,2))-5); + startDateCal.set(Calendar.MONTH, Integer.parseInt(localUserData.getString("dateUntil").substring(3,5))-1); + startDateCal.set(Calendar.YEAR, Integer.parseInt(localUserData.getString("dateUntil").substring(6,10))); - } catch (JSONException e){ - e.printStackTrace(); - } - } else{ - todaysEntryText.setText(input.getText().toString()); - try{ - JSONArray journalEntriesOut = new JSONArray(); - - Calendar cal1 = Calendar.getInstance(); - cal1.set(Calendar.MILLISECOND, 0); - cal1.set(Calendar.SECOND, 0); - cal1.set(Calendar.MINUTE, 0); - cal1.set(Calendar.HOUR, 0); - Date today = cal1.getTime(); - SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY", Locale.getDefault()); - - boolean todayExists = false; - - if(journalArray != null){ - for(int i = 0; i < journalArray.length(); i++){ - if(sdf.format(today).equals(journalArray.getJSONObject(i).getString("Date"))){ - todayExists = true; - JSONObject tempObject = new JSONObject(); - tempObject.put("Date", sdf.format(today)); - tempObject.put("Experiment", localUserData.getJSONObject("lockedExperiment").getString("Title")); - tempObject.put("Entry", input.getText()); - journalEntriesOut.put(tempObject); + SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY", Locale.getDefault()); + + boolean todayExists = false; + + if(journalArray != null){ + d("dbg_journalLength", String.valueOf(journalArray.length())); + for(int i = 0; i < journalArray.length(); i++){ + if(sdf.format(today).equals(journalArray.getJSONObject(i).getString("Date"))){ + todayExists = true; + JSONObject tempObject = new JSONObject(); + tempObject.put("Date", sdf.format(today)); + tempObject.put("startDate", sdf.format(startDateCal.getTime())); + if(localUserData.getJSONObject("lockedExperiment").optString("Title", "NoValidString").equals("NoValidString")){ + tempObject.put("Experiment", "None"); } else { - journalEntriesOut.put(journalArray.getJSONObject(i)); + tempObject.put("Experiment", localUserData.getJSONObject("lockedExperiment").getString("Title")); } + tempObject.put("Entry", input.getText()); + journalEntriesOut.put(tempObject); + } else { + d("dbg_oldJournalAdded", "true"); + journalEntriesOut.put(journalArray.getJSONObject(i)); } } + } + + if(!todayExists) { + JSONObject tempObject = new JSONObject(); - if(!todayExists) { - JSONObject tempObject = new JSONObject(); - tempObject.put("Date", sdf.format(today)); + tempObject.put("Date", sdf.format(today)); + tempObject.put("startDate", sdf.format(startDateCal.getTime())); + if(localUserData.getJSONObject("lockedExperiment").optString("Title", "NoValidString").equals("NoValidString")){ + tempObject.put("Experiment", "None"); + } else { tempObject.put("Experiment", localUserData.getJSONObject("lockedExperiment").getString("Title")); - tempObject.put("Entry", input.getText()); - journalEntriesOut.put(journalEntriesOut.length()-1, tempObject); } + tempObject.put("Entry", input.getText()); + journalEntriesOut.put(tempObject); + } + + if(localUserData.getJSONObject("lockedExperiment").optString("Title", "noExperiment").matches("noExperiment")){ + calendarViewForJournal.addEvent(new Event(latestExperimentColor, today.getTime(), "No Experiment")); + } else { + calendarViewForJournal.addEvent(new Event(latestExperimentColor, today.getTime(), localUserData.getJSONObject("lockedExperiment").getString("Title"))); + } + - if(sdf.format(oldDateJournal).equals(sdf.format(today))){ + if(sdf.format(oldDateJournal).equals(sdf.format(today))){ + if(localUserData.getJSONObject("lockedExperiment").optString("Title", "NoValidString").equals("NoValidString")){ + selectedEntryTitle.setText(Html.fromHtml("None (" + sdf.format(today) + "):")); + } else { selectedEntryTitle.setText(Html.fromHtml(localUserData.getJSONObject("lockedExperiment").getString("Title") + " (" + sdf.format(today) + "):")); - selectedEntryText.setText(todaysEntryText.getText().toString()); } + selectedEntryText.setText(todaysEntryText.getText().toString()); + } - localUserData.put("journal", journalEntriesOut); - ProjectMacros.saveFile(ProgressActivity.this, "localUserData.json", localUserData.toString()); + localUserData.put("journal", journalEntriesOut); + ProjectMacros.saveFile(ProgressActivity.this, "localUserData.json", localUserData.toString()); - final StitchAppClient client; - if(Stitch.hasAppClient(getString(R.string.mongo_stitch_id))){ - client = Stitch.getDefaultAppClient(); - } else { - client = Stitch.initializeDefaultAppClient(getString(R.string.mongo_stitch_id)); - } + final StitchAppClient client; + if(Stitch.hasAppClient(getString(R.string.mongo_stitch_id))){ + client = Stitch.getDefaultAppClient(); + } else { + client = Stitch.initializeDefaultAppClient(getString(R.string.mongo_stitch_id)); + } - final RemoteMongoClient mongoClient = client.getServiceClient(RemoteMongoClient.factory, "XBF"); - final RemoteMongoCollection<Document> coll = mongoClient.getDatabase("IPServer").getCollection("UserData"); - SharedPreferences savedSettings = ProgressActivity.this.getSharedPreferences("com.yearthreeproject.xbframework.PREFERENCE_FILE_KEY", Context.MODE_PRIVATE); + final RemoteMongoClient mongoClient = client.getServiceClient(RemoteMongoClient.factory, "XBF"); + final RemoteMongoCollection<Document> coll = mongoClient.getDatabase("IPServer").getCollection("UserData"); - client.getAuth().loginWithCredential(new UserPasswordCredential(savedSettings.getString("email", "invalid"), savedSettings.getString("password", "invalid"))).addOnCompleteListener(task -> { - if (task.isSuccessful()) { - Log.d("stitch", "Successfully logged in as user " + task.getResult().getId()); - } - }).addOnCompleteListener(task->{ + client.getAuth().addAuthListener(auth -> { + if(auth.isLoggedIn()){ coll.updateOne( - new Document("owner_id", savedSettings.getString("ownerId", "invalid")), + new Document("owner_id", auth.getUser().getId()), Document.parse(localUserData.toString()) - .append("owner_id", savedSettings.getString("ownerId", "invalid")), + .append("owner_id", auth.getUser().getId()), new RemoteUpdateOptions().upsert(true)).addOnCompleteListener(task1->{ - d("dbg_was_succesful", String.valueOf(task1.isSuccessful())); - d("dbg_storedJSON", localUserData.toString()); + d("dbg_uploaded", "success"); }); - }); + } + }); - } catch (JSONException e) { - e.printStackTrace(); - } + } catch (JSONException e) { + e.printStackTrace(); } - }}); + } + }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { @@ -441,7 +471,7 @@ public class ProgressActivity extends AppCompatActivity { } @RequiresApi(api = Build.VERSION_CODES.KITKAT) - private void generateJournalExperimentEntries(LinearLayout parent, String experiment) { + private void generateJournalExperimentEntries(LinearLayout parent, String experiment, String startDate) { if(experimentJournalLayout == null){ experimentJournalLayout = new LinearLayout(this); experimentJournalLayout.setOrientation(LinearLayout.VERTICAL); @@ -450,36 +480,38 @@ public class ProgressActivity extends AppCompatActivity { if (localUserData.getBoolean("locked") && journalArray != null) { for (int i = 0; i < journalArray.length(); i++) { - if (journalArray.getJSONObject(i).getString("Experiment").equals(localUserData.getJSONObject("lockedExperiment").getString("Title"))){ - LinearLayout tempLayout = new LinearLayout(this); - tempLayout.setOrientation(LinearLayout.VERTICAL); - TextView tempTitle = new TextView(this); - TextView tempEntry = new TextView(this); - - Calendar cal = Calendar.getInstance(); - cal.set(Calendar.MILLISECOND, 0); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MINUTE, 0); - cal.set(Calendar.HOUR, 0); - cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(journalArray.getJSONObject(i).getString("Date").substring(0,2))); - cal.set(Calendar.MONTH, Integer.parseInt(journalArray.getJSONObject(i).getString("Date").substring(3,5))-1); - cal.set(Calendar.YEAR, Integer.parseInt(journalArray.getJSONObject(i).getString("Date").substring(6,10))); - Date dateValue = cal.getTime(); - SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY", Locale.getDefault()); - - tempTitle.setText(Html.fromHtml(journalArray.getJSONObject(i).getString("Experiment") + " (" + sdf.format(dateValue) + "):")); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - tempTitle.setTextColor(getColor(R.color.colorPrimary)); - } - tempTitle.setTextSize(20); + if(journalArray.getJSONObject(i) != JSONObject.NULL && localUserData.getJSONObject("lockedExperiment") != JSONObject.NULL && startDate != null){ + if (journalArray.getJSONObject(i).getString("Experiment").equals(localUserData.getJSONObject("lockedExperiment").getString("Title")) && (journalArray.getJSONObject(i).getString("startDate")).matches(startDate)){ + LinearLayout tempLayout = new LinearLayout(this); + tempLayout.setOrientation(LinearLayout.VERTICAL); + TextView tempTitle = new TextView(this); + TextView tempEntry = new TextView(this); + + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.MILLISECOND, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.HOUR, 0); + cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(journalArray.getJSONObject(i).getString("Date").substring(0,2))); + cal.set(Calendar.MONTH, Integer.parseInt(journalArray.getJSONObject(i).getString("Date").substring(3,5))-1); + cal.set(Calendar.YEAR, Integer.parseInt(journalArray.getJSONObject(i).getString("Date").substring(6,10))); + Date dateValue = cal.getTime(); + SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY", Locale.getDefault()); + + tempTitle.setText(Html.fromHtml(journalArray.getJSONObject(i).getString("Experiment") + " (" + sdf.format(dateValue) + "):")); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + tempTitle.setTextColor(getColor(R.color.colorPrimary)); + } + tempTitle.setTextSize(20); - tempEntry.setText(Html.fromHtml(journalArray.getJSONObject(i).getString("Entry"))); + tempEntry.setText(Html.fromHtml(journalArray.getJSONObject(i).getString("Entry"))); - tempLayout.addView(tempTitle); - tempLayout.addView(tempEntry); - tempLayout.addView(ProjectMacros.newHR(this, 4, "#587B7F")); + tempLayout.addView(tempTitle); + tempLayout.addView(tempEntry); + tempLayout.addView(ProjectMacros.newHR(this, 4, "#587B7F")); - experimentJournalLayout.addView(tempLayout); + experimentJournalLayout.addView(tempLayout); + } } } } @@ -532,21 +564,25 @@ public class ProgressActivity extends AppCompatActivity { } @RequiresApi(api = Build.VERSION_CODES.KITKAT) - private void generateJournalSelectedEntry(LinearLayout parent) { + private void generateJournalSelectedEntry(LinearLayout parent, String experimentName, String startDateString) throws JSONException { Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR, 0); - Date today = cal.getTime(); - SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY", Locale.getDefault()); + d("dbg_experiment_name_startString", experimentName + " " + startDateString); if(selectedJournalLayout == null){ selectedJournalLayout = new LinearLayout(this); selectedJournalLayout.setOrientation(LinearLayout.VERTICAL); selectedEntryTitle = new TextView(this); - selectedEntryTitle.setText(Html.fromHtml( "Select an entry!")); + if(todaysEntryText == null){ + selectedEntryTitle.setText(Html.fromHtml( "Select an entry!")); + } else { + selectedEntryTitle.setText(currentExperimentTitle.getText()); + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { selectedEntryTitle.setTextColor(getColor(R.color.colorPrimary)); } @@ -555,7 +591,24 @@ public class ProgressActivity extends AppCompatActivity { } if(selectedEntryText == null){ selectedEntryText = new TextView(this); - selectedEntryText.setText(Html.fromHtml("Or click the pen in the bottom right to add / edit an entry for today!")); + if(todaysEntryText == null){ + selectedEntryText.setText(Html.fromHtml("Or click the pen in the bottom right to add / edit an entry for today!")); + } else { + for(int i = 0; i < journalArray.length(); i++){ + cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(journalArray.getJSONObject(i).getString("Date").substring(0,2))); + cal.set(Calendar.MONTH, Integer.parseInt(journalArray.getJSONObject(i).getString("Date").substring(3,5))-1); + cal.set(Calendar.YEAR, Integer.parseInt(journalArray.getJSONObject(i).getString("Date").substring(6,10))); + Date dateValue = cal.getTime(); + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY", Locale.getDefault()); + + if(startDateString != null) { + if (sdf.format(dateValue).matches(startDateString)) { + selectedEntryText.setText(todaysEntryText.getText()); + } + } + } + } + } selectedJournalLayout.addView(selectedEntryText); parent.addView(selectedJournalLayout); @@ -587,7 +640,6 @@ public class ProgressActivity extends AppCompatActivity { todaysEntryText = new TextView(this); try{ - boolean entryToday = false; int entryIndex = 0; @@ -639,14 +691,24 @@ public class ProgressActivity extends AppCompatActivity { final String[] markColor = {"#8FFF0000","#8F0A8F0F","#8F0000FF"}; int markColorIndex = 0; String oldExperiment = ""; + int experimentCount = 0; if(journalArray != null){ d("dbg_jourNNull", "true"); for(int i = 0; i < journalArray.length(); i++){ if(i == 0) oldExperiment = journalArray.getJSONObject(i).getString("Experiment"); + if(experimentCount == 5){ + markColorIndex++; + experimentCount = 0; + oldExperiment = journalArray.getJSONObject(i).getString("Experiment"); + } + experimentCount++; + + d("dbg_exCount", String.valueOf(experimentCount)); if(!journalArray.getJSONObject(i).getString("Experiment").equals(oldExperiment)){ markColorIndex++; + experimentCount = 0; oldExperiment = journalArray.getJSONObject(i).getString("Experiment"); } @@ -678,7 +740,7 @@ public class ProgressActivity extends AppCompatActivity { if(calendarViewForJournal.getEvents(dateClicked).size() == 0){ ProjectMacros.showToast(progressToast, ProgressActivity.this, "Cannot select a date without data!"); - calendarViewForJournal.setCurrentDate(oldDateGraph); + calendarViewForJournal.setCurrentDate(oldDateJournal); Month[0] = dateFormatForMonth.format(calendarViewForJournal.getFirstDayOfCurrentMonth()); monthTextViewJournal.setText(Month[0]); } else { @@ -689,6 +751,7 @@ public class ProgressActivity extends AppCompatActivity { try { String experimentName = ""; + String startDate = ""; for (int i = 0; i < journalArray.length(); i++) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY", Locale.getDefault()); @@ -699,9 +762,10 @@ public class ProgressActivity extends AppCompatActivity { String entryTitle = journalArray.getJSONObject(i).getString("Experiment") + " (" + sdf.format(dateClicked) + "):"; selectedEntryTitle.setText(entryTitle); experimentName = journalArray.getJSONObject(i).getString("Experiment"); + startDate = journalArray.getJSONObject(i).getString("startDate"); } } - generateJournalExperimentEntries(parent, experimentName); + generateJournalExperimentEntries(parent, experimentName, startDate); } catch (JSONException e) { e.printStackTrace(); @@ -752,13 +816,23 @@ public class ProgressActivity extends AppCompatActivity { final String[] markColor = {"#8FFF0000","#8F0A8F0F","#8F0000FF"}; int markColorIndex = 0; String oldExperiment = ""; + int experimentCount = 0; if(archivedExperimentData != null){ for(int i = 0; i < archivedExperimentData.length(); i++){ if(i == 0) oldExperiment = archivedExperimentData.getJSONObject(i).getString("Experiment"); + if(experimentCount == 5){ + markColorIndex++; + experimentCount = 0; + oldExperiment = archivedExperimentData.getJSONObject(i).getString("Experiment"); + } + experimentCount++; + + d("dbg_exCount", String.valueOf(experimentCount)); if(!archivedExperimentData.getJSONObject(i).getString("Experiment").equals(oldExperiment)){ markColorIndex++; + experimentCount = 0; oldExperiment = archivedExperimentData.getJSONObject(i).getString("Experiment"); } @@ -812,11 +886,12 @@ public class ProgressActivity extends AppCompatActivity { try { List<DataPoint> dataSeries; String experimentName; + long startDate = 0; if(calendarViewForGraphs.getEvents(dateClicked).get(0).getData() != null){ experimentName = (String) calendarViewForGraphs.getEvents(dateClicked).get(0).getData(); - dataSeries = arrayLoopForSelectedDateForData(archivedExperimentData, new ArrayList<DataPoint>(), experimentName); - lowest = arrayLoopForSelectedDateForLowest(archivedExperimentData, lowest, experimentName); + startDate = arrayLoopForSelectedDateStartDate(archivedExperimentData, dateClicked); + dataSeries = arrayLoopForSelectedDateForData(archivedExperimentData, new ArrayList<DataPoint>(), experimentName, startDate); } else { experimentName = localUserData.getJSONObject("lockedExperiment").getString("Title"); dataSeries = loopJSONArrayForPoints(currentExperimentData, new ArrayList<DataPoint>()); @@ -833,7 +908,11 @@ public class ProgressActivity extends AppCompatActivity { } } - generateSelectedGraph(parent, series, lowest); + if(calendarViewForGraphs.getEvents(dateClicked).get(0).getData() != null){ + generateSelectedGraph(parent, series, startDate); + } else { + generateSelectedGraph(parent, series, lowest); + } String graphTitleString = "Experiment: " + experimentName; selectedGraphTitle.setText(graphTitleString); @@ -887,13 +966,10 @@ public class ProgressActivity extends AppCompatActivity { LineGraphSeries<DataPoint> series1 = new LineGraphSeries< >(series); PointsGraphSeries<DataPoint> series2 = new PointsGraphSeries<>(series); - series2.setCustomShape(new PointsGraphSeries.CustomShape() { - @Override - public void draw(Canvas canvas, Paint paint, float x, float y, DataPointInterface dataPoint) { - paint.setStrokeWidth(7); - canvas.drawLine(x-15, y-15, x+15, y+15, paint); - canvas.drawLine(x+15, y-15, x-15, y+15, paint); - } + series2.setCustomShape((canvas, paint, x, y, dataPoint) -> { + paint.setStrokeWidth(7); + canvas.drawLine(x-15, y-15, x+15, y+15, paint); + canvas.drawLine(x+15, y-15, x-15, y+15, paint); }); selectedGraph.addSeries(series1); @@ -922,7 +998,14 @@ public class ProgressActivity extends AppCompatActivity { try { if (currentExperimentData != null) { - currentExperimentTitle.setText(Html.fromHtml("Current Experiment: " + localUserData.getJSONObject("lockedExperiment").getString("Title"))); + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.HOUR, 0); + + SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY", Locale.getDefault()); + + currentExperimentTitle.setText(localUserData.getJSONObject("lockedExperiment").getString("Title") + " (" + sdf.format(cal.getTime()) + "):"); DataPoint[] dataSeries; @@ -1068,7 +1151,7 @@ public class ProgressActivity extends AppCompatActivity { graph.getGridLabelRenderer().setNumHorizontalLabels(5); graph.getViewport().setMaxY(5); - graph.getViewport().setMinY(0); + graph.getViewport().setMinY(1); graph.getViewport().setYAxisBoundsManual(true); graph.getViewport().setMinX(lowest-2500); @@ -1080,9 +1163,16 @@ public class ProgressActivity extends AppCompatActivity { graph.getGridLabelRenderer().setHumanRounding(false); } - private List<DataPoint> arrayLoopForSelectedDateForData(JSONArray array, List<DataPoint> dataSeries, String match){ + private List<DataPoint> arrayLoopForSelectedDateForData(JSONArray array, List<DataPoint> dataSeries, String match, long startDate){ try{ Calendar cal = Calendar.getInstance(); + Calendar startCal = Calendar.getInstance(); + + startCal.set(Calendar.MINUTE, 0); + startCal.set(Calendar.SECOND, 0); + startCal.set(Calendar.HOUR, 0); + + cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.HOUR, 0); @@ -1093,8 +1183,14 @@ public class ProgressActivity extends AppCompatActivity { cal.set(Calendar.MONTH, Integer.parseInt(array.getJSONObject(i).getString("Date").substring(3,5))-1); cal.set(Calendar.YEAR, Integer.parseInt(array.getJSONObject(i).getString("Date").substring(6,10))); - Date tempDate = cal.getTime(); - dataSeries.add(new DataPoint(tempDate, Double.parseDouble(array.getJSONObject(i).getString("AverageResult")))); + startCal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(array.getJSONObject(i).getString("startDate").substring(0,2))); + startCal.set(Calendar.MONTH, Integer.parseInt(array.getJSONObject(i).getString("startDate").substring(3,5))-1); + startCal.set(Calendar.YEAR, Integer.parseInt(array.getJSONObject(i).getString("startDate").substring(6,10))); + + if(startDate == startCal.getTimeInMillis()){ + Date tempDate = cal.getTime(); + dataSeries.add(new DataPoint(tempDate, Double.parseDouble(array.getJSONObject(i).getString("AverageResult")))); + } } } return dataSeries; @@ -1104,6 +1200,30 @@ public class ProgressActivity extends AppCompatActivity { } } + private long arrayLoopForSelectedDateStartDate(JSONArray array, Date dateClicked) { + try{ + Calendar cal = Calendar.getInstance(); + cal.set(Calendar.MINUTE, 0); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.HOUR, 0); + + SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY", Locale.getDefault()); + + for (int i = 0; i < array.length(); i++) { + if (sdf.format(dateClicked).equals(array.getJSONObject(i).getString("Date"))) { + cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(array.getJSONObject(i).getString("startDate").substring(0,2))); + cal.set(Calendar.MONTH, Integer.parseInt(array.getJSONObject(i).getString("startDate").substring(3,5))-1); + cal.set(Calendar.YEAR, Integer.parseInt(array.getJSONObject(i).getString("startDate").substring(6,10))); + } + } + + return cal.getTime().getTime(); + } catch (JSONException e){ + e.printStackTrace(); + return 0; + } + } + private long arrayLoopForSelectedDateForLowest(@NonNull JSONArray array, long lowest, String match){ try{ Calendar cal = Calendar.getInstance(); diff --git a/app/src/main/java/com/yearthreeproject/xbframework/ProjectMacros.java b/app/src/main/java/com/yearthreeproject/xbframework/ProjectMacros.java index 0e0e206affb3a4bc84623746997afe2ccd049764..9ee17fb8e5159bee7f70d3dd2659e58875558003 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/ProjectMacros.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/ProjectMacros.java @@ -272,22 +272,4 @@ class ProjectMacros { return false; } - static String readRaw(int resource, Context context) { - InputStream inputStream = context.getResources().openRawResource(resource); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - int ctr; - String outputString = ""; - try { - ctr = inputStream.read(); - while (ctr != -1) { - byteArrayOutputStream.write(ctr); - ctr = inputStream.read(); - } - inputStream.close(); - outputString = byteArrayOutputStream.toString(); - } catch (Exception e) { - e.printStackTrace(); - } - return outputString; - } } diff --git a/app/src/main/java/com/yearthreeproject/xbframework/ShopActivity.java b/app/src/main/java/com/yearthreeproject/xbframework/ShopActivity.java index d5e9e4d67ae8e8b59220bafe859f90c985f83774..ea69101468341655992b6f0170d83437493997fc 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/ShopActivity.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/ShopActivity.java @@ -2,6 +2,7 @@ package com.yearthreeproject.xbframework; import android.annotation.SuppressLint; import android.graphics.Color; +import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.view.Gravity; @@ -109,7 +110,9 @@ public class ShopActivity extends AppCompatActivity { shopItemCard.setLayoutParams(cardParams); - shopItemCard.setCardBackgroundColor(Color.parseColor("#E6E6E6")); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + shopItemCard.setCardBackgroundColor(getColor(R.color.colorPrimaryAccent)); + } shopItemCard.setMaxCardElevation((float) 0.0); shopItemCard.setRadius((float) 5.0); @@ -122,16 +125,21 @@ public class ShopActivity extends AppCompatActivity { TextView itemTitle = new TextView(ShopActivity.this); itemTitle.setId(uniqueId++); itemTitle.setText(shopItem.getString("Title")); + itemTitle.setTypeface(itemTitle.getTypeface(), Typeface.BOLD); + itemTitle.setPadding(6,6,6,6); TextView itemDesc = new TextView(ShopActivity.this); itemDesc.setId(uniqueId++); itemDesc.setText(shopItem.getString("Blurb")); + itemDesc.setPadding(6,6,6,6); TextView itemPrice = new TextView(ShopActivity.this); itemPrice.setId(uniqueId++); - String textViewTempText = Double.toString(shopItem.getDouble("Price")); + String textViewTempText = "£" + Double.toString(shopItem.getDouble("Price")); itemPrice.setText(textViewTempText); - itemPrice.setBackgroundColor(Color.parseColor("#FFFFFF")); + itemPrice.setTypeface(itemPrice.getTypeface(), Typeface.ITALIC); + itemPrice.setBackgroundColor(Color.parseColor("#CED9D9")); + itemPrice.setPadding(6,6,6,6); RelativeLayout.LayoutParams imageParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); imageParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); @@ -155,6 +163,8 @@ public class ShopActivity extends AppCompatActivity { shopItemLL.addView(itemPrice, priceParams); shopItemLL.addView(itemDesc, descParams); + shopItemCard.setContentPadding(6,6,6,6); + shopItemCard.addView(shopItemLL); shopItemCard.setOnClickListener(new OnClickListener() { diff --git a/app/src/main/java/com/yearthreeproject/xbframework/SurveyResponseActivity.java b/app/src/main/java/com/yearthreeproject/xbframework/SurveyResponseActivity.java index 59c8b85d500a00f76961f26631ec5e3628c06a57..48060e2dae88cc59ea770d3bd77c9f96080febb7 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/SurveyResponseActivity.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/SurveyResponseActivity.java @@ -125,12 +125,17 @@ public class SurveyResponseActivity extends AppCompatActivity { Date today = Calendar.getInstance().getTime(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY", Locale.getDefault()); + Calendar startDate = Calendar.getInstance(); + startDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(localDataJSON.getString("dateUntil").substring(0,2))-5); + startDate.set(Calendar.MONTH, Integer.parseInt(localDataJSON.getString("dateUntil").substring(3,5))-1); + startDate.set(Calendar.YEAR, Integer.parseInt(localDataJSON.getString("dateUntil").substring(6,10))); JSONObject todaysResponse = new JSONObject().put("Results", rawResponses) .put("Experiment", localDataJSON.getJSONObject("lockedExperiment").getString("Title")) .put("Type", localDataJSON.getJSONObject("lockedExperiment").getString("Type")) .put("Date", sdf.format(today)) - .put("AverageResult", averageResult); + .put("AverageResult", averageResult) + .put("startDate", sdf.format(startDate.getTime())); JSONObject lockedExperimentEdit = localDataJSON.getJSONObject("lockedExperiment"); JSONArray responseArray; @@ -140,7 +145,16 @@ public class SurveyResponseActivity extends AppCompatActivity { responseArray = lockedExperimentEdit.getJSONArray("UserData"); } - responseArray.put(todaysResponse); + boolean replaced = false; + + for(int i = 0; i < responseArray.length(); i++){ + if(sdf.format(today).equals(responseArray.getJSONObject(i).getString("Date"))){ + responseArray.remove(i); + responseArray.put(i, todaysResponse); + replaced = true; + } + } + if(!replaced) responseArray.put(todaysResponse); lockedExperimentEdit.put("UserData", responseArray); localDataJSON.put("lockedExperiment", lockedExperimentEdit); diff --git a/app/src/main/res/layout/activity_new_box.xml b/app/src/main/res/layout/activity_new_box.xml index 3f1f3f7b15c7c6b48caa9d235c8191dc5ed63287..4cf9b674e116d4d5632ef5b6ffeaddff3cc0afb1 100644 --- a/app/src/main/res/layout/activity_new_box.xml +++ b/app/src/main/res/layout/activity_new_box.xml @@ -4,7 +4,7 @@ xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" - tools:context=".NewBox"> + tools:context=".NewBoxActivity"> <com.google.android.material.appbar.AppBarLayout android:layout_width="match_parent" diff --git a/app/src/main/res/layout/content_new_box.xml b/app/src/main/res/layout/content_new_box.xml index 91b9c2adfc13f8a5fb0317ce2c251591579f008b..68d23e1d61863693e33e25c23b5b0b6fcb18617f 100644 --- a/app/src/main/res/layout/content_new_box.xml +++ b/app/src/main/res/layout/content_new_box.xml @@ -8,7 +8,7 @@ android:layout_marginTop="32dp" android:orientation="vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior" - tools:context=".NewBox" + tools:context=".NewBoxActivity" tools:showIn="@layout/activity_new_box"> <TextView @@ -102,7 +102,6 @@ android:ems="10" android:hint="@string/NewBoxBoxTitleHint" android:inputType="textPersonName" - android:text="@string/GenericTitleEditText" tools:ignore="Autofill" /> <EditText @@ -113,7 +112,6 @@ android:ems="10" android:hint="@string/NewBoxBlurbHint" android:inputType="textPersonName" - android:text="@string/GenericEditTextDescription" tools:ignore="Autofill" /> <EditText @@ -124,7 +122,6 @@ android:ems="10" android:hint="@string/GenericEditTextDescription" android:inputType="textPersonName" - android:text="@string/NewBoxEditTextLongerDescription" tools:ignore="Autofill" /> <EditText @@ -135,7 +132,6 @@ android:ems="10" android:hint="@string/NewBoxEditTextWarningHint" android:inputType="textPersonName" - android:text="@string/NewBoxWarningEditText" tools:ignore="Autofill" /> <ImageView diff --git a/app/src/main/res/raw/shop.json b/app/src/main/res/raw/shop.json index 00a348a28e8abf8e45584af4a54fa260ac1e1134..0dd72d33ebb546b2d2ab9d6e76d10b44ac9209f6 100644 --- a/app/src/main/res/raw/shop.json +++ b/app/src/main/res/raw/shop.json @@ -4,5 +4,22 @@ "Blurb": "A salt shaker with an included camera to capture images of food", "Description": "A salt shaker with the capability to take an image of your food without you thinking. Perfect for boxes concerning eating, and could enhance the quality of data collected.", "Price": 14.99, - "Locked": true -}] \ No newline at end of file + "Available": false +}, + { + "Title": "Mug with microphone", + "Image": null, + "Blurb": "A mug with a hidden microphone to analyse data ", + "Description": "A mug with a hidden microphone to capture conversations, this allows data analysis on the quality of conversations. The audio will be processed and then deleted, to keep privacy on the data.", + "Price": 19.99, + "Available": false + }, + { + "Title": "Third example", + "Image": null, + "Blurb": "This is just another example", + "Description": "", + "Price": 0.99, + "Available": false + } +] \ No newline at end of file diff --git a/app/src/main/res/values/idValues.xml b/app/src/main/res/values/idValues.xml deleted file mode 100644 index d781ec5f1e5a72f34217ca9664b3cff376368b17..0000000000000000000000000000000000000000 --- a/app/src/main/res/values/idValues.xml +++ /dev/null @@ -1,4 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<resources> - -</resources> diff --git a/build.gradle b/build.gradle index ff1b8a87321d82e5fe76add2c14c5c71d5660697..2b22439a39284c57fa0e490143d3e858d0a41535 100644 --- a/build.gradle +++ b/build.gradle @@ -7,7 +7,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.6.2' + classpath 'com.android.tools.build:gradle:3.6.3' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files diff --git a/designs/saltshaker.png b/designs/saltshaker.png new file mode 100644 index 0000000000000000000000000000000000000000..585e6d07467a4f5e1cdfb677cd340cb63a2dad10 Binary files /dev/null and b/designs/saltshaker.png differ diff --git a/planning/Bill of Materials.xlsx b/planning/Bill of Materials.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..45924f0f278ca80543410db26289b4d93c86b22c Binary files /dev/null and b/planning/Bill of Materials.xlsx differ diff --git a/planning/Daily progress.xlsx b/planning/Daily progress.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..c1f0936361fe51b227e3806c3320f78e2f765cfa Binary files /dev/null and b/planning/Daily progress.xlsx differ diff --git a/planning/Gantt.xlsx b/planning/Gantt.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..dd9a7ddab57224c9aa17428966e96844f2c1fbe3 Binary files /dev/null and b/planning/Gantt.xlsx differ diff --git a/planning/Logbook.pdf b/planning/Logbook.pdf new file mode 100644 index 0000000000000000000000000000000000000000..d702f6d17235351f259fe061f50b91c03e22cf0a Binary files /dev/null and b/planning/Logbook.pdf differ diff --git a/planning/Risk analysis.xlsx b/planning/Risk analysis.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..f4401421b43d645e8f7caada1a46636bb545abff Binary files /dev/null and b/planning/Risk analysis.xlsx differ diff --git a/reports/final/Project Report Body.docx b/reports/final/Project Report Body.docx new file mode 100644 index 0000000000000000000000000000000000000000..6c65e49e7f204ebde23d10809c0bc754d6a58a83 Binary files /dev/null and b/reports/final/Project Report Body.docx differ diff --git a/reports/final/Project Report Body.pdf b/reports/final/Project Report Body.pdf new file mode 100644 index 0000000000000000000000000000000000000000..38d53b74512755c8a816a568a03809beef82ba0d Binary files /dev/null and b/reports/final/Project Report Body.pdf differ diff --git a/reports/final/Project Report.docx b/reports/final/Project Report.docx new file mode 100644 index 0000000000000000000000000000000000000000..6c65e49e7f204ebde23d10809c0bc754d6a58a83 Binary files /dev/null and b/reports/final/Project Report.docx differ diff --git a/reports/final/Project Report.pdf b/reports/final/Project Report.pdf new file mode 100644 index 0000000000000000000000000000000000000000..b1fdd996d23aae724c408051e367afef49fc69dc Binary files /dev/null and b/reports/final/Project Report.pdf differ diff --git a/reports/progress/Progress Report Body.docx b/reports/progress/Progress Report Body.docx new file mode 100644 index 0000000000000000000000000000000000000000..2b5d3d406a4c039d691bfd7964ccc4d5cbf6c065 Binary files /dev/null and b/reports/progress/Progress Report Body.docx differ diff --git a/reports/progress/Progress Report.docx b/reports/progress/Progress Report.docx new file mode 100644 index 0000000000000000000000000000000000000000..acccb1f5b7cfe6de09be7f8e592b5ca2ea3cae97 Binary files /dev/null and b/reports/progress/Progress Report.docx differ diff --git a/reports/progress/Progress Report.pdf b/reports/progress/Progress Report.pdf new file mode 100644 index 0000000000000000000000000000000000000000..128ee6c1bc53451b7a0903a3612c46e8657623da Binary files /dev/null and b/reports/progress/Progress Report.pdf differ diff --git a/reports/progress/ShorterReportBody.pdf b/reports/progress/ShorterReportBody.pdf new file mode 100644 index 0000000000000000000000000000000000000000..a3bb3c842f63887eae2314953ec15adb116a944c Binary files /dev/null and b/reports/progress/ShorterReportBody.pdf differ diff --git a/reports/project brief/Project Brief.docx b/reports/project brief/Project Brief.docx new file mode 100644 index 0000000000000000000000000000000000000000..22c822da06e4affb00f19d7e87034a4364103357 Binary files /dev/null and b/reports/project brief/Project Brief.docx differ