diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml index 7b570b3fbc548269d856ca362696c98c894cc676..a2a71aefe78f4b9748b24cd5e3d6130f48bbf6a2 100644 --- a/.idea/inspectionProfiles/Project_Default.xml +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -6,5 +6,6 @@ <option name="DONT_REPORT_TRUE_ASSERT_STATEMENTS" value="false" /> </inspection_tool> <inspection_tool class="DanglingJavadoc" enabled="false" level="WARNING" enabled_by_default="false" /> + <inspection_tool class="RawUseOfParameterizedType" enabled="false" level="WARNING" enabled_by_default="false" /> </profile> </component> \ No newline at end of file diff --git a/_supplementary_files/internship/database.png b/_supplementary_files/internship/database.png new file mode 100644 index 0000000000000000000000000000000000000000..f3f6c00c8bc5acdf309f48225a21f10d83178062 Binary files /dev/null and b/_supplementary_files/internship/database.png differ diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index c0e03bfab784bc12b81043a2d7a85ec40cc77f29..b1af992527b06a6145b7fbcbd432605a3c99d1af 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -16,7 +16,10 @@ android:supportsRtl="true" android:theme="@style/Theme.AppCompat.Light.NoActionBar" android:screenOrientation="portrait" - tools:ignore="GoogleAppIndexingWarning"> + tools:ignore="GoogleAppIndexingWarning,UnusedAttribute" + android:usesCleartextTraffic="true" + android:networkSecurityConfig="@xml/network_security_config" + android:fullBackupContent="true"> <activity android:name=".MainActivity" android:screenOrientation="portrait" diff --git a/app/src/main/java/com/yearthreeproject/xbframework/ExperimentActivity.java b/app/src/main/java/com/yearthreeproject/xbframework/ExperimentActivity.java index f16d1a3a0ed543f9b79d5d4c26df889c2c4b878d..a472e8f8d791253481f8050bbb680a91889033f4 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/ExperimentActivity.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/ExperimentActivity.java @@ -187,7 +187,7 @@ public class ExperimentActivity extends AppCompatActivity { .optJSONArray("experiments") .optJSONArray(finalButtonIndex - finalOffset).getJSONObject(0) .optJSONObject("_id").optString("$oid"); - editCurrentExperimentJSON.put("id", new JSONObject().put("$oid", experiment_id)); + editCurrentExperimentJSON.put("_id", new JSONObject().put("$oid", experiment_id)); Calendar calendar = Calendar.getInstance(); diff --git a/app/src/main/java/com/yearthreeproject/xbframework/MainActivity.java b/app/src/main/java/com/yearthreeproject/xbframework/MainActivity.java index 58bd88c599d4ca367b8db9ae822eef47a9132c93..c6b5975003ccbe65f5e042e6b64b15a7ea9d8434 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/MainActivity.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/MainActivity.java @@ -240,8 +240,7 @@ public class MainActivity extends AppCompatActivity { JSONObject localUserJson = new JSONObject(ProjectMacros.readFile(MainActivity.this, "localUserData.json")); JSONObject userCurrentExperimentJson = localUserJson.optJSONObject("current_experiment"); - JSONObject currentExperimentJson = userCurrentExperimentJson.optJSONArray("experiment").getJSONObject(0); - d("current", currentExperimentJson.toString()); + JSONObject currentExperimentJson = userCurrentExperimentJson.optJSONArray("experiment").optJSONObject(0); if (!currentExperimentJson.optBoolean("release_time_lock", false)) { startActivity(new Intent(MainActivity.this, SurveyResponseActivity.class)); } else if (ProjectMacros.compareTimes(dateToday, currentExperimentJson.optString("survey_start")) @@ -278,7 +277,7 @@ public class MainActivity extends AppCompatActivity { } currentExperimentJson.put("locked", false); - currentExperimentJson.put("id", JSONObject.NULL); + currentExperimentJson.put("_id", JSONObject.NULL); currentExperimentJson.put("date_until", JSONObject.NULL); currentExperimentJson.remove("experiment"); @@ -294,7 +293,7 @@ public class MainActivity extends AppCompatActivity { Document currentExperimentDoc = (Document) userDoc.get("current_experiment"); currentExperimentDoc .append("locked", false) - .append("id", null) + .append("_id", null) .append("date_until", null) .remove("experiment"); userDoc.append("current_experiment", currentExperimentDoc); diff --git a/app/src/main/java/com/yearthreeproject/xbframework/ProgressActivity.java b/app/src/main/java/com/yearthreeproject/xbframework/ProgressActivity.java index 6a9f4ee4689592c872aa170452372484716c0d6d..417107abcc2b37260e2479b16d6c6abec1c6cbdb 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/ProgressActivity.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/ProgressActivity.java @@ -172,17 +172,20 @@ public class ProgressActivity extends AppCompatActivity { // Need set up completions to be shown in the graphs if(resultsExist){ // If there is only archive this will be the latest ran - d(TAG, "initialiseGlobalVariables: " + resultsData.getJSONArray(resultsData.length()-1)); - latestResultsExperimentId = resultsData.getJSONArray(resultsData.length()-1).getJSONObject(0).getString("experiment"); - latestResultsEndDate = resultsData.getJSONArray(resultsData.length()-1).getJSONObject(0).getJSONObject("end_date").getString("$date"); - latestExperimentDate = resultsData.getJSONArray(resultsData.length()-1).getJSONObject(0).getJSONObject("date").getString("$date"); + d(TAG, "initialiseGlobalVariables: " + resultsData.getJSONObject(resultsData.length()-1)); + latestResultsExperimentId = resultsData.getJSONObject(resultsData.length()-1).getString("experiment"); + latestResultsEndDate = resultsData.getJSONObject(resultsData.length()-1).getJSONObject("end_date").getString("$date"); + latestExperimentDate = resultsData.getJSONObject(resultsData.length()-1).getJSONObject("date").getString("$date"); dataSeries = arrayLoopForSelectedDateForData(resultsData, new ArrayList<>(), latestResultsExperimentId, latestExperimentDate); } if(completionsExist){ // If there is also currentExperiment this will run latest, making this the highest selected graph - latestResultsExperimentId = localUserJson.getJSONObject("current_experiment").getJSONArray("experiment").getJSONObject(0).getString("name"); - latestResultsEndDate = completionsData.getJSONArray(completionsData.length()-1).getJSONObject(0).getJSONObject("end_date").getString("$date"); - latestExperimentDate = completionsData.getJSONArray(completionsData.length()-1).getJSONObject(0).getJSONObject("date").getString("$date"); - dataSeries = arrayLoopForSelectedDateForData(completionsData, new ArrayList<>(), latestResultsExperimentId, latestResultsEndDate); + d(TAG, "initialiseGlobalVariables: resultExperiment " + completionsData.getJSONObject(completionsData.length()-1)); + if(!completionsData.getJSONObject(completionsData.length() - 1).equals(new JSONArray())){ + latestResultsExperimentId = completionsData.getJSONObject(completionsData.length()-1).getString("experiment"); + latestResultsEndDate = completionsData.getJSONObject(completionsData.length()-1).getJSONObject("end_date").getString("$date"); + latestExperimentDate = completionsData.getJSONObject(completionsData.length()-1).getJSONObject("date").getString("$date"); + dataSeries = arrayLoopForSelectedDateForData(completionsData, new ArrayList<>(), latestResultsExperimentId, latestResultsEndDate); + } } initialiseGraphGUI(dataSeries); } @@ -377,7 +380,7 @@ public class ProgressActivity extends AppCompatActivity { .append("entry", input.getText().toString()) .append("date", today) .append("end_date", endDate) - .append("experiment_name", localUserJson.getJSONObject("current_experiment").getJSONArray("experiment").getJSONObject(0).optString("name", "None")); + .append("experiment_name", localUserJson.getJSONObject("current_experiment").getJSONObject("experiment").optString("name", "None")); journalEntriesOut.put(new JSONObject(tempObject.toJson())); } else { journalEntriesOut.put(journalArray.getJSONObject(i)); @@ -391,20 +394,20 @@ public class ProgressActivity extends AppCompatActivity { .append("entry", input.getText().toString()) .append("date", today) .append("end_date", endDate) - .append("experiment_name", localUserJson.getJSONObject("current_experiment").getJSONArray("experiment").getJSONObject(0).optString("name", "None")); + .append("experiment_name", localUserJson.getJSONObject("current_experiment").getJSONObject("experiment").optString("name", "None")); journalEntriesOut.put(new JSONObject(tempObject.toJson())); } - journalCalendarView.addEvent(new Event(latestExperimentColor, today.getTime(), localUserJson.getJSONObject("current_experiment").getJSONArray("experiment").getJSONObject(0).optString("name", "No Experiment"))); + journalCalendarView.addEvent(new Event(latestExperimentColor, today.getTime(), localUserJson.getJSONObject("current_experiment").getJSONObject("experiment").optString("name", "No Experiment"))); if (sdf.format(journalSelectedDate).equals(sdf.format(today))) { - journalSelectedTitleTextView.setText(Html.fromHtml(localUserJson.getJSONObject("current_experiment").getJSONArray("experiment").getJSONObject(0).optString("name", "None") + " (" + sdf.format(today) + "):")); + journalSelectedTitleTextView.setText(Html.fromHtml(localUserJson.getJSONObject("current_experiment").getJSONObject("experiment").optString("name", "None") + " (" + sdf.format(today) + "):")); journalSelectedEntryTextView.setText(journalCurrentEntryTextView.getText().toString()); } // Replace journal.entries with updated entries - JSONObject journalJSON = localUserJson.getJSONArray("journal").getJSONObject(0); + JSONObject journalJSON = localUserJson.getJSONObject("journal"); journalJSON.put("entries", journalEntriesOut); localUserJson.put("journal", new JSONArray().put(journalJSON)); @@ -691,21 +694,23 @@ public class ProgressActivity extends AppCompatActivity { Date queryDate = new Date(); if(resultsExist){ - String oldExperimentStartDate = resultsData.getJSONArray(0).getJSONObject(0).getJSONObject("end_date").getString("$date"); + String oldExperimentStartDate = resultsData.getJSONObject(0).getJSONObject("end_date").getString("$date"); int experimentCount = 0; for(int i = 0; i < resultsData.length(); i++){ - queryDate.setTime(Long.parseLong(resultsData.getJSONArray(i).getJSONObject(0).getJSONObject("date").getString("$date"))); - if(experimentCount++ == 5 || !(oldExperimentStartDate.equals(resultsData.getJSONArray(i).getJSONObject(0).getJSONObject("date").getString("$date")))){ - markColorIndex++; - experimentCount = 0; - oldExperimentStartDate = resultsData.getJSONArray(i).getJSONObject(0).getJSONObject("end_date").getString("$date"); - } + if(!resultsData.getJSONObject(i).equals(new JSONArray())){ + queryDate.setTime(Long.parseLong(resultsData.getJSONObject(i).getJSONObject("date").getString("$date"))); + if(experimentCount++ == 5 || !(oldExperimentStartDate.equals(resultsData.getJSONObject(i).getJSONObject("date").getString("$date")))){ + markColorIndex++; + experimentCount = 0; + oldExperimentStartDate = resultsData.getJSONObject(i).getJSONObject("end_date").getString("$date"); + } - if(DateUtils.isToday(Long.parseLong(resultsData.getJSONArray(i).getJSONObject(0).getJSONObject("date").getString("$date")))){ // If the date is today - graphCalendarView.setCurrentDayBackgroundColor(Color.parseColor(markColor[markColorIndex%3])); + if(DateUtils.isToday(Long.parseLong(resultsData.getJSONObject(i).getJSONObject("date").getString("$date")))){ // If the date is today + graphCalendarView.setCurrentDayBackgroundColor(Color.parseColor(markColor[markColorIndex%3])); + } + graphCalendarView.addEvent(new Event(Color.parseColor(markColor[markColorIndex%3]), queryDate.getTime(), resultsData.getJSONObject(i).getString("experiment"))); } - graphCalendarView.addEvent(new Event(Color.parseColor(markColor[markColorIndex%3]), queryDate.getTime(), resultsData.getJSONArray(i).getJSONObject(0).getString("experiment"))); } markColorIndex++; @@ -713,11 +718,13 @@ public class ProgressActivity extends AppCompatActivity { if(completionsExist){ for(int i = 0; i < completionsData.length(); i++){ - queryDate.setTime(Long.parseLong(completionsData.getJSONArray(i).getJSONObject(0).getJSONObject("date").getString("$date"))); - if(DateUtils.isToday(Long.parseLong(completionsData.getJSONArray(i).getJSONObject(0).getJSONObject("date").getString("$date")))){ - graphCalendarView.setCurrentDayBackgroundColor(Color.parseColor(markColor[markColorIndex%3])); + if(!completionsData.getJSONObject(i).equals(new JSONArray())){ + queryDate.setTime(Long.parseLong(completionsData.getJSONObject(i).getJSONObject("date").getString("$date"))); + if(DateUtils.isToday(Long.parseLong(completionsData.getJSONObject(i).getJSONObject("date").getString("$date")))){ + graphCalendarView.setCurrentDayBackgroundColor(Color.parseColor(markColor[markColorIndex%3])); + } + graphCalendarView.addEvent(new Event(Color.parseColor(markColor[markColorIndex%3]), queryDate.getTime())); } - graphCalendarView.addEvent(new Event(Color.parseColor(markColor[markColorIndex%3]), queryDate.getTime())); } } @@ -747,7 +754,7 @@ public class ProgressActivity extends AppCompatActivity { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()); dataSeries = arrayLoopForSelectedDateForData(resultsData, new ArrayList<>(), experimentName, sdf.format(tempDate)); } else { - experimentName = localUserJson.getJSONObject("current_experiment").getJSONArray("experiment").getJSONObject(0).getString("name"); + experimentName = localUserJson.getJSONObject("current_experiment").getJSONObject("experiment").getString("name"); dataSeries = loopJSONArrayForPoints(completionsData, new ArrayList<>()); } @@ -845,10 +852,10 @@ public class ProgressActivity extends AppCompatActivity { Calendar cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/YYYY", Locale.getDefault()); - d(TAG, "generateCurrentExperimentGraph: " + (localUserJson.getJSONObject("current_experiment").getJSONArray("experiment").optJSONObject(0) != JSONObject.NULL)); - String currentExperimentText = (localUserJson.getJSONObject("current_experiment").getJSONArray("experiment").optJSONObject(0) != JSONObject.NULL + d(TAG, "generateCurrentExperimentGraph: " + (localUserJson.getJSONObject("current_experiment").optJSONObject("experiment") != JSONObject.NULL)); + String currentExperimentText = (localUserJson.getJSONObject("current_experiment").optJSONObject("experiment") != JSONObject.NULL ? "No experiment" - : localUserJson.getJSONObject("current_experiment").getJSONArray("experiment").optJSONObject(0).optString("name", "No experiment") ) + : localUserJson.getJSONObject("current_experiment").getJSONObject("experiment").optString("name", "No experiment") ) + " (" + sdf.format(cal.getTime()) + "):"; graphCurrentTextView.setText(currentExperimentText); @@ -972,8 +979,10 @@ public class ProgressActivity extends AppCompatActivity { private List<DataPoint> loopJSONArrayForPoints(JSONArray array, List<DataPoint> dataSeries) throws JSONException{ Date date = new Date(); for(int i = 0; i < array.length(); i++){ - date.setTime(Long.parseLong(array.getJSONArray(i).getJSONObject(0).getJSONObject("end_date").getString("$date"))); - dataSeries.add(new DataPoint(date, Double.parseDouble(array.getJSONArray(i).getJSONObject(0).getString("completion_percent")))); + if(!array.getJSONObject(i).equals(new JSONArray())){ + date.setTime(Long.parseLong(array.getJSONObject(i).getJSONObject("end_date").getString("$date"))); + dataSeries.add(new DataPoint(date, Double.parseDouble(array.getJSONObject(i).getString("completion_percent")))); + } } return dataSeries; } @@ -985,9 +994,11 @@ public class ProgressActivity extends AppCompatActivity { } for(int i = 0; i < array.length(); i++){ - queryDate.setTime(Long.parseLong(array.getJSONArray(i).getJSONObject(0).getJSONObject("date").getString("$date"))); - long calNow = queryDate.getTime(); - if (i == 0 || calNow <= lowest) lowest = calNow; + if(!array.getJSONObject(i).equals(new JSONArray())){ + queryDate.setTime(Long.parseLong(array.getJSONObject(i).getJSONObject("date").getString("$date"))); + long calNow = queryDate.getTime(); + if (i == 0 || calNow <= lowest) lowest = calNow; + } } return lowest; } @@ -996,11 +1007,13 @@ public class ProgressActivity extends AppCompatActivity { private List<DataPoint> arrayLoopForSelectedDateForData(JSONArray array, List<DataPoint> dataSeries, String experimentName, String experimentStartDate) throws JSONException { Date queryEntryDate = new Date(); for (int i = 0; i < array.length(); i++) { - JSONObject queryJSON = array.getJSONArray(i).getJSONObject(0); - if (experimentName.equals(queryJSON.getString("experiment"))) { - queryEntryDate.setTime(Long.parseLong(queryJSON.getJSONObject("date").getString("$date"))); - if(experimentStartDate.equals(queryJSON.getJSONObject("end_date").getString("$date"))){ - dataSeries.add(new DataPoint(queryEntryDate, Double.parseDouble(queryJSON.getString("completion_percent")))); + if(!array.getJSONObject(i).equals(new JSONArray())){ + JSONObject queryJSON = array.getJSONObject(i); + if (experimentName.equals(queryJSON.getString("experiment"))) { + queryEntryDate.setTime(Long.parseLong(queryJSON.getJSONObject("date").getString("$date"))); + if(experimentStartDate.equals(queryJSON.getJSONObject("end_date").getString("$date"))){ + dataSeries.add(new DataPoint(queryEntryDate, Double.parseDouble(queryJSON.getString("completion_percent")))); + } } } } @@ -1011,9 +1024,11 @@ public class ProgressActivity extends AppCompatActivity { Date queryDate = new Date(); for (int i = 0; i < array.length(); i++) { - queryDate.setTime(Long.parseLong(array.getJSONArray(i).getJSONObject(0).getJSONObject("end_date").getString("$date"))); - if (queryDate.equals(dateClicked)) { - return queryDate.getTime(); + if(!array.getJSONObject(i).equals(new JSONArray())){ + queryDate.setTime(Long.parseLong(array.getJSONObject(i).getJSONObject("end_date").getString("$date"))); + if (queryDate.equals(dateClicked)) { + return queryDate.getTime(); + } } } return 0; diff --git a/app/src/main/java/com/yearthreeproject/xbframework/SettingsActivity.java b/app/src/main/java/com/yearthreeproject/xbframework/SettingsActivity.java index 819a0ba3cadc6785546a86f3837dc7213a8b8f9a..df8669df89aaedc4cde26195bac8e748f98a82b3 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/SettingsActivity.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/SettingsActivity.java @@ -2,23 +2,39 @@ package com.yearthreeproject.xbframework; import android.graphics.Typeface; import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; import android.widget.LinearLayout; +import android.widget.Spinner; import android.widget.TextView; import androidx.annotation.Nullable; +import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; +import org.bson.Document; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import java.util.ArrayList; import java.util.Iterator; import java.util.Objects; +import io.realm.mongodb.App; +import io.realm.mongodb.mongo.MongoCollection; + public class SettingsActivity extends AppCompatActivity { private static final String TAG = "SettingsActivity"; + private boolean changed = false; + private JSONObject localUserJson; + + private ArrayList<Spinner> spinnerArrayList = new ArrayList<>(); + @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -32,34 +48,123 @@ public class SettingsActivity extends AppCompatActivity { LinearLayout settingsLayout = findViewById(R.id.settings_page); try { - JSONObject localUserJson = new JSONObject(ProjectMacros.readFile(this, "localUserData.json")); + localUserJson = new JSONObject(ProjectMacros.readFile(this, "localUserData.json")); + + Log.d(TAG, "onCreate: localUserJson " + localUserJson); Iterator<String> keys = localUserJson.keys(); + final ArrayList<String[]> answerGroups = new ArrayList<>(); + answerGroups.add(new String[]{"True", "False"}); + answerGroups.add(new String[]{"True", "False"}); + answerGroups.add(getResources().getStringArray(R.array.DemographicsGenderA)); + answerGroups.add(getResources().getStringArray(R.array.DemographicsAgeA)); + answerGroups.add(getResources().getStringArray(R.array.DemographicsRaceA)); + answerGroups.add(getResources().getStringArray(R.array.DemographicsEducationA)); + answerGroups.add(getResources().getStringArray(R.array.DemographicsMaritalA)); + answerGroups.add(getResources().getStringArray(R.array.DemographicsEmploymentA)); + answerGroups.add(getResources().getStringArray(R.array.DemographicsIncomeA)); + + int arrayIndex = 0; + while(keys.hasNext()) { String key = keys.next(); + Log.d(TAG, "onCreate: key " + key); // check its not an object, and is not the user id, then create the layout to show the item if (!(localUserJson.get(key) instanceof JSONObject || localUserJson.get(key) instanceof JSONArray || key.equals("_user_id"))) { LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.HORIZONTAL); + ArrayList<String> spinnerArray = new ArrayList<>(); + for (String s : answerGroups.get(arrayIndex)) { + Log.d(TAG, "onCreate: spinnerAdd " + s); + spinnerArray.add(s); + } + + + Spinner spinner = new Spinner(this); + ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray); + spinner.setAdapter(spinnerArrayAdapter); + int spinnerPosition = spinnerArrayAdapter.getPosition(localUserJson.getString(key)); + spinner.setSelection(spinnerPosition); + + spinnerArrayList.add(spinner); + TextView title = new TextView(this); String keyFormatted = key.substring(0, 1).toUpperCase() + key.substring(1); title.setText(keyFormatted + ": "); title.setTypeface(null, Typeface.BOLD); title.setTextSize(22); - TextView settingValue = new TextView(this); - settingValue.setText(localUserJson.getString(key)); - settingValue.setTextSize(22); - layout.addView(title); - layout.addView(settingValue); + layout.addView(spinner); settingsLayout.addView(layout); + arrayIndex++; + + spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { + try { + if(localUserJson.getString(key) != parent.getItemAtPosition(position)){ + Log.d(TAG, "onItemSelected: item changed to " + parent.getItemAtPosition(position)); + Log.d(TAG, "onItemSelected: changed " + "true"); + changed = true; + } + } catch (JSONException e) { + e.printStackTrace(); + } + } + + @Override + public void onNothingSelected(AdapterView<?> parent) { + + } + }); } } } catch (JSONException e) { e.printStackTrace(); } } + + + @Override + public void onBackPressed() { + Log.d(TAG, "onBackPressed: changed " + changed); + if(changed){ + AlertDialog.Builder al = new AlertDialog.Builder(SettingsActivity.this); + al.setTitle("Are you sure?") + .setMessage("Are you sure you want to leave the page? Your responses will be changed.") + .setPositiveButton("Yes", (dialog, which) -> { + try { + // mongo upload here + Document updateDocument = new Document(); + Iterator<String> keys = localUserJson.keys(); + ArrayList<String> keyNames = new ArrayList<>(); + while (keys.hasNext()) { + String key = keys.next(); + if (!(localUserJson.get(key) instanceof JSONObject || localUserJson.get(key) instanceof JSONArray || key.equals("_user_id"))) + keyNames.add(key); + } + int itemPosition = 0; + for (Spinner spinner : spinnerArrayList) { + if(keyNames.get(itemPosition).equals("anonymous") || keyNames.get(itemPosition).equals("contactable")) updateDocument.append(keyNames.get(itemPosition++), spinner.getSelectedItem() == "True"); + else updateDocument.append(keyNames.get(itemPosition++), spinner.getSelectedItem()); + } + Log.d(TAG, "onBackPressed: updateDocument " + updateDocument); + App realmApp = ((MongoRealmApp) this.getApplication()).getApp(); + MongoCollection userCollection = realmApp.currentUser().getMongoClient("mongodb-atlas").getDatabase("V1").getCollection("Users"); + userCollection.updateOne(new Document("_user_id", realmApp.currentUser().getId()), + new Document("$set", updateDocument)); + finish(); + } catch (JSONException e){ + e.printStackTrace(); + } + }) + .setNegativeButton("No", null) + .show(); + } else { + finish(); + } + } } diff --git a/app/src/main/java/com/yearthreeproject/xbframework/SurveyResponseActivity.java b/app/src/main/java/com/yearthreeproject/xbframework/SurveyResponseActivity.java index b48e92a069540ddc18f1b9c03b8583dfc1b3eda3..4b6ebca5ace5784273c42499c8c0af64f9db5773 100644 --- a/app/src/main/java/com/yearthreeproject/xbframework/SurveyResponseActivity.java +++ b/app/src/main/java/com/yearthreeproject/xbframework/SurveyResponseActivity.java @@ -36,6 +36,8 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import java.time.LocalDateTime; +import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; @@ -142,7 +144,7 @@ public class SurveyResponseActivity extends AppCompatActivity { if(group){ d(TAG, "onCreate: finalGroupDocumentExperiment " + finalGroupDocument.get("current_experiment")); - experimentDocument = await(experimentCollection.findOne(new Document("_id", finalGroupDocument.get("current_experiment", Document.class).getObjectId("id")))); + experimentDocument = await(experimentCollection.findOne(new Document("_id", finalGroupDocument.get("current_experiment", Document.class).getObjectId("_id")))); experimentJSON = new JSONObject(experimentDocument.toJson()); } else { JSONObject localUserJSON = new JSONObject(ProjectMacros.readFile(this, "localUserData.json")); @@ -242,6 +244,7 @@ public class SurveyResponseActivity extends AppCompatActivity { fab.setOnClickListener(v -> completeSubmission()); } + @SuppressLint("NewApi") @RequiresApi(api = Build.VERSION_CODES.KITKAT) private void completeSubmission() { boolean correctSubmission = true; @@ -268,11 +271,9 @@ public class SurveyResponseActivity extends AppCompatActivity { int upperValue = Integer.parseInt(values[1]); if (queryInt <= upperValue && lowerValue <= queryInt) { - d(TAG, "int completed correctly"); completedResults++; } } else if(queryInt == lowerValue) { - d(TAG, "int completed correctly"); completedResults++; } } @@ -290,19 +291,11 @@ public class SurveyResponseActivity extends AppCompatActivity { Integer.parseInt(lowerTime[0]) <= Integer.parseInt(queryTime[0])){ if(Integer.parseInt(queryTime[0]) == Integer.parseInt(upperTime[0]) && Integer.parseInt(queryTime[1]) <= Integer.parseInt(upperTime[1])){ - // If upper hour is the same - // && if the minutes are below the threshold for upper time, if yes, correct - d(TAG, "date completed correctly"); completedResults++; } else if (Integer.parseInt(lowerTime[0]) == Integer.parseInt(queryTime[0]) && Integer.parseInt(lowerTime[1]) <= Integer.parseInt(queryTime[1])){ - // If lower hour is the same - // && if the minutes are above the threshold for lowest time, if yes, correct - d(TAG, "date completed correctly"); completedResults++; } else { - // If neither are the same, and it fits within the range, minutes are irrelevant - d(TAG, "date completed correctly"); completedResults++; } } @@ -312,7 +305,6 @@ public class SurveyResponseActivity extends AppCompatActivity { if(!completionResponses.get(i).optString("expected").equals("null")){ totalPossibleResults++; if(completionResponses.get(i).optString("response").equals(completionResponses.get(i).optString("expected"))) { - d(TAG, "default completed correctly"); completedResults++; } } @@ -320,28 +312,48 @@ public class SurveyResponseActivity extends AppCompatActivity { } - d(TAG, "completionPercent calculation "+completedResults + "/" + totalPossibleResults); double completionPercent = (completedResults / (double) totalPossibleResults)*100; - d(TAG, "completionPercent " + completionPercent); int perceptionResponseTotal = 0; - for (int i = 0; i < surveyResponses.size(); i++) { - if (surveyResponses.get(i).optString("response").equals("null")) correctSubmission = false; - rawSurveyResults.add(Document.parse(surveyResponses.get(i).toString())); - if("bad".equals(surveyResponses.get(i).optString("agree"))){ - perceptionResponseTotal += (5-surveyResponses.get(i).optInt("response")); + for (int i = 0; i < perceptionResponses.size(); i++) { + if (perceptionResponses.get(i).optString("response").equals("null")) correctSubmission = false; + rawPerceptionResults.add(Document.parse(perceptionResponses.get(i).toString())); + perceptionResponseTotal += perceptionResponses.get(i).optInt("response"); + } + double perceptionResponseAverage = (perceptionResponseTotal / (double) (perceptionResponses.size())); + + int surveyResponseTotal = 0; + for(int i = 0; i < surveyResponses.size(); i++){ + if(surveyResponses.get(i).optString("response").equals("null")) correctSubmission = false; + int currentAddition; + switch(surveyResponses.get(i).optString("response")){ + case "Strongly Disagree": + currentAddition = 1; + break; + case "Disagree": + currentAddition = 2; + break; + case "Impartial": + currentAddition = 3; + break; + case "Agree": + currentAddition = 4; + break; + case "Strongly Agree": + currentAddition = 5; + break; + default: + currentAddition = 0; + correctSubmission = false; + } + if("good".equals(surveyResponses.get(i).optString("agree"))){ + surveyResponseTotal += currentAddition; } else { - perceptionResponseTotal += surveyResponses.get(i).optInt("response"); + surveyResponseTotal += 5-currentAddition; } + rawSurveyResults.add(Document.parse(surveyResponses.get(i).toString())); } - double responseAverage = (perceptionResponseTotal / (double) (surveyResponses.size()+1))*100; - - d(TAG, "completeSubmission: responseAverage " + responseAverage); - - for(int i = 0; i < perceptionResponses.size(); i++){ - if(perceptionResponses.get(i).optString("response").equals("null")) correctSubmission = false; - rawPerceptionResults.add(Document.parse(perceptionResponses.get(i).toString())); - } + double surveyResponseAverage = (surveyResponseTotal / (double) (surveyResponses.size())); if (correctSubmission) { AlertDialog.Builder al = new AlertDialog.Builder(SurveyResponseActivity.this); @@ -356,9 +368,17 @@ public class SurveyResponseActivity extends AppCompatActivity { MongoCollection<Document> perceptionCollection = realmApp.currentUser().getMongoClient("mongodb-atlas").getDatabase("V1").getCollection("Perceptions"); MongoCollection<Document> userCollection = realmApp.currentUser().getMongoClient("mongodb-atlas").getDatabase("V1").getCollection("Users"); + d(TAG, "completeSubmission: experimentJSON " + experimentJSON); Document currentExperiment = Document.parse(experimentJSON.toString()); Date end_date = new Date(); - end_date.setTime(groupDocument.get("current_experiment", Document.class).getDate("date_until").getTime()); + + if(groupDocument != null){ + String ISODate = groupDocument.get("current_experiment", Document.class).getString("date_until").replace("date_until", "").replace("Z", ""); + @SuppressLint({"NewApi", "LocalSuppress"}) LocalDateTime localDateTime = LocalDateTime.parse(ISODate); + end_date.setTime(localDateTime.toEpochSecond(ZoneOffset.ofTotalSeconds(0))); + } + else + end_date.setTime(Long.parseLong(localUserJson.getJSONObject("current_experiment").getJSONObject("date_until").getString("$date"))); Document responsesDocument = null; Document completionsDocument = null; @@ -367,18 +387,21 @@ public class SurveyResponseActivity extends AppCompatActivity { if(rawSurveyResults.size() > 0){ Document queryDocument = new Document("_user_id", realmApp.currentUser().getId()); queryDocument.append("date", today); - if(groupDocument != null){ - queryDocument.append("group", groupDocument.getObjectId("_id")); - } else { - queryDocument.append("group", new Document("$eq", null)); - } Document responseDocument = new Document("_user_id", realmApp.currentUser().getId()) .append("date", today) .append("end_date", end_date) - .append("experiment", currentExperiment.getObjectId("id")) + .append("experiment", currentExperiment.getObjectId("_id")) .append("responses", rawSurveyResults) - .append("group", groupDocument.getObjectId("_id")); + .append("survey_average", surveyResponseAverage); + + if(groupDocument != null){ + queryDocument.append("group", groupDocument.getObjectId("_id")); + responseDocument.append("group", groupDocument.getObjectId("_id")); + } else { + queryDocument.append("group", new Document("$eq", null)); + responseDocument.append("group", null); + } responsesDocument = await(responseCollection.findOneAndUpdate(queryDocument, responseDocument, @@ -389,19 +412,21 @@ public class SurveyResponseActivity extends AppCompatActivity { if(rawCompletionResults.size() > 0){ Document queryDocument = new Document("_user_id", realmApp.currentUser().getId()); queryDocument.append("date", today); - if(groupDocument != null){ - queryDocument.append("group", groupDocument.getObjectId("_id")); - } else { - queryDocument.append("group", new Document("$eq", null)); - } Document completionDocument = new Document("_user_id", realmApp.currentUser().getId()) .append("date", today) .append("end_date", end_date) - .append("experiment", currentExperiment.getObjectId("id")) + .append("experiment", currentExperiment.getObjectId("_id")) .append("responses", rawCompletionResults) - .append("completion_percent", (int) completionPercent) - .append("group", groupDocument.getObjectId("_id")); + .append("completion_percent", completionPercent); + + if(groupDocument != null){ + queryDocument.append("group", groupDocument.getObjectId("_id")); + completionDocument.append("group", groupDocument.getObjectId("_id")); + } else { + queryDocument.append("group", new Document("$eq", null)); + completionDocument.append("group", null); + } completionsDocument = await(completionCollection.findOneAndUpdate(queryDocument, completionDocument, @@ -413,18 +438,21 @@ public class SurveyResponseActivity extends AppCompatActivity { if(rawPerceptionResults.size() > 0){ Document queryDocument = new Document("_user_id", realmApp.currentUser().getId()); queryDocument.append("date", today); - if(groupDocument != null){ - queryDocument.append("group", groupDocument.getObjectId("_id")); - } else { - queryDocument.append("group", new Document("$eq", null)); - } Document perceptionDocument = new Document("_user_id", realmApp.currentUser().getId()) .append("date", today) .append("end_date", end_date) - .append("experiment", currentExperiment.getObjectId("id")) + .append("experiment", currentExperiment.getObjectId("_id")) .append("responses", rawPerceptionResults) - .append("group", groupDocument.getObjectId("_id")); + .append("survey_average", perceptionResponseAverage); + + if(groupDocument != null){ + queryDocument.append("group", groupDocument.getObjectId("_id")); + perceptionDocument.append("group", groupDocument.getObjectId("_id")); + } else { + queryDocument.append("group", new Document("$eq", null)); + perceptionDocument.append("group", null); + } perceptionsDocument = await(perceptionCollection.findOneAndUpdate(queryDocument, perceptionDocument, @@ -432,31 +460,31 @@ public class SurveyResponseActivity extends AppCompatActivity { d(TAG, "completeSubmission: perceptionsDocument " + perceptionsDocument); } - Document userDocument = new Document(); Document queryDocument = new Document("_user_id", realmApp.currentUser().getId()); + Document userDocument = await(userCollection.findOne(queryDocument)); - if (groupDocument != null) queryDocument.put("group", groupDocument.getObjectId("_id")); if (completionsDocument != null) { - userDocument.put("$addToSet", new Document("experiment_completions", completionsDocument.getObjectId("_id"))); - d(TAG, "completeSubmission: userDocument " + userDocument); - await(userCollection.updateOne(queryDocument, userDocument)); + ArrayList experimentCompletions = userDocument.get("experiment_completions", ArrayList.class); + if(!experimentCompletions.contains(completionsDocument.getObjectId("_id"))) experimentCompletions.add(completionsDocument.getObjectId("_id")); + userDocument.put("experiment_completions", experimentCompletions); } if (responsesDocument != null) { - userDocument.put("$addToSet", new Document("results", responsesDocument.getObjectId("_id"))); - d(TAG, "completeSubmission: userDocument " + userDocument); - await(userCollection.updateOne(queryDocument, userDocument)); + ArrayList results = userDocument.get("results", ArrayList.class); + if(!results.contains(responsesDocument.getObjectId("_id"))) results.add(responsesDocument.getObjectId("_id")); + userDocument.put("results", results); } if (perceptionsDocument != null) { - userDocument.put("$addToSet", new Document("perceptions", perceptionsDocument.getObjectId("_id"))); - d(TAG, "completeSubmission: userDocument " + userDocument); - await(userCollection.updateOne(queryDocument, userDocument)); + ArrayList perceptions = userDocument.get("perceptions", ArrayList.class); + if(!perceptions.contains(perceptionsDocument.getObjectId("_id"))) perceptions.add(perceptionsDocument.getObjectId("_id")); + userDocument.put("perceptions", perceptions); } + await(userCollection.updateOne(queryDocument, userDocument)); + d(TAG, "completeSubmission: userUpdated apparently"); finish(); } catch (JSONException| InterruptedException | ExecutionException e) { e.printStackTrace(); } }).start(); - //finish(); }).setNegativeButton("No", null) .show(); } else { @@ -798,9 +826,6 @@ public class SurveyResponseActivity extends AppCompatActivity { case 2: response = -1; break; - case 3: - response = 0; - break; case 4: response = 1; break; diff --git a/app/src/main/res/xml/backup_descriptor.xml b/app/src/main/res/xml/backup_descriptor.xml new file mode 100644 index 0000000000000000000000000000000000000000..c95b36ce5717a47b35dd7de3ed0259712d8f25cc --- /dev/null +++ b/app/src/main/res/xml/backup_descriptor.xml @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="utf-8"?> +<full-backup-content> + <!-- TODO Remove the following "exclude" elements to make them a part of the auto backup --> + <!-- Exclude the shared preferences file that contains the GCM registrationId --> + <exclude + domain="sharedpref" + path="com.yearthreeproject.xbframework.PREFERENCE_FILE_KEY.xml" /> +</full-backup-content> diff --git a/app/src/main/res/xml/network_security_config.xml b/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 0000000000000000000000000000000000000000..b9325155e6440d745afe430fa4e97a41ee1bbcba --- /dev/null +++ b/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="utf-8"?> +<network-security-config> + <domain-config cleartextTrafficPermitted="true"> + <domain includeSubdomains="true">your_site_domain.com</domain> + </domain-config> +</network-security-config> \ No newline at end of file