private void deleteRepository() {
    MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());
    builder.progress(true, 0);
    builder.content(R.string.deleting_repository);
    deleteRepoDialog = builder.show();
    DeleteRepoClient deleteRepoClient = new DeleteRepoClient(getActivity(), repoInfo);
    deleteRepoClient
        .observable()
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Subscriber<Response>() {
              @Override
              public void onCompleted() {}

              @Override
              public void onError(Throwable e) {
                Toast.makeText(getActivity(), "Repository delete failed", Toast.LENGTH_SHORT)
                    .show();
              }

              @Override
              public void onNext(Response response) {
                if (getActivity() != null) {
                  if (deleteRepoDialog != null) {
                    deleteRepoDialog.dismiss();
                  }
                  getActivity().setResult(Activity.RESULT_CANCELED);
                  getActivity().finish();
                }
              }
            });
  }
Ejemplo n.º 2
0
 public static void showInputDialog(
     Activity context, int title, int hint, String prefillInput, final InputCallback callback) {
   @SuppressLint("InflateParams")
   final View view = context.getLayoutInflater().inflate(R.layout.dialog_input, null);
   MaterialDialog.Builder dialog =
       new MaterialDialog.Builder(context)
           .title(title)
           .positiveText(android.R.string.ok)
           .negativeText(android.R.string.cancel)
           .callback(
               new MaterialDialog.ButtonCallback() {
                 @Override
                 public void onPositive(MaterialDialog dialog) {
                   if (callback != null) {
                     EditText input = (EditText) view.findViewById(R.id.input);
                     callback.onInput(input.getText().toString().trim());
                   }
                 }
               })
           .customView(view, true);
   final EditText input = (EditText) view.findViewById(R.id.input);
   if (hint != 0) input.setHint(hint);
   if (prefillInput != null) input.append(prefillInput);
   MaterialDialog alert = dialog.build();
   alert.setOnDismissListener(
       new DialogInterface.OnDismissListener() {
         @Override
         public void onDismiss(DialogInterface dialog) {
           if (callback instanceof InputCancelCallback)
             ((InputCancelCallback) callback).onCancel();
         }
       });
   alert.show();
 }
Ejemplo n.º 3
0
  @NonNull
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    String text =
        String.format(
            "%s\n\n%s\n\n%s",
            DreamDroid.VERSION_STRING,
            getString(R.string.license),
            getString(R.string.source_code_link));

    MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());
    builder
        .title(R.string.about)
        .content(text)
        .neutralText(R.string.donate)
        .positiveText(R.string.privacy)
        .callback(
            new MaterialDialog.ButtonCallback() {
              @Override
              public void onNeutral(MaterialDialog dialog) {
                ExtendedHashMap skus = ((BaseActivity) getActivity()).getIabItems();
                DonationDialog d = DonationDialog.newInstance(skus);
                ((MultiPaneHandler) getActivity()).showDialogFragment(d, "donate_dialog");
              }

              @Override
              public void onPositive(MaterialDialog dialog) {
                finishDialog(Statics.ACTION_SHOW_PRIVACY_STATEMENT, null);
              }
            });

    MaterialDialog dialog = builder.build();
    Linkify.addLinks(dialog.getContentView(), Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS);
    return dialog;
  }
Ejemplo n.º 4
0
  /**
   * Create a dialog containing (parts of the) change log.
   *
   * @param full If this is {@code true} the full change log is displayed. Otherwise only changes
   *     for versions newer than the last version are displayed.
   * @return A dialog containing the (partial) change log.
   */
  protected Dialog getDialog(boolean full) {
    WebView wv = new WebView(mContext);
    // wv.setBackgroundColor(0); // transparent
    wv.loadDataWithBaseURL(null, getLog(full), "text/html", "UTF-8", null);

    MaterialDialog.Builder builder = new MaterialDialog.Builder(mContext);
    builder
        .title(
            mContext
                .getResources()
                .getString(full ? R.string.changelog_full_title : R.string.changelog_title))
        .customView(wv, false)
        .positiveText(mContext.getResources().getString(R.string.changelog_ok_button))
        .onPositive(
            new MaterialDialog.SingleButtonCallback() {
              @Override
              public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                updateVersionInPreferences();
              }
            })
        .onNegative(
            new MaterialDialog.SingleButtonCallback() {
              @Override
              public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                getFullLogDialog().show();
              }
            });
    if (!full) {
      // Show "More…" button if we're only displaying a partial change log.
      builder.negativeText(R.string.changelog_show_full);
    }

    return builder.build();
  }
