예제 #1
0
 /* (non-Javadoc)
  * calls {@link #convText for formatting the values retrieved from the cursor}
  * @see android.widget.SimpleCursorAdapter#setViewText(android.widget.TextView, java.lang.String)
  */
 @Override
 public void setViewText(TextView v, String text) {
   switch (v.getId()) {
     case R.id.date:
       text = Utils.convDateTime(text, itemDateFormat);
       break;
     case R.id.amount:
       text = Utils.convAmount(text, mAccount.currency);
   }
   super.setViewText(v, text);
 }
예제 #2
0
 @Override
 public boolean onPreferenceChange(Preference pref, Object value) {
   String key = pref.getKey();
   if (key.equals(MyApplication.PrefKey.SHARE_TARGET.getKey())) {
     String target = (String) value;
     URI uri;
     if (!target.equals("")) {
       uri = Utils.validateUri(target);
       if (uri == null) {
         Toast.makeText(
                 getBaseContext(),
                 getString(R.string.ftp_uri_malformed, target),
                 Toast.LENGTH_LONG)
             .show();
         return false;
       }
       String scheme = uri.getScheme();
       if (!(scheme.equals("ftp") || scheme.equals("mailto"))) {
         Toast.makeText(
                 getBaseContext(),
                 getString(R.string.share_scheme_not_supported, scheme),
                 Toast.LENGTH_LONG)
             .show();
         return false;
       }
       Intent intent;
       if (scheme.equals("ftp")) {
         intent = new Intent(android.content.Intent.ACTION_SENDTO);
         intent.setData(android.net.Uri.parse(target));
         if (!Utils.isIntentAvailable(this, intent)) {
           showDialog(R.id.FTP_DIALOG);
         }
       }
     }
   } else if (key.equals(MyApplication.PrefKey.ENTER_LICENCE.getKey())) {
     if (Utils.verifyLicenceKey((String) value)) {
       Toast.makeText(getBaseContext(), R.string.licence_validation_success, Toast.LENGTH_LONG)
           .show();
       MyApplication.getInstance().setContribEnabled(true);
       setProtectionDependentsState();
     } else {
       Toast.makeText(getBaseContext(), R.string.licence_validation_failure, Toast.LENGTH_LONG)
           .show();
       MyApplication.getInstance().setContribEnabled(false);
     }
     configureContribPrefs();
   }
   return true;
 }
예제 #3
0
 @Override
 public Uri save() {
   ContentValues initialValues = new ContentValues();
   initialValues.put(KEY_LABEL, label);
   initialValues.put(KEY_LABEL_NORMALIZED, Utils.normalize(label));
   Uri uri;
   if (getId() == 0) {
     if (!isMain(parentId)) {
       uri = null;
       AcraHelper.report(new Exception("Attempt to store deep category hierarchy detected"));
     } else {
       initialValues.put(KEY_PARENTID, parentId);
       try {
         uri = cr().insert(CONTENT_URI, initialValues);
       } catch (SQLiteConstraintException e) {
         uri = null;
       }
     }
   } else {
     uri = CONTENT_URI.buildUpon().appendPath(String.valueOf(getId())).build();
     try {
       cr().update(
               CONTENT_URI.buildUpon().appendPath(String.valueOf(getId())).build(),
               initialValues,
               null,
               null);
     } catch (SQLiteConstraintException e) {
       uri = null;
     }
   }
   return uri;
 }
예제 #4
0
 private Intent findDirPicker() {
   Intent intent = new Intent("com.estrongs.action.PICK_DIRECTORY ");
   intent.putExtra("com.estrongs.intent.extra.TITLE", "Select Directory");
   if (Utils.isIntentAvailable(this, intent)) {
     return intent;
   }
   return null;
 }
예제 #5
0
 public void updateBalance() {
   ExpenseEdit ctx = (ExpenseEdit) getActivity();
   if (ctx == null) return;
   unsplitAmount = ctx.getAmount();
   // when we are called before transaction is loaded in parent activity
   if (unsplitAmount == null) return;
   unsplitAmount.setAmountMinor(unsplitAmount.getAmountMinor() - transactionSum);
   if (balanceTv != null) balanceTv.setText(Utils.formatCurrency(unsplitAmount));
 }
예제 #6
0
 private void setAppDirSummary() {
   File appDir = Utils.requireAppDir();
   Preference pref = findPreference(MyApplication.PrefKey.APP_DIR.getKey());
   if (appDir == null) {
     pref.setSummary(R.string.external_storage_unavailable);
     pref.setEnabled(false);
   } else {
     pref.setSummary(appDir.getPath());
   }
 }
  @Override
  public void onDialogClosed(boolean positiveResult) {

    if (positiveResult) {
      if (boolProtect && strPass1 != null && strPass1.equals(strPass2)) {
        String hash = Utils.md5(strPass1);
        MyApplication.PrefKey.SET_PASSWORD.putString(hash);
      }
      ((PasswordPreference) getPreference()).setValue(boolProtect);
    }
  }
