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);
        }
      }
    }
  }
 @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);
 }
  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);
    }
  }
  // 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());
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    PreferenceManager.setDefaultValues(this, R.xml.prefs, false);
    prefs.registerOnSharedPreferenceChangeListener(this);

    // set preferred lang to the default lang
    if ("".equals(prefs.getString(PrefsActivity.PREF_LANGUAGE, ""))) {
      prefs
          .edit()
          .putString(PrefsActivity.PREF_LANGUAGE, Locale.getDefault().getLanguage())
          .apply();
    }

    messageContainer = this.findViewById(R.id.home_messages);
    messageText = (TextView) this.findViewById(R.id.home_message);
    messageButton = (Button) this.findViewById(R.id.message_action_button);

    courses = new ArrayList<>();
    courseListAdapter = new CourseListAdapter(this, courses);
    courseList = (ListView) findViewById(R.id.course_list);
    courseList.setAdapter(courseListAdapter);

    // the alternative of registerForContextMenu(courseList);
    CourseContextMenuCustom courseMenu = new CourseContextMenuCustom(this);
    courseMenu.registerForContextMenu(courseList, this);

    courseList.setOnItemClickListener(
        new OnItemClickListener() {

          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Course selectedCourse = courses.get(position);
            Intent i = new Intent(OppiaMobileActivity.this, CourseIndexActivity.class);
            Bundle tb = new Bundle();
            tb.putSerializable(Course.TAG, selectedCourse);
            i.putExtras(tb);
            startActivity(i);
          }
        });

    llNone = (LinearLayout) this.findViewById(R.id.no_courses);
    initialCourseListPadding = courseList.getPaddingTop();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Initializing Drawer Layout and ActionBarToggle
    final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
    navigationView = (NavigationView) findViewById(R.id.navigation_view);
    ((TextView) navigationView.getHeaderView(0).findViewById(R.id.drawer_user_fullname))
        .setText(SessionManager.getUserDisplayName(this));
    ((TextView) navigationView.getHeaderView(0).findViewById(R.id.drawer_username))
        .setText(SessionManager.getUsername(this));
    navigationView.setNavigationItemSelectedListener(
        new NavigationView.OnNavigationItemSelectedListener() {
          @Override
          public boolean onNavigationItemSelected(MenuItem menuItem) {
            boolean result = onOptionsItemSelected(menuItem);
            menuItem.setChecked(false);
            drawerLayout.closeDrawers();
            return result;
          }
        });

    ActionBarDrawerToggle actionBarDrawerToggle =
        new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close) {
          @Override
          public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we dont want anything to happen
            // so we leave this blank
            super.onDrawerClosed(drawerView);
          }

          @Override
          public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen
            // so we leave this blank
            super.onDrawerOpened(drawerView);
          }
        };

    // Setting the actionbarToggle to drawer layout
    drawerLayout.setDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();
  }
  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();
            }
          });
    }
  }