Ejemplo n.º 5
0
  @Override
  public void showLoadDialog(String title, String message) {
    MaterialDialog.Builder builder =
        new MaterialDialog.Builder(this)
            .title(title)
            .content(message)
            .positiveText("确定")
            .onPositive(
                new MaterialDialog.SingleButtonCallback() {
                  @Override
                  public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    presenter.updateOrderCargo(unRemoveEt.getText().toString());
                  }
                })
            .negativeText("取消")
            .onNegative(
                new MaterialDialog.SingleButtonCallback() {
                  @Override
                  public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    dialog.dismiss();
                  }
                });

    MaterialDialog dialog = builder.build();
    dialog.show();
  }
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final Resources res = getResources();

    Activity activity = getActivity();
    final MaterialDialog.Builder builder = new MaterialDialog.Builder(activity);

    int type = getArguments().getInt("type");
    if (type == CARD_BROWSER_MY_SEARCHES_TYPE_LIST) {
      mSavedFilters = (HashMap<String, String>) getArguments().getSerializable("savedFilters");
      mSearchesAdapter =
          new MySearchesArrayAdapter(activity, new ArrayList<>(mSavedFilters.keySet()));
      mSearchesAdapter.notifyDataSetChanged(); // so the values are sorted.
      builder
          .title(res.getString(R.string.card_browser_list_my_searches_title))
          .adapter(
              mSearchesAdapter,
              new MaterialDialog.ListCallback() {
                @Override
                public void onSelection(
                    MaterialDialog dialog, View itemView, int which, CharSequence text) {
                  mMySearchesDialogListener.OnSelection(mSearchesAdapter.getItem(which));
                  dialog.dismiss();
                }
              });
    } else if (type == CARD_BROWSER_MY_SEARCHES_TYPE_SAVE) {
      mCurrentSearchTerms = getArguments().getString("currentSearchTerms");
      builder
          .title(getString(R.string.card_browser_list_my_searches_save))
          .positiveText(getString(android.R.string.ok))
          .negativeText(getString(R.string.cancel))
          .input(
              R.string.card_browser_list_my_searches_new_name,
              R.string.empty_string,
              new MaterialDialog.InputCallback() {
                @Override
                public void onInput(MaterialDialog dialog, CharSequence text) {
                  mMySearchesDialogListener.OnSaveSearch(text.toString(), mCurrentSearchTerms);
                }
              });
    }
    MaterialDialog dialog = builder.build();
    if (dialog.getListView() != null) {
      dialog
          .getListView()
          .setDivider(
              new ColorDrawable(ContextCompat.getColor(activity, R.color.material_grey_600)));
      dialog.getListView().setDividerHeight(1);
      // adjust padding to use dp as seen here: http://stackoverflow.com/a/9685690/1332026
      float scale = res.getDisplayMetrics().density;
      int dpAsPixels = (int) (5 * scale + 0.5f);
      dialog.getView().setPadding(dpAsPixels, 0, dpAsPixels, dpAsPixels);
    }

    return dialog;
  }
Ejemplo n.º 7
0
  public void showInstructionDialogBox() {
    MaterialDialog.Builder dialogBuilder =
        new MaterialDialog.Builder(this)
            .title(R.string.instruction)
            .content(R.string.patternDrawInstruction)
            .positiveText(R.string.next)
            .cancelable(false);
    dialogBuilder.show();
    dialogBuilder.callback(
        new MaterialDialog.ButtonCallback() {
          @Override
          public void onPositive(MaterialDialog dialog) {
            Log.d("OK ", "great");
            startTime = new SimpleDateFormat("mmss").format(Calendar.getInstance().getTime());
            showArrows();
            /*
            int[] location5= new int[2];
            int[] locationK= new int[2];
            int[] location6= new int[2];
            int[] locationL= new int[2];
            int location5CenterX, location5CenterY, locationKCenterX , locationKCenterY , location6CenterX , location6CenterY, locationLCenterX, locationLCenterY;
            Button button5 = (Button) findViewById(R.id.pattern_button5);
            Button buttonK = (Button) findViewById(R.id.pattern_buttonK);
            Button button6 = (Button) findViewById(R.id.pattern_button6);
            Button buttonL = (Button) findViewById(R.id.pattern_buttonL);

            button5.getLocationOnScreen(location5);
            location5CenterX =location5[0]+ button5.getWidth()/2;
            location5CenterY =location5[1];

            buttonK.getLocationOnScreen(locationK);
            locationKCenterX =locationK[0]+ buttonK.getWidth()/2;
            locationKCenterY =locationK[1];

            button6.getLocationOnScreen(location6);
            location6CenterX =location6[0]+ button6.getWidth()/2;
            location6CenterY =location6[1];

            buttonL.getLocationOnScreen(locationL);
            locationLCenterX =locationL[0]+ buttonL.getWidth()/2;
            locationLCenterY =locationL[1];

            arrowView = new ArrowView(getApplicationContext(), location5CenterX,location5CenterY,locationKCenterX,locationKCenterY);
            addContentView(arrowView, new ViewGroup.LayoutParams(1000,1000));

            arrowView = new ArrowView(getApplicationContext(), locationKCenterX,locationKCenterY,location6CenterX,location6CenterY);
            addContentView(arrowView, new ViewGroup.LayoutParams(1000,1000));

            arrowView = new ArrowView(getApplicationContext(), location6CenterX,location6CenterY,locationLCenterX,locationLCenterY);
            addContentView(arrowView, new ViewGroup.LayoutParams(1000,1000));
            */

          }
        });
  }