예제 #8
0
 private void fillSums(HeaderViewHolder holder, Cursor mGroupingCursor) {
   holder.sumExpense.setText(
       "- "
           + Utils.convAmount(
               DbUtils.getLongOr0L(mGroupingCursor, columnIndexGroupSumExpense),
               mAccount.currency));
   holder.sumIncome.setText(
       "+ "
           + Utils.convAmount(
               DbUtils.getLongOr0L(mGroupingCursor, columnIndexGroupSumIncome),
               mAccount.currency));
   holder.sumTransfer.setText(
       "<-> "
           + Utils.convAmount(
               DbUtils.getLongOr0L(mGroupingCursor, columnIndexGroupSumTransfer),
               mAccount.currency));
   holder.interimBalance.setText(
       "= "
           + Utils.convAmount(
               DbUtils.getLongOr0L(mGroupingCursor, columIndexGroupSumInterim),
               mAccount.currency));
 }
예제 #9
0
 @Override
 public void onClick(View v) {
   final SharedPreferences settings = MyApplication.getInstance().getSettings();
   final String securityQuestion = MyApplication.PrefKey.SECURITY_QUESTION.getString("");
   EditText input = (EditText) dialog.findViewById(R.id.password);
   TextView error = (TextView) dialog.findViewById(R.id.passwordInvalid);
   if (v == dialog.getButton(AlertDialog.BUTTON_NEGATIVE)) {
     if ((Boolean) input.getTag()) {
       input.setTag(Boolean.valueOf(false));
       ((Button) v).setText(R.string.password_lost);
       dialog.setTitle(R.string.password_prompt);
     } else {
       input.setTag(Boolean.valueOf(true));
       dialog.setTitle(securityQuestion);
       ((Button) v).setText(android.R.string.cancel);
     }
   } else {
     String value = input.getText().toString();
     boolean isInSecurityQuestion = (Boolean) input.getTag();
     if (Utils.md5(value)
         .equals(
             (isInSecurityQuestion
                     ? MyApplication.PrefKey.SECURITY_ANSWER
                     : MyApplication.PrefKey.SET_PASSWORD)
                 .getString(""))) {
       input.setText("");
       error.setText("");
       MyApplication.getInstance().setLocked(false);
       ctx.findViewById(android.R.id.content).setVisibility(View.VISIBLE);
       if (ctx instanceof ActionBarActivity) {
         ((ActionBarActivity) ctx).getSupportActionBar().show();
       }
       if (isInSecurityQuestion) {
         MyApplication.PrefKey.PERFORM_PROTECTION.putBoolean(false);
         Toast.makeText(
                 ctx.getBaseContext(), R.string.password_disabled_reenable, Toast.LENGTH_LONG)
             .show();
         dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setText(R.string.password_lost);
         dialog.setTitle(R.string.password_prompt);
         input.setTag(Boolean.valueOf(false));
       }
       dialog.dismiss();
     } else {
       input.setText("");
       error.setText(
           isInSecurityQuestion
               ? R.string.password_security_answer_not_valid
               : R.string.password_not_valid);
     }
   }
 }
예제 #10
0
 protected BigDecimal validateAmountInput(AmountEditText input, boolean showToUser) {
   String strAmount = input.getText().toString();
   if (strAmount.equals("")) {
     if (showToUser) input.setError(getString(R.string.no_amount_given));
     return null;
   }
   BigDecimal amount = Utils.validateNumber(input.getNumberFormat(), strAmount);
   if (amount == null) {
     if (showToUser)
       input.setError(
           getString(R.string.invalid_number_format, input.getNumberFormat().format(11.11)));
     return null;
   }
   return amount;
 }
예제 #11
0
 private void setGrouping() {
   switch (mAccount.grouping) {
     case DAY:
       itemDateFormat = localizedTimeFormat;
       break;
     case MONTH:
       itemDateFormat = new SimpleDateFormat("dd");
       break;
     case WEEK:
       itemDateFormat = new SimpleDateFormat("EEE");
       break;
     case YEAR:
     case NONE:
       itemDateFormat = Utils.localizedYearlessDateFormat();
   }
   restartGroupingLoader();
 }
예제 #12
0
 private void configureContribPrefs() {
   Preference pref1 = findPreference(MyApplication.PrefKey.REQUEST_LICENCE.getKey()),
       pref2 = findPreference(MyApplication.PrefKey.CONTRIB_DONATE.getKey());
   if (MyApplication.getInstance().isContribEnabled()) {
     ((PreferenceCategory) findPreference(MyApplication.PrefKey.CATEGORY_CONTRIB.getKey()))
         .removePreference(pref1);
     pref2.setSummary(
         Utils.concatResStrings(
             this, R.string.thank_you, R.string.pref_contrib_donate_summary_already_contrib));
   } else {
     pref1.setOnPreferenceClickListener(this);
     pref1.setSummary(
         getString(
             R.string.pref_request_licence_summary,
             Secure.getString(getContentResolver(), Secure.ANDROID_ID)));
     pref2.setSummary(R.string.pref_contrib_donate_summary);
   }
   pref2.setOnPreferenceClickListener(this);
   findPreference(MyApplication.PrefKey.SHORTCUT_CREATE_SPLIT.getKey())
       .setEnabled(MyApplication.getInstance().isContribEnabled());
 }
