@Override
 public void onStart() {
   super.onStart();
   DbHelper db = DbHelper.getInstance(this);
   userId = db.getUserId(SessionManager.getUsername(this));
   displayCourses(userId);
 }
 protected void upgradeV54a() {
   DbHelper db = DbHelper.getInstance(ctx);
   long userId = db.getUserId(SessionManager.getUsername(ctx));
   int points = prefs.getInt(UpgradeManagerTask.PREF_POINTS, 0);
   int badges = prefs.getInt(UpgradeManagerTask.PREF_BADGES, 0);
   Log.d(TAG, "points: " + points);
   db.updateUserPoints(userId, points);
   db.updateUserBadges(userId, badges);
 }
 /* go through and add html content to tables
  */
 protected void upgradeV43() {
   SearchUtils.reindexAll(ctx);
   prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
   User user = new User();
   user.setUsername(SessionManager.getUsername(ctx));
   user.setApiKey(prefs.getString(UpgradeManagerTask.PREF_API_KEY, ""));
   DbHelper db = DbHelper.getInstance(ctx);
   long userId = db.addOrUpdateUser(user);
   db.updateV43(userId);
 }
  @Override
  protected Payload doInBackground(Payload... params) {
    Payload payload = new Payload();
    payload.setResult(false);
    String csvPath =
        Storage.getStorageLocationRoot(ctx) + File.separator + SessionManager.ACCOUNTS_CSV_FILENAME;
    File csvAccounts = new File(csvPath);

    if (csvAccounts.exists()) {
      BufferedReader reader = null;
      try {
        String line;
        reader = new BufferedReader(new FileReader(csvAccounts));
        DbHelper db = DbHelper.getInstance(ctx);
        int usersAdded = 0;
        while ((line = reader.readLine()) != null) {
          String[] rowData = line.split(CSV_SEPARATOR);

          if (rowData.length < CSV_COLUMNS) {
            Log.d(TAG, "Bad csv line, ignoring: " + line);
            continue;
          }
          User csvUser = new User();
          csvUser.setUsername(rowData[CSV_USERNAME_COLUMN]);
          csvUser.setPasswordEncrypted(rowData[CSV_PASSWORD_COLUMN]);
          csvUser.setApiKey(rowData[CSV_APIKEY_COLUMN]);

          db.addOrUpdateUser(csvUser);
          usersAdded++;
        }

        if (usersAdded > 0) {
          payload.setResult(true);
          payload.setResultResponse(
              ctx.getString(R.string.info_startup_preloaded_accounts, usersAdded));
        }
        Log.d(TAG, usersAdded + " users added");
      } catch (IOException ex) {
        Mint.logException(ex);
        ex.printStackTrace();
        payload.setResult(true);
        payload.setResultResponse(ctx.getString(R.string.error_preloading_accounts));
      } finally {
        try {
          if (reader != null) reader.close();
          boolean deleted = csvAccounts.delete();
          Log.d(TAG, "CSV file " + (deleted ? "" : "not ") + "deleted");
        } catch (IOException e) {
          Mint.logException(e);
        }
      }
    }

    return payload;
  }
  private void updateReminders() {
    if (prefs.getBoolean(PrefsActivity.PREF_SHOW_SCHEDULE_REMINDERS, false)) {
      DbHelper db = DbHelper.getInstance(OppiaMobileActivity.this);
      int max = Integer.valueOf(prefs.getString(PrefsActivity.PREF_NO_SCHEDULE_REMINDERS, "2"));
      long userId = db.getUserId(SessionManager.getUsername(this));
      ArrayList<Activity> activities = db.getActivitiesDue(max, userId);

      this.drawReminders(activities);
    } else {
      LinearLayout ll = (LinearLayout) findViewById(R.id.schedule_reminders);
      ll.setVisibility(View.GONE);
    }
  }
 public void onBackPressed() {
   end_time = System.currentTimeMillis();
   System.out.println("Start: " + start_time.toString() + "  " + "End: " + end_time.toString());
   dbh.insertCCHLog(
       "Point of Care", "ANC Acute Emergencies", start_time.toString(), end_time.toString());
   finish();
 }
 public void onBackPressed() {
   end_time = System.currentTimeMillis();
   dbh.insertCCHLog(
       "Point of Care",
       "PNC Mother Diagnostic: Managing Danger Signs",
       start_time.toString(),
       end_time.toString());
   finish();
 }
  /* rescans all the installed courses and reinstalls them, to ensure that
   * the new titles etc are picked up
   */
  protected void upgradeV17() {
    File dir = new File(Storage.getCoursesPath(ctx));
    String[] children = dir.list();
    if (children != null) {
      for (String course : children) {
        publishProgress("checking: " + course);
        String courseXMLPath = "";
        String courseScheduleXMLPath = "";
        String courseTrackerXMLPath = "";
        // check that it's unzipped etc correctly
        try {
          courseXMLPath =
              dir + File.separator + course + File.separator + MobileLearning.COURSE_XML;
          courseScheduleXMLPath =
              dir + File.separator + course + File.separator + MobileLearning.COURSE_SCHEDULE_XML;
          courseTrackerXMLPath =
              dir + File.separator + course + File.separator + MobileLearning.COURSE_TRACKER_XML;
        } catch (ArrayIndexOutOfBoundsException aioobe) {
          FileUtils.cleanUp(dir, Storage.getDownloadPath(ctx) + course);
          break;
        }

        // check a module.xml file exists and is a readable XML file
        CourseXMLReader cxr;
        CourseScheduleXMLReader csxr;
        CourseTrackerXMLReader ctxr;
        try {
          cxr = new CourseXMLReader(courseXMLPath, 0, ctx);
          csxr = new CourseScheduleXMLReader(courseScheduleXMLPath);
          File trackerXML = new File(courseTrackerXMLPath);
          ctxr = new CourseTrackerXMLReader(trackerXML);
        } catch (InvalidXMLException e) {
          e.printStackTrace();
          break;
        }

        Course c = new Course(prefs.getString(PrefsActivity.PREF_STORAGE_LOCATION, ""));
        c.setVersionId(cxr.getVersionId());
        c.setTitles(cxr.getTitles());
        c.setShortname(course);
        c.setImageFile(course + File.separator + cxr.getCourseImage());
        c.setLangs(cxr.getLangs());
        c.setPriority(cxr.getPriority());

        DbHelper db = DbHelper.getInstance(ctx);
        long courseId = db.addOrUpdateCourse(c);

        if (courseId != -1) {
          db.insertActivities(cxr.getActivities(courseId));
          db.insertTrackers(ctxr.getTrackers(courseId, 0));
        }

        // add schedule
        // put this here so even if the course content isn't updated the schedule will be
        db.insertSchedule(csxr.getSchedule());
        db.updateScheduleVersion(courseId, csxr.getScheduleVersion());
      }
    }
  }
  private void displayCourses(long userId) {

    DbHelper db = DbHelper.getInstance(this);
    courses.clear();
    courses.addAll(db.getCourses(userId));

    LinearLayout llLoading = (LinearLayout) this.findViewById(R.id.loading_courses);
    llLoading.setVisibility(View.GONE);

    if (courses.size() < MobileLearning.DOWNLOAD_COURSES_DISPLAY) {
      displayDownloadSection();
    } else {
      TextView tv = (TextView) this.findViewById(R.id.manage_courses_text);
      tv.setText(R.string.no_courses);
      llNone.setVisibility(View.GONE);
    }

    courseListAdapter.notifyDataSetChanged();
    this.updateReminders();
    this.scanMedia();
  }
  public void loadQuiz() {
    if (this.quiz == null) {
      this.quiz = new Quiz();
      this.quiz.load(
          quizContent,
          prefs.getString(PrefsActivity.PREF_LANGUAGE, Locale.getDefault().getLanguage()));
    }
    if (this.isOnResultsPage) {
      this.showResults();
    } else {
      // determine availability
      if (this.quiz.getAvailability() == Quiz.AVAILABILITY_ALWAYS) {
        this.showQuestion();
      } else if (this.quiz.getAvailability() == Quiz.AVAILABILITY_SECTION) {

        // check to see if all previous section activities have been completed

        DbHelper db = DbHelper.getInstance(getActivity());
        long userId = db.getUserId(SessionManager.getUsername(getActivity()));
        boolean completed = db.isPreviousSectionActivitiesCompleted(course, activity, userId);

        if (completed) {
          this.showQuestion();
        } else {
          ViewGroup vg = (ViewGroup) getView().findViewById(activity.getActId());
          vg.removeAllViews();
          vg.addView(View.inflate(getView().getContext(), R.layout.widget_quiz_unavailable, null));

          TextView tv = (TextView) getView().findViewById(R.id.quiz_unavailable);
          tv.setText(R.string.widget_quiz_unavailable_section);
        }
      } else if (this.quiz.getAvailability() == Quiz.AVAILABILITY_COURSE) {
        // check to see if all previous course activities have been completed
        DbHelper db = DbHelper.getInstance(getActivity());
        long userId = db.getUserId(SessionManager.getUsername(getActivity()));
        boolean completed = db.isPreviousCourseActivitiesCompleted(course, activity, userId);

        if (completed) {
          this.showQuestion();
        } else {
          ViewGroup vg = (ViewGroup) getView().findViewById(activity.getActId());
          vg.removeAllViews();
          vg.addView(View.inflate(getView().getContext(), R.layout.widget_quiz_unavailable, null));

          TextView tv = (TextView) getView().findViewById(R.id.quiz_unavailable);
          tv.setText(R.string.widget_quiz_unavailable_course);
        }
      }
    }
  }
  // update all the current quiz results for the score/maxscore etc
  protected void upgradeV54() {
    DbHelper db = DbHelper.getInstance(ctx);
    ArrayList<QuizAttempt> quizAttempts = db.getAllQuizAttempts();
    long userId = db.getUserId(SessionManager.getUsername(ctx));

    ArrayList<Course> courses = db.getAllCourses();
    ArrayList<v54UpgradeQuizObj> quizzes = new ArrayList<>();

    for (Course c : courses) {
      try {
        CourseXMLReader cxr = new CourseXMLReader(c.getCourseXMLLocation(), c.getCourseId(), ctx);

        ArrayList<Activity> baseActs = cxr.getBaselineActivities();
        for (Activity a : baseActs) {
          if (a.getActType().equalsIgnoreCase("quiz")) {
            String quizContent = a.getContents("en");
            try {
              JSONObject quizJson = new JSONObject(quizContent);
              v54UpgradeQuizObj q = new v54UpgradeQuizObj();
              q.id = quizJson.getInt("id");
              q.digest = quizJson.getJSONObject("props").getString("digest");
              q.threshold = quizJson.getJSONObject("props").getInt("passthreshold");
              quizzes.add(q);
            } catch (JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        }

        // now add the standard activities
        ArrayList<Activity> acts = cxr.getActivities(c.getCourseId());
        for (Activity a : acts) {
          if (a.getActType().equalsIgnoreCase("quiz")) {
            String quizContent = a.getContents("en");
            try {
              JSONObject quizJson = new JSONObject(quizContent);
              v54UpgradeQuizObj q = new v54UpgradeQuizObj();
              q.id = quizJson.getInt("id");
              q.digest = quizJson.getJSONObject("props").getString("digest");
              q.threshold = quizJson.getJSONObject("props").getInt("passthreshold");
              quizzes.add(q);
            } catch (JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        }
      } catch (InvalidXMLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    for (QuizAttempt qa : quizAttempts) {
      // data back to json obj
      try {
        JSONObject jsonData = new JSONObject(qa.getData());
        qa.setMaxscore((float) jsonData.getDouble("maxscore"));
        qa.setScore((float) jsonData.getDouble("score"));

        int quizId = jsonData.getInt("quiz_id");

        v54UpgradeQuizObj currentQuiz = null;

        // find the relevant quiz in quizzes
        for (v54UpgradeQuizObj tmpQuiz : quizzes) {
          if (tmpQuiz.id == quizId) {
            currentQuiz = tmpQuiz;
            break;
          }
        }

        if (currentQuiz == null) {
          Log.d(TAG, "not found");
        } else {
          Log.d(TAG, "Found");
          qa.setActivityDigest(currentQuiz.digest);
          if (qa.getScoreAsPercent() >= currentQuiz.threshold) {
            qa.setPassed(true);
          } else {
            qa.setPassed(false);
          }
        }

        // make the actual updates
        qa.setUserId(userId);
        db.updateQuizAttempt(qa);

      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    ArrayList<QuizAttempt> checkQuizAttempts = db.getAllQuizAttempts();
    for (QuizAttempt qa : checkQuizAttempts) {
      // display current data
      Log.d(TAG, "data: " + qa.getData());
      Log.d(TAG, "digest: " + qa.getActivityDigest());
      Log.d(TAG, "userid: " + qa.getUserId());
      Log.d(TAG, "courseid: " + qa.getCourseId());
      Log.d(TAG, "score: " + qa.getScore());
      Log.d(TAG, "maxscore: " + qa.getMaxscore());
      Log.d(TAG, "passed: " + qa.isPassed());
    }
  }
  public void showResults() {

    // log the activity as complete
    isOnResultsPage = true;
    quiz.mark(prefs.getString(PrefsActivity.PREF_LANGUAGE, Locale.getDefault().getLanguage()));
    // save results ready to send back to the quiz server
    String data = quiz.getResultObject().toString();
    Log.d(TAG, data);

    DbHelper db = DbHelper.getInstance(super.getActivity());
    long userId = db.getUserId(SessionManager.getUsername(getActivity()));

    QuizAttempt qa = new QuizAttempt();
    qa.setCourseId(course.getCourseId());
    qa.setUserId(userId);
    qa.setData(data);

    qa.setActivityDigest(activity.getDigest());
    qa.setScore(quiz.getUserscore());
    qa.setMaxscore(quiz.getMaxscore());
    qa.setPassed(this.getActivityCompleted());
    qa.setSent(false);
    db.insertQuizAttempt(qa);

    // Check if quiz results layout is already loaded
    View quizResultsLayout = getView().findViewById(R.id.widget_quiz_results);
    if (quizResultsLayout == null) {
      // load new layout
      View C = getView().findViewById(R.id.quiz_progress);
      ViewGroup parent = (ViewGroup) C.getParent();
      int index = parent.indexOfChild(C);
      parent.removeView(C);
      C =
          super.getActivity()
              .getLayoutInflater()
              .inflate(R.layout.widget_quiz_results, parent, false);
      parent.addView(C, index);
    }

    TextView title = (TextView) getView().findViewById(R.id.quiz_results_score);
    title.setText(
        super.getActivity().getString(R.string.widget_quiz_results_score, this.getPercent()));

    if (this.isBaseline) {
      TextView baselineExtro = (TextView) getView().findViewById(R.id.quiz_results_baseline);
      baselineExtro.setVisibility(View.VISIBLE);
      baselineExtro.setText(super.getActivity().getString(R.string.widget_quiz_baseline_completed));
    }

    // TODO add TextView here to give overall feedback if it's in the quiz

    // Show the detail of which questions were right/wrong
    if (quiz.getShowFeedback() == Quiz.SHOW_FEEDBACK_ALWAYS
        || quiz.getShowFeedback() == Quiz.SHOW_FEEDBACK_ATEND) {
      ListView questionFeedbackLV = (ListView) getView().findViewById(R.id.quiz_results_feedback);
      ArrayList<QuizFeedback> quizFeedback = new ArrayList<QuizFeedback>();
      List<QuizQuestion> questions = this.quiz.getQuestions();
      for (QuizQuestion q : questions) {
        if (!(q instanceof Description)) {
          QuizFeedback qf = new QuizFeedback();
          qf.setScore(q.getScoreAsPercent());
          qf.setQuestionText(
              q.getTitle(
                  prefs.getString(PrefsActivity.PREF_LANGUAGE, Locale.getDefault().getLanguage())));
          qf.setUserResponse(q.getUserResponses());
          qf.setFeedbackText(
              q.getFeedback(
                  prefs.getString(PrefsActivity.PREF_LANGUAGE, Locale.getDefault().getLanguage())));
          quizFeedback.add(qf);
        }
      }
      QuizFeedbackAdapter qfa = new QuizFeedbackAdapter(super.getActivity(), quizFeedback);
      questionFeedbackLV.setAdapter(qfa);
    }

    // Show restart or continue button
    Button restartBtn = (Button) getView().findViewById(R.id.quiz_results_button);

    if (this.isBaseline) {
      restartBtn.setText(super.getActivity().getString(R.string.widget_quiz_baseline_goto_course));
      restartBtn.setOnClickListener(
          new View.OnClickListener() {
            public void onClick(View v) {
              QuizWidget.this.getActivity().finish();
            }
          });
    } else {
      restartBtn.setText(super.getActivity().getString(R.string.widget_quiz_results_restart));
      restartBtn.setOnClickListener(
          new View.OnClickListener() {
            public void onClick(View v) {
              QuizWidget.this.restart();
            }
          });
    }
  }