Ejemplo n.º 8
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_parsing_json);

    toolbar = (Toolbar) findViewById(R.id.toolbar_spinner);
    setSupportActionBar(toolbar);
    setTitle("수질정보");

    ArrayAdapter<String> adapter =
        new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, PurificationPlant);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    items = (ArrayList<String>) getIntent().getSerializableExtra("data");
    index = getIntent().getIntExtra("index", 1);

    ph = (TextView) findViewById(R.id.ph);
    tak = (TextView) findViewById(R.id.tak);
    zan = (TextView) findViewById(R.id.zan);
    junsujang = (TextView) findViewById(R.id.jungsujang);

    update = (TextView) findViewById(R.id.dayOfUpdate);

    dialogBuilder = new MaterialDialog.Builder(parsingJson.this);
    dialogBuilder.title("데이터 로드중..").content("잠시만 기다려주세요").progress(true, 0);
    mDialog = dialogBuilder.build();

    spinner = (MaterialSpinner) findViewById(R.id.spinner);
    spinner.setAdapter(adapter);
    spinner.setSelection(index);
    spinner.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
            PurificationPlant_choice = PurificationPlant_code[position];
            data.clear();
            index = position;
            new JsonLoadingTask().execute();
            junsujang.setText(PurificationPlant[index]);
            mDialog.show();
          }

          @Override
          public void onNothingSelected(AdapterView<?> adapterView) {}
        });

    new JsonLoadingTask().execute();
  }
Ejemplo n.º 9
0
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());

    return builder
        .title(getString(R.string.export_title))
        .progress(true, 100)
        .content(getString(R.string.dialog_export_content))
        .negativeText(getString(R.string.dialog_cancel))
        .onNegative(
            new MaterialDialog.SingleButtonCallback() {
              @Override
              public void onClick(
                  @NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
                task.cancel();
              }
            })
        .build();
  }