예제 #13
0
  // credits Financisto
  // src/ru/orangesoftware/financisto/activity/PreferencesActivity.java
  private void addShortcut(String activity, int nameId, int iconId, Bundle extra) {
    Intent shortcutIntent = createShortcutIntent(activity);
    if (extra != null) {
      shortcutIntent.putExtras(extra);
    }
    Intent intent = new Intent();
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(nameId));
    intent.putExtra(
        Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, iconId));
    intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");

    if (Utils.isIntentReceiverAvailable(this, intent)) {
      sendBroadcast(intent);
      Toast.makeText(getBaseContext(), getString(R.string.pref_shortcut_added), Toast.LENGTH_LONG)
          .show();
    } else {
      Toast.makeText(
              getBaseContext(), getString(R.string.pref_shortcut_not_added), Toast.LENGTH_LONG)
          .show();
    }
  }
예제 #14
0
 private Result analyzeSAX(int id) {
   return Utils.analyzeGrisbiFileWithSAX(
       getInstrumentation().getContext().getResources().openRawResource(id));
 }
예제 #15
0
 @Override
 public boolean onPreferenceClick(Preference preference) {
   if (preference.getKey().equals(MyApplication.PrefKey.CONTRIB_DONATE.getKey())) {
     Utils.contribBuyDo(MyPreferenceActivity.this);
     return true;
   }
   if (preference.getKey().equals(MyApplication.PrefKey.REQUEST_LICENCE.getKey())) {
     String androidId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
     Intent i = new Intent(android.content.Intent.ACTION_SEND);
     i.setType("plain/text");
     i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {MyApplication.FEEDBACK_EMAIL});
     i.putExtra(
         android.content.Intent.EXTRA_SUBJECT,
         "[" + getString(R.string.app_name) + "] " + getString(R.string.contrib_key));
     i.putExtra(
         android.content.Intent.EXTRA_TEXT,
         getString(R.string.request_licence_mail_head, androidId)
             + " \n\n["
             + getString(R.string.request_licence_mail_description)
             + "]");
     if (!Utils.isIntentAvailable(MyPreferenceActivity.this, i)) {
       Toast.makeText(
               getBaseContext(), R.string.no_app_handling_email_available, Toast.LENGTH_LONG)
           .show();
     } else {
       startActivity(i);
     }
     return true;
   }
   if (preference.getKey().equals(MyApplication.PrefKey.SEND_FEEDBACK.getKey())) {
     CommonCommands.dispatchCommand(this, R.id.FEEDBACK_COMMAND, null);
     return true;
   }
   if (preference.getKey().equals(MyApplication.PrefKey.RATE.getKey())) {
     PrefKey.NEXT_REMINDER_RATE.putLong(-1);
     CommonCommands.dispatchCommand(this, R.id.RATE_COMMAND, null);
     return true;
   }
   if (preference.getKey().equals(MyApplication.PrefKey.MORE_INFO_DIALOG.getKey())) {
     showDialog(R.id.MORE_INFO_DIALOG);
     return true;
   }
   if (preference.getKey().equals(MyApplication.PrefKey.RESTORE.getKey())
       || preference.getKey().equals(MyApplication.PrefKey.RESTORE_LEGACY.getKey())) {
     startActivityForResult(preference.getIntent(), RESTORE_REQUEST);
     return true;
   }
   if (preference.getKey().equals(MyApplication.PrefKey.APP_DIR.getKey())) {
     File appDir = Utils.requireAppDir();
     Preference pref = findPreference(MyApplication.PrefKey.APP_DIR.getKey());
     if (appDir == null) {
       pref.setSummary(R.string.external_storage_unavailable);
       pref.setEnabled(false);
     } else {
       Intent intent = new Intent(this, FolderBrowser.class);
       intent.putExtra(FolderBrowser.PATH, appDir.getPath());
       startActivityForResult(intent, PICK_FOLDER_REQUEST);
     }
     return true;
   }
   if (preference.getKey().equals(MyApplication.PrefKey.SHORTCUT_CREATE_TRANSACTION.getKey())) {
     Bundle extras = new Bundle();
     extras.putBoolean(AbstractWidget.EXTRA_START_FROM_WIDGET, true);
     extras.putBoolean(AbstractWidget.EXTRA_START_FROM_WIDGET_DATA_ENTRY, true);
     addShortcut(
         ".activity.ExpenseEdit",
         R.string.transaction,
         R.drawable.shortcut_create_transaction_icon,
         extras);
     return true;
   }
   if (preference.getKey().equals(MyApplication.PrefKey.SHORTCUT_CREATE_TRANSFER.getKey())) {
     Bundle extras = new Bundle();
     extras.putBoolean(AbstractWidget.EXTRA_START_FROM_WIDGET, true);
     extras.putBoolean(AbstractWidget.EXTRA_START_FROM_WIDGET_DATA_ENTRY, true);
     extras.putInt(MyApplication.KEY_OPERATION_TYPE, MyExpenses.TYPE_TRANSFER);
     addShortcut(
         ".activity.ExpenseEdit",
         R.string.transfer,
         R.drawable.shortcut_create_transfer_icon,
         extras);
     return true;
   }
   if (preference.getKey().equals(MyApplication.PrefKey.SHORTCUT_CREATE_SPLIT.getKey())) {
     Bundle extras = new Bundle();
     extras.putBoolean(AbstractWidget.EXTRA_START_FROM_WIDGET, true);
     extras.putBoolean(AbstractWidget.EXTRA_START_FROM_WIDGET_DATA_ENTRY, true);
     extras.putInt(MyApplication.KEY_OPERATION_TYPE, MyExpenses.TYPE_SPLIT);
     addShortcut(
         ".activity.ExpenseEdit",
         R.string.split_transaction,
         R.drawable.shortcut_create_split_icon,
         extras);
     return true;
   }
   return false;
 }
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    final MyExpenses ctx = (MyExpenses) getActivity();
    Context wrappedCtx = DialogUtils.wrapContext2(ctx);
    if (mTransaction == null) {
      return new AlertDialog.Builder(wrappedCtx)
          .setMessage("Transaction has been deleted")
          .create();
    }
    final LayoutInflater li = LayoutInflater.from(wrappedCtx);
    View view = li.inflate(R.layout.transaction_detail, null);
    int title;
    boolean type =
        mTransaction.amount.getAmountMinor() > 0 ? ExpenseEdit.INCOME : ExpenseEdit.EXPENSE;
    if (mTransaction instanceof SplitTransaction) {
      // TODO: refactor duplicated code with SplitPartList
      title = R.string.split_transaction;
      View emptyView = view.findViewById(R.id.empty);
      Resources.Theme theme = ctx.getTheme();
      TypedValue color = new TypedValue();
      theme.resolveAttribute(R.attr.colorExpense, color, true);
      final int colorExpense = color.data;
      theme.resolveAttribute(R.attr.colorIncome, color, true);
      final int colorIncome = color.data;

      ListView lv = (ListView) view.findViewById(R.id.list);
      // Create an array to specify the fields we want to display in the list
      String[] from = new String[] {KEY_LABEL_MAIN, KEY_AMOUNT};

      // and an array of the fields we want to bind those fields to
      int[] to = new int[] {R.id.category, R.id.amount};

      final String categorySeparator, commentSeparator;
      categorySeparator = " : ";
      commentSeparator = " / ";
      // Now create a simple cursor adapter and set it to display
      mAdapter =
          new SimpleCursorAdapter(ctx, R.layout.split_part_row, null, from, to, 0) {
            /* (non-Javadoc)
             * calls {@link #convText for formatting the values retrieved from the cursor}
             * @see android.widget.SimpleCursorAdapter#setViewText(android.widget.TextView, java.lang.String)
             */
            @Override
            public void setViewText(TextView v, String text) {
              switch (v.getId()) {
                case R.id.amount:
                  text = Utils.convAmount(text, mTransaction.amount.getCurrency());
              }
              super.setViewText(v, text);
            }
            /* (non-Javadoc)
             * manipulates the view for amount (setting expenses to red) and
             * category (indicate transfer direction with => or <=
             * @see android.widget.CursorAdapter#getView(int, android.view.View, android.view.ViewGroup)
             */
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
              View row = super.getView(position, convertView, parent);
              TextView tv1 = (TextView) row.findViewById(R.id.amount);
              Cursor c = getCursor();
              c.moveToPosition(position);
              int col = c.getColumnIndex(KEY_AMOUNT);
              long amount = c.getLong(col);
              if (amount < 0) {
                tv1.setTextColor(colorExpense);
                // Set the background color of the text.
              } else {
                tv1.setTextColor(colorIncome);
              }
              TextView tv2 = (TextView) row.findViewById(R.id.category);
              if (Build.VERSION.SDK_INT < 11) tv2.setTextColor(Color.WHITE);
              String catText = tv2.getText().toString();
              if (DbUtils.getLongOrNull(c, KEY_TRANSFER_PEER) != null) {
                catText = ((amount < 0) ? "=&gt; " : "&lt;= ") + catText;
              } else {
                Long catId = DbUtils.getLongOrNull(c, KEY_CATID);
                if (catId == null) {
                  catText = getString(R.string.no_category_assigned);
                } else {
                  col = c.getColumnIndex(KEY_LABEL_SUB);
                  String label_sub = c.getString(col);
                  if (label_sub != null && label_sub.length() > 0) {
                    catText += categorySeparator + label_sub;
                  }
                }
              }
              col = c.getColumnIndex(KEY_COMMENT);
              String comment = c.getString(col);
              if (comment != null && comment.length() > 0) {
                catText += (catText.equals("") ? "" : commentSeparator) + "<i>" + comment + "</i>";
              }
              tv2.setText(Html.fromHtml(catText));
              return row;
            }
          };
      lv.setAdapter(mAdapter);
      lv.setEmptyView(emptyView);
      LoaderManager manager = ctx.getSupportLoaderManager();
      if (manager.getLoader(MyExpenses.SPLIT_PART_CURSOR) != null
          && !manager.getLoader(MyExpenses.SPLIT_PART_CURSOR).isReset())
        manager.restartLoader(MyExpenses.SPLIT_PART_CURSOR, null, this);
      else manager.initLoader(MyExpenses.SPLIT_PART_CURSOR, null, this);
    } else {
      view.findViewById(R.id.SplitContainer).setVisibility(View.GONE);
      if (mTransaction instanceof Transfer) {
        title = R.string.transfer;
        ((TextView) view.findViewById(R.id.AccountLabel)).setText(R.string.transfer_from_account);
        ((TextView) view.findViewById(R.id.CategoryLabel)).setText(R.string.transfer_to_account);
      } else title = type ? R.string.income : R.string.expense;
    }
    String accountLabel = Account.getInstanceFromDb(mTransaction.accountId).label;
    if (mTransaction instanceof Transfer) {
      ((TextView) view.findViewById(R.id.Account))
          .setText(type ? mTransaction.label : accountLabel);
      ((TextView) view.findViewById(R.id.Category))
          .setText(type ? accountLabel : mTransaction.label);
    } else {
      ((TextView) view.findViewById(R.id.Account)).setText(accountLabel);
      if ((mTransaction.catId != null && mTransaction.catId > 0)) {
        ((TextView) view.findViewById(R.id.Category)).setText(mTransaction.label);
      } else {
        view.findViewById(R.id.CategoryRow).setVisibility(View.GONE);
      }
    }
    ((TextView) view.findViewById(R.id.Date))
        .setText(
            DateFormat.getDateInstance(DateFormat.FULL).format(mTransaction.getDate())
                + " "
                + DateFormat.getTimeInstance(DateFormat.SHORT).format(mTransaction.getDate()));
    ((TextView) view.findViewById(R.id.Amount))
        .setText(
            Utils.formatCurrency(
                new Money(
                    mTransaction.amount.getCurrency(),
                    Math.abs(mTransaction.amount.getAmountMinor()))));
    if (!mTransaction.comment.equals(""))
      ((TextView) view.findViewById(R.id.Comment)).setText(mTransaction.comment);
    else view.findViewById(R.id.CommentRow).setVisibility(View.GONE);
    if (!mTransaction.referenceNumber.equals(""))
      ((TextView) view.findViewById(R.id.Number)).setText(mTransaction.referenceNumber);
    else view.findViewById(R.id.NumberRow).setVisibility(View.GONE);
    if (!mTransaction.payee.equals(""))
      ((TextView) view.findViewById(R.id.Payee)).setText(mTransaction.payee);
    else view.findViewById(R.id.PayeeRow).setVisibility(View.GONE);
    if (mTransaction.methodId != null)
      ((TextView) view.findViewById(R.id.Method))
          .setText(PaymentMethod.getInstanceFromDb(mTransaction.methodId).getDisplayLabel());
    else view.findViewById(R.id.MethodRow).setVisibility(View.GONE);
    if (Account.getInstanceFromDb(mTransaction.accountId).type.equals(Type.CASH))
      view.findViewById(R.id.StatusRow).setVisibility(View.GONE);
    else {
      TextView tv = (TextView) view.findViewById(R.id.Status);
      tv.setBackgroundColor(mTransaction.crStatus.color);
      tv.setText(mTransaction.crStatus.toString());
    }
    return new AlertDialog.Builder(getActivity())
        .setTitle(title)
        .setView(view)
        .setNegativeButton(android.R.string.ok, this)
        .setPositiveButton(R.string.menu_edit, this)
        .create();
  }
예제 #17
0
  @SuppressWarnings("deprecation")
  @Override
  public void onCreate(Bundle savedInstanceState) {
    setTheme(MyApplication.getThemeId(Build.VERSION.SDK_INT < 11));
    super.onCreate(savedInstanceState);
    setTitle(Utils.concatResStrings(this, R.string.app_name, R.string.menu_settings));
    addPreferencesFromResource(R.layout.preferences);
    Preference pref = findPreference(MyApplication.PrefKey.SHARE_TARGET.getKey());
    pref.setSummary(
        getString(R.string.pref_share_target_summary)
            + ":\n"
            + "ftp: \"ftp://*****:*****@my.example.org:port/my/directory/\"\n"
            + "mailto: \"mailto:[email protected]\"");
    pref.setOnPreferenceChangeListener(this);
    configureContribPrefs();
    findPreference(MyApplication.PrefKey.SEND_FEEDBACK.getKey()).setOnPreferenceClickListener(this);
    findPreference(MyApplication.PrefKey.MORE_INFO_DIALOG.getKey())
        .setOnPreferenceClickListener(this);

    pref = findPreference(MyApplication.PrefKey.RESTORE.getKey());
    pref.setTitle(getString(R.string.pref_restore_title) + " (ZIP)");
    pref.setOnPreferenceClickListener(this);

    pref = findPreference(MyApplication.PrefKey.RESTORE_LEGACY.getKey());
    pref.setTitle(
        getString(R.string.pref_restore_title)
            + " ("
            + getString(R.string.pref_restore_legacy_data)
            + ")");
    pref.setOnPreferenceClickListener(this);

    findPreference(MyApplication.PrefKey.RATE.getKey()).setOnPreferenceClickListener(this);

    findPreference(MyApplication.PrefKey.ENTER_LICENCE.getKey())
        .setOnPreferenceChangeListener(this);
    setProtectionDependentsState();

    findPreference(MyApplication.PrefKey.PERFORM_PROTECTION.getKey())
        .setOnPreferenceChangeListener(this);

    findPreference(MyApplication.PrefKey.PROTECTION_ENABLE_ACCOUNT_WIDGET.getKey())
        .setOnPreferenceChangeListener(this);

    findPreference(MyApplication.PrefKey.PROTECTION_ENABLE_TEMPLATE_WIDGET.getKey())
        .setOnPreferenceChangeListener(this);

    findPreference(MyApplication.PrefKey.APP_DIR.getKey()).setOnPreferenceClickListener(this);
    setAppDirSummary();
    if (savedInstanceState == null
        && TextUtils.equals(
            getIntent().getStringExtra(KEY_OPEN_PREF_KEY),
            MyApplication.PrefKey.PLANNER_CALENDAR_ID.getKey())) {
      ((CalendarListPreference) findPreference(MyApplication.PrefKey.PLANNER_CALENDAR_ID.getKey()))
          .show();
    }

    findPreference(MyApplication.PrefKey.SHORTCUT_CREATE_TRANSACTION.getKey())
        .setOnPreferenceClickListener(this);
    findPreference(MyApplication.PrefKey.SHORTCUT_CREATE_TRANSFER.getKey())
        .setOnPreferenceClickListener(this);
    findPreference(MyApplication.PrefKey.SHORTCUT_CREATE_SPLIT.getKey())
        .setOnPreferenceClickListener(this);
    findPreference(MyApplication.PrefKey.SECURITY_QUESTION.getKey())
        .setSummary(
            Utils.concatResStrings(
                this, R.string.pref_security_question_summary, R.string.contrib_key_requires));
    findPreference(MyApplication.PrefKey.SHORTCUT_CREATE_SPLIT.getKey())
        .setSummary(
            Utils.concatResStrings(
                this, R.string.pref_shortcut_summary, R.string.contrib_key_requires));
  }