Ejemplo n.º 10
0
  @Override
  public MaterialDialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mType = getArguments().getInt("dialogType");
    Resources res = getResources();
    MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());
    builder.cancelable(true).title(getTitle());

    boolean sqliteInstalled = false;
    try {
      sqliteInstalled = Runtime.getRuntime().exec("sqlite3 --version").waitFor() == 0;
    } catch (IOException | InterruptedException e) {
      e.printStackTrace();
    }

    switch (mType) {
      case DIALOG_CURSOR_SIZE_LIMIT_EXCEEDED:
      case DIALOG_LOAD_FAILED:
        // Collection failed to load; give user the option of either choosing from repair options,
        // or closing
        // the activity
        return builder
            .cancelable(false)
            .content(getMessage())
            .iconAttr(R.attr.dialogErrorIcon)
            .positiveText(res.getString(R.string.error_handling_options))
            .negativeText(res.getString(R.string.close))
            .callback(
                new MaterialDialog.ButtonCallback() {
                  @Override
                  public void onPositive(MaterialDialog dialog) {
                    ((DeckPicker) getActivity()).showDatabaseErrorDialog(DIALOG_ERROR_HANDLING);
                  }

                  @Override
                  public void onNegative(MaterialDialog dialog) {
                    ((DeckPicker) getActivity()).exit();
                  }
                })
            .show();

      case DIALOG_DB_ERROR:
        // Database Check failed to execute successfully; give user the option of either choosing
        // from repair
        // options, submitting an error report, or closing the activity
        MaterialDialog dialog =
            builder
                .cancelable(false)
                .content(getMessage())
                .iconAttr(R.attr.dialogErrorIcon)
                .positiveText(res.getString(R.string.error_handling_options))
                .negativeText(res.getString(R.string.answering_error_report))
                .neutralText(res.getString(R.string.close))
                .callback(
                    new MaterialDialog.ButtonCallback() {
                      @Override
                      public void onPositive(MaterialDialog dialog) {
                        ((DeckPicker) getActivity()).showDatabaseErrorDialog(DIALOG_ERROR_HANDLING);
                      }

                      @Override
                      public void onNegative(MaterialDialog dialog) {
                        ((DeckPicker) getActivity()).sendErrorReport();
                        dismissAllDialogFragments();
                      }

                      @Override
                      public void onNeutral(MaterialDialog dialog) {
                        ((DeckPicker) getActivity()).exit();
                      }
                    })
                .show();
        dialog
            .getCustomView()
            .findViewById(R.id.buttonDefaultNegative)
            .setEnabled(((DeckPicker) getActivity()).hasErrorFiles());
        return dialog;

      case DIALOG_ERROR_HANDLING:
        // The user has asked to see repair options; allow them to choose one of the repair options
        // or go back
        // to the previous dialog
        ArrayList<String> options = new ArrayList<>();
        ArrayList<Integer> values = new ArrayList<>();
        if (!((AnkiActivity) getActivity()).colIsOpen()) {
          // retry
          options.add(res.getString(R.string.backup_retry_opening));
          values.add(0);
        } else {
          // fix integrity
          options.add(res.getString(R.string.check_db));
          values.add(1);
        }
        // repair db with sqlite
        if (sqliteInstalled) {
          options.add(res.getString(R.string.backup_error_menu_repair));
          values.add(2);
        }
        // // restore from backup
        options.add(res.getString(R.string.backup_restore));
        values.add(3);
        // delete old collection and build new one
        options.add(res.getString(R.string.backup_full_sync_from_server));
        values.add(4);
        // delete old collection and build new one
        options.add(res.getString(R.string.backup_del_collection));
        values.add(5);

        String[] titles = new String[options.size()];
        mRepairValues = new int[options.size()];
        for (int i = 0; i < options.size(); i++) {
          titles[i] = options.get(i);
          mRepairValues[i] = values.get(i);
        }

        dialog =
            builder
                .iconAttr(R.attr.dialogErrorIcon)
                .negativeText(res.getString(R.string.dialog_cancel))
                .items(titles)
                .itemsCallback(
                    new MaterialDialog.ListCallback() {
                      @Override
                      public void onSelection(
                          MaterialDialog materialDialog,
                          View view,
                          int which,
                          CharSequence charSequence) {
                        switch (mRepairValues[which]) {
                          case 0:
                            ((DeckPicker) getActivity()).restartActivity();
                            return;
                          case 1:
                            ((DeckPicker) getActivity())
                                .showDatabaseErrorDialog(DIALOG_CONFIRM_DATABASE_CHECK);
                            return;
                          case 2:
                            ((DeckPicker) getActivity())
                                .showDatabaseErrorDialog(DIALOG_REPAIR_COLLECTION);
                            return;
                          case 3:
                            ((DeckPicker) getActivity())
                                .showDatabaseErrorDialog(DIALOG_RESTORE_BACKUP);
                            return;
                          case 4:
                            ((DeckPicker) getActivity())
                                .showDatabaseErrorDialog(DIALOG_FULL_SYNC_FROM_SERVER);
                            return;
                          case 5:
                            ((DeckPicker) getActivity())
                                .showDatabaseErrorDialog(DIALOG_NEW_COLLECTION);
                        }
                      }
                    })
                .show();
        return dialog;

      case DIALOG_REPAIR_COLLECTION:
        // Allow user to run BackupManager.repairCollection()
        return builder
            .content(getMessage())
            .iconAttr(R.attr.dialogErrorIcon)
            .positiveText(res.getString(R.string.dialog_positive_repair))
            .negativeText(res.getString(R.string.dialog_cancel))
            .callback(
                new MaterialDialog.ButtonCallback() {
                  @Override
                  public void onPositive(MaterialDialog dialog) {
                    ((DeckPicker) getActivity()).repairDeck();
                    dismissAllDialogFragments();
                  }
                })
            .show();

      case DIALOG_RESTORE_BACKUP:
        // Allow user to restore one of the backups
        String path = CollectionHelper.getInstance().getCollectionPath(getActivity());
        File[] files = BackupManager.getBackups(new File(path));
        mBackups = new File[files.length];
        for (int i = 0; i < files.length; i++) {
          mBackups[i] = files[files.length - 1 - i];
        }
        if (mBackups.length == 0) {
          builder
              .title(res.getString(R.string.backup_restore))
              .content(getMessage())
              .positiveText(res.getString(R.string.dialog_ok))
              .callback(
                  new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                      ((DeckPicker) getActivity()).showDatabaseErrorDialog(DIALOG_ERROR_HANDLING);
                    }
                  });
        } else {
          String[] dates = new String[mBackups.length];
          for (int i = 0; i < mBackups.length; i++) {
            dates[i] =
                mBackups[i]
                    .getName()
                    .replaceAll(".*-(\\d{4}-\\d{2}-\\d{2})-(\\d{2})-(\\d{2}).apkg", "$1 ($2:$3 h)");
          }
          builder
              .title(res.getString(R.string.backup_restore_select_title))
              .negativeText(res.getString(R.string.dialog_cancel))
              .callback(
                  new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onNegative(MaterialDialog dialog) {
                      dismissAllDialogFragments();
                    }
                  })
              .items(dates)
              .itemsCallbackSingleChoice(
                  dates.length,
                  new MaterialDialog.ListCallbackSingleChoice() {
                    @Override
                    public boolean onSelection(
                        MaterialDialog materialDialog,
                        View view,
                        int which,
                        CharSequence charSequence) {
                      if (mBackups[which].length() > 0) {
                        // restore the backup if it's valid
                        ((DeckPicker) getActivity()).restoreFromBackup(mBackups[which].getPath());
                        dismissAllDialogFragments();
                      } else {
                        // otherwise show an error dialog
                        new MaterialDialog.Builder(getActivity())
                            .title(R.string.backup_error)
                            .content(R.string.backup_invalid_file_error)
                            .positiveText(R.string.dialog_ok)
                            .build()
                            .show();
                      }
                      return true;
                    }
                  });
        }
        return builder.show();

      case DIALOG_NEW_COLLECTION:
        // Allow user to create a new empty collection
        return builder
            .content(getMessage())
            .positiveText(res.getString(R.string.dialog_positive_create))
            .negativeText(res.getString(R.string.dialog_cancel))
            .callback(
                new MaterialDialog.ButtonCallback() {
                  @Override
                  public void onPositive(MaterialDialog dialog) {
                    CollectionHelper.getInstance().closeCollection(false);
                    String path = CollectionHelper.getCollectionPath(getActivity());
                    if (BackupManager.moveDatabaseToBrokenFolder(path, false)) {
                      ((DeckPicker) getActivity()).restartActivity();
                    } else {
                      ((DeckPicker) getActivity()).showDatabaseErrorDialog(DIALOG_LOAD_FAILED);
                    }
                  }
                })
            .show();

      case DIALOG_CONFIRM_DATABASE_CHECK:
        // Confirmation dialog for database check
        return builder
            .content(getMessage())
            .positiveText(res.getString(R.string.dialog_ok))
            .negativeText(res.getString(R.string.dialog_cancel))
            .callback(
                new MaterialDialog.ButtonCallback() {
                  @Override
                  public void onPositive(MaterialDialog dialog) {
                    ((DeckPicker) getActivity()).integrityCheck();
                    dismissAllDialogFragments();
                  }
                })
            .show();

      case DIALOG_CONFIRM_RESTORE_BACKUP:
        // Confirmation dialog for backup restore
        return builder
            .content(getMessage())
            .positiveText(res.getString(R.string.dialog_continue))
            .negativeText(res.getString(R.string.dialog_cancel))
            .callback(
                new MaterialDialog.ButtonCallback() {
                  @Override
                  public void onPositive(MaterialDialog dialog) {
                    ((DeckPicker) getActivity()).showDatabaseErrorDialog(DIALOG_RESTORE_BACKUP);
                  }
                })
            .show();

      case DIALOG_FULL_SYNC_FROM_SERVER:
        // Allow user to do a full-sync from the server
        return builder
            .content(getMessage())
            .positiveText(res.getString(R.string.dialog_positive_overwrite))
            .negativeText(res.getString(R.string.dialog_cancel))
            .callback(
                new MaterialDialog.ButtonCallback() {
                  @Override
                  public void onPositive(MaterialDialog dialog) {
                    ((DeckPicker) getActivity()).sync("download");
                    dismissAllDialogFragments();
                  }
                })
            .show();

      default:
        return null;
    }
  }
Ejemplo n.º 11
0
  private void showUpdateIntervalTimePreferencesDialog() {
    final Context context = ui.getActivity();

    MaterialDialog.Builder builder = new MaterialDialog.Builder(context);
    builder.title(R.string.pref_autoUpdateIntervallOrTime_title);
    builder.content(R.string.pref_autoUpdateIntervallOrTime_message);
    builder.positiveText(R.string.pref_autoUpdateIntervallOrTime_Interval);
    builder.negativeText(R.string.pref_autoUpdateIntervallOrTime_TimeOfDay);
    builder.neutralText(R.string.pref_autoUpdateIntervallOrTime_Disable);
    builder.onPositive(
        (dialog, which) -> {
          AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
          builder1.setTitle(context.getString(R.string.pref_autoUpdateIntervallOrTime_Interval));
          final String[] values =
              context.getResources().getStringArray(R.array.update_intervall_values);
          final String[] entries = getUpdateIntervalEntries(values);
          long currInterval = UserPreferences.getUpdateInterval();
          int checkedItem = -1;
          if (currInterval > 0) {
            String currIntervalStr = String.valueOf(TimeUnit.MILLISECONDS.toHours(currInterval));
            checkedItem = ArrayUtils.indexOf(values, currIntervalStr);
          }
          builder1.setSingleChoiceItems(
              entries,
              checkedItem,
              (dialog1, which1) -> {
                int hours = Integer.parseInt(values[which1]);
                UserPreferences.setUpdateInterval(hours);
                dialog1.dismiss();
                setUpdateIntervalText();
              });
          builder1.setNegativeButton(context.getString(R.string.cancel_label), null);
          builder1.show();
        });
    builder.onNegative(
        (dialog, which) -> {
          int hourOfDay = 7, minute = 0;
          int[] updateTime = UserPreferences.getUpdateTimeOfDay();
          if (updateTime.length == 2) {
            hourOfDay = updateTime[0];
            minute = updateTime[1];
          }
          TimePickerDialog timePickerDialog =
              new TimePickerDialog(
                  context,
                  (view, selectedHourOfDay, selectedMinute) -> {
                    if (view.getTag() == null) { // onTimeSet() may get called twice!
                      view.setTag("TAGGED");
                      UserPreferences.setUpdateTimeOfDay(selectedHourOfDay, selectedMinute);
                      setUpdateIntervalText();
                    }
                  },
                  hourOfDay,
                  minute,
                  DateFormat.is24HourFormat(context));
          timePickerDialog.setTitle(
              context.getString(R.string.pref_autoUpdateIntervallOrTime_TimeOfDay));
          timePickerDialog.show();
        });
    builder.onNeutral(
        (dialog, which) -> {
          UserPreferences.setUpdateInterval(0);
          setUpdateIntervalText();
        });
    builder.show();
  }
  @Override
  protected void showDialog(Bundle state) {
    List<Integer> indices = new ArrayList<>();
    for (String s : getValues()) {
      int index = findIndexOfValue(s);
      if (index >= 0) indices.add(findIndexOfValue(s));
    }
    MaterialDialog.Builder builder =
        new MaterialDialog.Builder(context)
            .title(getDialogTitle())
            .icon(getDialogIcon())
            .negativeText(getNegativeButtonText())
            .positiveText(getPositiveButtonText())
            .onAny(
                new MaterialDialog.SingleButtonCallback() {
                  @Override
                  public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    switch (which) {
                      default:
                        MaterialMultiSelectListPreference.this.onClick(
                            dialog, DialogInterface.BUTTON_POSITIVE);
                        break;
                      case NEUTRAL:
                        MaterialMultiSelectListPreference.this.onClick(
                            dialog, DialogInterface.BUTTON_NEUTRAL);
                        break;
                      case NEGATIVE:
                        MaterialMultiSelectListPreference.this.onClick(
                            dialog, DialogInterface.BUTTON_NEGATIVE);
                        break;
                    }
                  }
                })
            .items(getEntries())
            .itemsCallbackMultiChoice(
                indices.toArray(new Integer[indices.size()]),
                new MaterialDialog.ListCallbackMultiChoice() {
                  @Override
                  public boolean onSelection(
                      MaterialDialog dialog, Integer[] which, CharSequence[] text) {
                    onClick(null, DialogInterface.BUTTON_POSITIVE);
                    dialog.dismiss();
                    final Set<String> values = new HashSet<>();
                    for (int i : which) {
                      values.add(getEntryValues()[i].toString());
                    }
                    if (callChangeListener(values)) setValues(values);
                    return true;
                  }
                })
            .dismissListener(this);

    final View contentView = onCreateDialogView();
    if (contentView != null) {
      onBindDialogView(contentView);
      builder.customView(contentView, false);
    } else {
      builder.content(getDialogMessage());
    }

    PrefUtil.registerOnActivityDestroyListener(this, this);

    mDialog = builder.build();
    if (state != null) mDialog.onRestoreInstanceState(state);
    mDialog.show();
  }