예제 #18
0
 public void refresh() {
   Utils.requireLoader(mManager, SORTABLE_CURSOR, null, this);
 }
예제 #19
0
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      convertView = super.getView(position, convertView, parent);
      Cursor c = getCursor();
      c.moveToPosition(position);
      boolean doesHavePlan = !c.isNull(columnIndexPlanId);
      TextView tv1 = (TextView) convertView.findViewById(R.id.amount);
      long amount = c.getLong(columnIndexAmount);
      tv1.setTextColor(amount < 0 ? colorExpense : colorIncome);
      tv1.setText(
          Utils.convAmount(amount, Utils.getSaveInstance(c.getString(columnIndexCurrency))));
      int color = c.getInt(columnIndexColor);
      convertView.findViewById(R.id.colorAccount).setBackgroundColor(color);
      TextView tv2 = (TextView) convertView.findViewById(R.id.category);
      CharSequence catText = tv2.getText();
      if (c.getInt(columnIndexTransferPeer) > 0) {
        catText = ((amount < 0) ? "=> " : "<= ") + catText;
      } else {
        Long catId = DbUtils.getLongOrNull(c, KEY_CATID);
        if (catId == null) {
          catText = Category.NO_CATEGORY_ASSIGNED_LABEL;
        } else {
          String label_sub = c.getString(columnIndexLabelSub);
          if (label_sub != null && label_sub.length() > 0) {
            catText = catText + categorySeparator + label_sub;
          }
        }
      }
      // TODO: simplify confer TemplateWidget
      SpannableStringBuilder ssb;
      String comment = c.getString(columnIndexComment);
      if (comment != null && comment.length() > 0) {
        ssb = new SpannableStringBuilder(comment);
        ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, comment.length(), 0);
        catText = TextUtils.concat(catText, commentSeparator, ssb);
      }
      String payee = c.getString(columnIndexPayee);
      if (payee != null && payee.length() > 0) {
        ssb = new SpannableStringBuilder(payee);
        ssb.setSpan(new UnderlineSpan(), 0, payee.length(), 0);
        catText = TextUtils.concat(catText, commentSeparator, ssb);
      }
      tv2.setText(catText);

      if (doesHavePlan) {
        String planInfo = c.getString(columnIndexPlanInfo);
        if (planInfo == null) {
          planInfo =
              getString(
                  ContextCompat.checkSelfPermission(
                              getActivity(), Manifest.permission.WRITE_CALENDAR)
                          == PackageManager.PERMISSION_DENIED
                      ? R.string.calendar_permission_required
                      : R.string.plan_event_deleted);
        }
        ((TextView) convertView.findViewById(R.id.title))
            .setText(
                //noinspection SetTextI18n
                c.getString(columnIndexTitle) + " (" + planInfo + ")");
      }
      ((ImageView) convertView.findViewById(R.id.Plan))
          .setImageResource(doesHavePlan ? R.drawable.ic_event : R.drawable.ic_menu_template);
      return convertView;
    }
  @Override
  public void onClick(DialogInterface dialog, int which) {
    Activity ctx = getActivity();
    if (ctx == null) {
      return;
    }
    Bundle args = getArguments();
    Long accountId = args != null ? args.getLong(KEY_ACCOUNTID) : null;
    AlertDialog dlg = (AlertDialog) dialog;
    String format =
        ((RadioGroup) dlg.findViewById(R.id.format)).getCheckedRadioButtonId() == R.id.csv
            ? "CSV"
            : "QIF";
    String dateFormat = dateFormatET.getText().toString();
    char decimalSeparator =
        ((RadioGroup) dlg.findViewById(R.id.separator)).getCheckedRadioButtonId() == R.id.dot
            ? '.'
            : ',';

    int handleDeleted;
    switch (handleDeletedGroup.getCheckedRadioButtonId()) {
      case R.id.update_balance:
        handleDeleted = Account.EXPORT_HANDLE_DELETED_UPDATE_BALANCE;
        break;
      case R.id.create_helper:
        handleDeleted = Account.EXPORT_HANDLE_DELETED_CREATE_HELPER;
        break;
      default: // -1
        handleDeleted = Account.EXPORT_HANDLE_DELETED_DO_NOTHING;
    }

    String encoding = (String) ((Spinner) dlg.findViewById(R.id.Encoding)).getSelectedItem();
    SharedPreferencesCompat.apply(
        MyApplication.getInstance()
            .getSettings()
            .edit()
            .putString(MyApplication.PrefKey.EXPORT_FORMAT.getKey(), format)
            .putString(PREFKEY_EXPORT_DATE_FORMAT, dateFormat)
            .putString(PREFKEY_EXPORT_ENCODING, encoding)
            .putInt(ExportTask.KEY_DECIMAL_SEPARATOR, decimalSeparator)
            .putInt(ExportTask.KEY_EXPORT_HANDLE_DELETED, handleDeleted));
    boolean deleteP = deleteCB.isChecked();
    boolean notYetExportedP = notYetExportedCB.isChecked();
    String fileName = fileNameET.getText().toString();
    Result appDirStatus = Utils.checkAppDir();
    if (appDirStatus.success) {
      Bundle b = new Bundle();
      b.putInt(ConfirmationDialogFragment.KEY_COMMAND_POSITIVE, R.id.START_EXPORT_COMMAND);
      if (accountId == null) {
      } else if (accountId > 0) {
        b.putLong(KEY_ROWID, accountId);
      } else {
        b.putString(KEY_CURRENCY, currency);
      }
      b.putString(TaskExecutionFragment.KEY_FORMAT, format);
      b.putBoolean(ExportTask.KEY_DELETE_P, deleteP);
      b.putBoolean(ExportTask.KEY_NOT_YET_EXPORTED_P, notYetExportedP);
      b.putString(TaskExecutionFragment.KEY_DATE_FORMAT, dateFormat);
      b.putChar(ExportTask.KEY_DECIMAL_SEPARATOR, decimalSeparator);
      b.putString(TaskExecutionFragment.KEY_ENCODING, encoding);
      b.putInt(ExportTask.KEY_EXPORT_HANDLE_DELETED, handleDeleted);
      b.putString(ExportTask.KEY_FILE_NAME, fileName);
      if (Utils.checkAppFolderWarning()) {
        ((ConfirmationDialogListener) getActivity()).onPositive(b);
      } else {
        b.putInt(ConfirmationDialogFragment.KEY_TITLE, R.string.dialog_title_attention);
        b.putString(
            ConfirmationDialogFragment.KEY_MESSAGE,
            getString(R.string.warning_app_folder_will_be_deleted_upon_uninstall));
        b.putString(
            ConfirmationDialogFragment.KEY_PREFKEY,
            MyApplication.PrefKey.APP_FOLDER_WARNING_SHOWN.getKey());
        ConfirmationDialogFragment.newInstance(b).show(getFragmentManager(), "APP_FOLDER_WARNING");
      }
    } else {
      Toast.makeText(ctx, appDirStatus.print(ctx), Toast.LENGTH_LONG).show();
    }
  }
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    MyExpenses ctx = (MyExpenses) getActivity();
    Bundle args = getArguments();
    Long accountId = args != null ? args.getLong(KEY_ACCOUNTID) : null;
    boolean allP = false, hasExported;
    String warningText;
    final String fileName;
    String now = new SimpleDateFormat("yyyMMdd-HHmmss", Locale.US).format(new Date());

    if (accountId == null) {
      allP = true;
      warningText = getString(R.string.warning_reset_account_all);
      // potential Strict mode violation (currently exporting all accounts with different currencies
      // is not active in the UI)
      hasExported = Account.getHasExported(null);
      fileName = "export" + "-" + now;
    } else {
      Account a = Account.getInstanceFromDb(accountId);
      hasExported = ctx.hasExported();
      if (accountId < 0L) {
        allP = true;
        currency = a.currency.getCurrencyCode();
        fileName = "export" + "-" + currency + "-" + now;
        warningText = getString(R.string.warning_reset_account_all, " (" + currency + ")");
      } else {
        fileName = Utils.escapeForFileName(a.label) + "-" + now;
        warningText = getString(R.string.warning_reset_account);
      }
    }

    LayoutInflater li = LayoutInflater.from(ctx);
    View view = li.inflate(R.layout.export_dialog, null);

    if (args.getBoolean(KEY_IS_FILTERED)) {
      view.findViewById(R.id.with_filter).setVisibility(View.VISIBLE);
      warningText = getString(R.string.warning_reset_account_matched);
    }

    dateFormatET = (EditText) view.findViewById(R.id.date_format);
    String dateFormatDefault =
        ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT)).toPattern();
    String dateFormat =
        MyApplication.getInstance().getSettings().getString(PREFKEY_EXPORT_DATE_FORMAT, "");
    if (dateFormat.equals("")) dateFormat = dateFormatDefault;
    else {
      try {
        new SimpleDateFormat(dateFormat, Locale.US);
      } catch (IllegalArgumentException e) {
        dateFormat = dateFormatDefault;
      }
    }
    dateFormatET.setText(dateFormat);
    dateFormatET.addTextChangedListener(
        new TextWatcher() {
          public void afterTextChanged(Editable s) {
            try {
              new SimpleDateFormat(s.toString(), Locale.US);
              mDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
            } catch (IllegalArgumentException e) {
              dateFormatET.setError(getString(R.string.date_format_illegal));
              mDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
            }
          }

          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          public void onTextChanged(CharSequence s, int start, int before, int count) {}
        });

    fileNameET = (EditText) view.findViewById(R.id.file_name);
    fileNameET.setText(fileName);
    fileNameET.addTextChangedListener(
        new TextWatcher() {
          public void afterTextChanged(Editable s) {
            int error = 0;
            if (s.toString().length() > 0) {
              if (s.toString().indexOf('/') > -1) {
                error = R.string.slash_forbidden_in_filename;
              }
            } else {
              error = R.string.no_title_given;
            }
            mDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(error == 0);
            if (error != 0) {
              fileNameET.setError(getString(error));
            }
          }

          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          public void onTextChanged(CharSequence s, int start, int before, int count) {}
        });

    notYetExportedCB = (CheckBox) view.findViewById(R.id.export_not_yet_exported);
    deleteCB = (CheckBox) view.findViewById(R.id.export_delete);
    warningTV = (TextView) view.findViewById(R.id.warning_reset);

    String encoding =
        MyApplication.getInstance().getSettings().getString(PREFKEY_EXPORT_ENCODING, "UTF-8");

    ((Spinner) view.findViewById(R.id.Encoding))
        .setSelection(
            Arrays.asList(getResources().getStringArray(R.array.pref_qif_export_file_encoding))
                .indexOf(encoding));

    formatRBCSV = (RadioButton) view.findViewById(R.id.csv);
    String format = MyApplication.PrefKey.EXPORT_FORMAT.getString("QIF");
    if (format.equals("CSV")) {
      formatRBCSV.setChecked(true);
    }

    separatorRBComma = (RadioButton) view.findViewById(R.id.comma);
    char separator =
        (char)
            MyApplication.getInstance()
                .getSettings()
                .getInt(ExportTask.KEY_DECIMAL_SEPARATOR, Utils.getDefaultDecimalSeparator());
    if (separator == ',') {
      separatorRBComma.setChecked(true);
    }

    handleDeletedGroup = (RadioGroup) view.findViewById(R.id.handle_deleted);
    View.OnClickListener radioClickListener =
        new View.OnClickListener() {
          public void onClick(View v) {
            int mappedAction =
                v.getId() == R.id.create_helper
                    ? Account.EXPORT_HANDLE_DELETED_CREATE_HELPER
                    : Account.EXPORT_HANDLE_DELETED_UPDATE_BALANCE;
            if (handleDeletedAction == mappedAction) {
              handleDeletedAction = Account.EXPORT_HANDLE_DELETED_DO_NOTHING;
              handleDeletedGroup.clearCheck();
            } else {
              handleDeletedAction = mappedAction;
            }
          }
        };

    final RadioButton updateBalanceRadioButton =
        (RadioButton) view.findViewById(R.id.update_balance);
    final RadioButton createHelperRadioButton = (RadioButton) view.findViewById(R.id.create_helper);
    updateBalanceRadioButton.setOnClickListener(radioClickListener);
    createHelperRadioButton.setOnClickListener(radioClickListener);

    if (savedInstanceState == null) {
      handleDeletedAction =
          MyApplication.getInstance()
              .getSettings()
              .getInt(
                  ExportTask.KEY_EXPORT_HANDLE_DELETED, Account.EXPORT_HANDLE_DELETED_DO_NOTHING);
      if (handleDeletedAction == Account.EXPORT_HANDLE_DELETED_UPDATE_BALANCE) {
        updateBalanceRadioButton.setChecked(true);
      } else if (handleDeletedAction == Account.EXPORT_HANDLE_DELETED_CREATE_HELPER) {
        createHelperRadioButton.setChecked(true);
      }
    }

    deleteCB.setOnCheckedChangeListener(this);
    if (hasExported) {
      notYetExportedCB.setChecked(true);
      notYetExportedCB.setVisibility(View.VISIBLE);
    }

    warningTV.setText(warningText);
    if (allP) {
      ((TextView) view.findViewById(R.id.file_name_label)).setText(R.string.folder_name);
    }
    AlertDialog.Builder builder =
        new AlertDialog.Builder(ctx)
            .setTitle(allP ? R.string.menu_reset_all : R.string.menu_reset)
            .setView(view)
            .setPositiveButton(android.R.string.ok, this)
            .setNegativeButton(android.R.string.cancel, null);
    if (Build.VERSION.SDK_INT < 11) builder.setIcon(android.R.drawable.ic_dialog_alert);
    else builder.setIconAttribute(android.R.attr.alertDialogIcon);
    mDialog = builder.create();
    return mDialog;
  }