Ejemplo n.º 13
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    actionBar = getSupportActionBar();
    assert (actionBar != null);
    actionBar.setDisplayShowTitleEnabled(false);

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle =
        new ActionBarDrawerToggle(
            this,
            drawer,
            toolbar,
            R.string.navigation_drawer_open,
            R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.getMenu().getItem(0).setChecked(true);

    // Sets the name and id in the header bar
    settings = getSharedPreferences(StartActivity.PREFS_NAME, 0);
    View headerLayout = navigationView.getHeaderView(0);
    TextView name = (TextView) headerLayout.findViewById(R.id.student_name);
    TextView id = (TextView) headerLayout.findViewById(R.id.student_id);
    name.setText(settings.getString("name", ""));
    id.setText(settings.getString("id", ""));

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    datePickerButton = (LinearLayout) findViewById(R.id.date_picker_button);
    UpdateSchedule.datePickerWeek = (TextView) findViewById(R.id.date_picker_week);
    UpdateSchedule.datePickerStudent = (TextView) findViewById(R.id.date_picker_student);
    datePickerButton.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {

            dialog.show(getFragmentManager(), "DatePickerDialog");
          }
        });

    cal = Calendar.getInstance();
    cal.setFirstDayOfWeek(Calendar.MONDAY);
    UpdateSchedule.dayOfWeek = DayPicker.toDayNumber(cal.get(Calendar.DAY_OF_WEEK));

    // TODO: Figure out the colors
    dialog =
        DatePickerDialog.newInstance(
            new DayPicker(),
            cal.get(Calendar.YEAR),
            cal.get(Calendar.MONTH),
            cal.get(Calendar.DAY_OF_MONTH));
    dialog.vibrate(false);

    resources = getResources();
    fragmentManager = getFragmentManager();

    replaceFragment(currentFragment);

    SharedPreferences.Editor editor = settings.edit();

    try {
      if (settings.getInt("version", 0)
          < getPackageManager().getPackageInfo(getPackageName(), 0).versionCode) {

        editor.putInt(
            "version", getPackageManager().getPackageInfo(getPackageName(), 0).versionCode);
        editor.apply();

        MaterialDialog.Builder update =
            new MaterialDialog.Builder(this)
                .title(R.string.update)
                .content(R.string.update_text)
                .positiveText(R.string.ok);
        update.show();
      }
    } catch (PackageManager.NameNotFoundException e) {
      e.printStackTrace();
    }

    if (settings.getInt("tutorial", 0) < StartActivity.TUTORIAL_VERSION) {

      editor.putInt("tutorial", StartActivity.TUTORIAL_VERSION);
      editor.apply();

      MaterialDialog.Builder tutorial =
          new MaterialDialog.Builder(this)
              .title(R.string.tutorial)
              .content(Html.fromHtml(getString(R.string.tutorial_text)))
              .positiveText(R.string.ok);
      tutorial.show();
    }

    if (!settings.getString("friends", "").equals("")) {

      Gson gson = new Gson();
      Type type = new TypeToken<List<FriendInfo>>() {}.getType();

      FriendsFragment.friendArrayList.clear();
      List<FriendInfo> friendList = gson.fromJson(settings.getString("friends", ""), type);

      for (int i = 0; i < friendList.size(); i++) {

        if (friendList.get(i).name != null && friendList.get(i).code != null) {

          FriendsFragment.friendArrayList.add(friendList.get(i));
        } else {
          Log.w("Friends", "Found null entry, skipping!");
        }
      }
    }

    invalidateOptionsMenu();
    editCallback =
        new MaterialDialog.InputCallback() {

          @Override
          public void onInput(@NonNull MaterialDialog materialDialog, CharSequence charSequence) {

            FriendsFragment.friendArrayList.get(editPosition).name = charSequence.toString();
            Collections.sort(FriendsFragment.friendArrayList, MainActivity.nameSorter);
            FriendsFragment.fa.notifyDataSetChanged();

            Gson gson = new Gson();
            String jsonFriends = gson.toJson(FriendsFragment.friendArrayList);

            SharedPreferences settings = getSharedPreferences(StartActivity.PREFS_NAME, 0);
            SharedPreferences.Editor editor = settings.edit();

            editor.putString("friends", jsonFriends);
            editor.apply();
          }
        };
    edit =
        new MaterialDialog.Builder(this)
            .title(getText(R.string.edit))
            .inputType(InputType.TYPE_CLASS_TEXT)
            .neutralText(R.string.cancel)
            .negativeText(R.string.remove)
            .onNegative(
                new MaterialDialog.SingleButtonCallback() {

                  @Override
                  public void onClick(
                      @NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {

                    FriendsFragment.friendArrayList.remove(editPosition);
                    Collections.sort(FriendsFragment.friendArrayList, MainActivity.nameSorter);
                    FriendsFragment.fa.notifyDataSetChanged();

                    Gson gson = new Gson();
                    String jsonFriends = gson.toJson(FriendsFragment.friendArrayList);

                    SharedPreferences settings = getSharedPreferences(StartActivity.PREFS_NAME, 0);
                    SharedPreferences.Editor editor = settings.edit();

                    editor.putString("friends", jsonFriends);
                    editor.apply();
                  }
                });
  }
Ejemplo n.º 14
0
  public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.menu_refresh) {
      ScheduleFragment.createList();
    } else if (id == R.id.menu_today) {
      goToday();
    } else if (id == R.id.menu_star) {

      if (ScheduleFragment.user.equals(Framework.MY_SCHEDULE)) {

        Snackbar.make(
                findViewById(R.id.drawer_layout),
                getResources().getString(R.string.selfFriends),
                Snackbar.LENGTH_SHORT)
            .show();

        return true;
      }

      if (FriendsFragment.friendArrayList.size() > 0) {

        for (int i = 0; i < FriendsFragment.friendArrayList.size(); i++) {
          if (FriendsFragment.friendArrayList.get(i).code != null
              && FriendsFragment.friendArrayList.get(i).code.equals(ScheduleFragment.user)) {

            Snackbar.make(
                    findViewById(R.id.drawer_layout),
                    getResources().getString(R.string.alreadyFriends),
                    Snackbar.LENGTH_SHORT)
                .show();

            return true;
          }
        }
      }

      MaterialDialog.Builder name =
          new MaterialDialog.Builder(this)
              .title(getText(R.string.addFriend))
              .inputType(InputType.TYPE_CLASS_TEXT)
              .input(
                  getString(R.string.name),
                  "",
                  new MaterialDialog.InputCallback() {

                    @Override
                    public void onInput(
                        @NonNull MaterialDialog materialDialog, CharSequence charSequence) {

                      FriendsFragment.friendArrayList.add(
                          new FriendInfo(charSequence.toString(), ScheduleFragment.user));
                      Collections.sort(FriendsFragment.friendArrayList, nameSorter);
                      FriendsFragment.fa.notifyDataSetChanged();

                      Gson gson = new Gson();
                      String jsonFriends = gson.toJson(FriendsFragment.friendArrayList);

                      SharedPreferences settings =
                          getSharedPreferences(StartActivity.PREFS_NAME, 0);
                      SharedPreferences.Editor editor = settings.edit();

                      editor.putString("friends", jsonFriends);
                      editor.apply();
                    }
                  });
      name.show();
    }

    return true;
  }
Ejemplo n.º 15
0
  // TODO: Move some off this stuff into seperate functions
  @SuppressWarnings("StatementWithEmptyBody")
  @Override
  public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    assert (actionBar != null);

    progressBar.setVisibility(View.GONE);

    if (id == R.id.nav_schedule) {
      actionBar.setDisplayShowTitleEnabled(false);
      actionBar.setTitle(R.string.title_activity_main);

      ScheduleFragment.user = Framework.MY_SCHEDULE;
      UpdateSchedule.dayOfWeek = DayPicker.toDayNumber(cal.get(Calendar.DAY_OF_WEEK));
      ScheduleFragment.setWeekUnix((int) (System.currentTimeMillis() / 1000));
      UpdateSchedule.scroll = true;
      ScheduleFragment.createList();
      datePickerButton.setVisibility(View.VISIBLE);
      menu.findItem(R.id.menu_search).setVisible(true);

      navigationView.getMenu().getItem(0).setChecked(true);
      if (ScheduleFragment.classArrayList.size() == 0) {
        progressBar.setVisibility(View.VISIBLE);
      }

      replaceFragment(sf);
      currentFragment = sf;
      //        } else if (id == R.id.nav_announcements) {
      //            ab.setDisplayShowTitleEnabled(true);
      //            ab.setTitle(R.string.title_fragment_announcements);
      //
      //            datePickerButton.setVisibility(View.GONE);
      //            menu.findItem(R.id.menu_search).setVisible(false);
      //
      //            replaceFragment(af);
    } else if (id == R.id.nav_friends) {
      actionBar.setDisplayShowTitleEnabled(true);
      actionBar.setTitle(R.string.title_fragment_friends);

      datePickerButton.setVisibility(View.GONE);
      menu.findItem(R.id.menu_search).setVisible(false);

      replaceFragment(ff);
      currentFragment = ff;
    } else if (id == R.id.nav_info) {

      MaterialDialog.Builder about =
          new MaterialDialog.Builder(this)
              .title(R.string.about)
              .content(R.string.about_text)
              .positiveText(R.string.ok)
              .negativeText(R.string.contact)
              .onNegative(
                  new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(
                        @NonNull MaterialDialog materialDialog,
                        @NonNull DialogAction dialogAction) {

                      Uri uri =
                          Uri.parse("mailto:[email protected]")
                              .buildUpon()
                              .build();

                      Intent intent = new Intent(Intent.ACTION_SENDTO, uri);

                      startActivity(Intent.createChooser(intent, getString(R.string.send)));
                    }
                  });
      about.show();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

    invalidateOptionsMenu();

    return true;
  }