Example #1
1
  /** Sends the current cooldown in action bar. */
  private void sendCooldownBar() {
    if (getPlayer() == null) return;

    StringBuilder stringBuilder = new StringBuilder();

    double currentCooldown = Core.getCustomPlayer(getPlayer()).canUse(type);
    double maxCooldown = type.getCountdown();

    int res = (int) (currentCooldown / maxCooldown * 10);
    ChatColor color;
    for (int i = 0; i < 10; i++) {
      color = ChatColor.RED;
      if (i < 10 - res) color = ChatColor.GREEN;
      stringBuilder.append(color + "â–�");
    }

    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator('.');
    otherSymbols.setPatternSeparator('.');
    final DecimalFormat decimalFormat = new DecimalFormat("0.0", otherSymbols);
    String timeLeft = decimalFormat.format(currentCooldown) + "s";

    PlayerUtils.sendInActionBar(
        getPlayer(), getName() + " §f" + stringBuilder.toString() + " §f" + timeLeft);
  }
Example #2
0
  /** @return Decimal format from EDI configuration */
  private DecimalFormat getDecimalFormatForConfiguration() {
    final DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getInstance();

    final ModelCamelContext context = getContext();
    decimalFormat.setMaximumFractionDigits(
        Integer.valueOf(
            Util.resolvePropertyPlaceholders(context, "edi.decimalformat.maximumFractionDigits")));

    final boolean isGroupingUsed =
        Boolean.valueOf(
            Util.resolvePropertyPlaceholders(context, "edi.decimalformat.isGroupingUsed"));
    decimalFormat.setGroupingUsed(isGroupingUsed);

    final DecimalFormatSymbols decimalFormatSymbols = decimalFormat.getDecimalFormatSymbols();

    if (isGroupingUsed) {
      final char groupingSeparator =
          Util.resolvePropertyPlaceholders(context, "edi.decimalformat.symbol.groupingSeparator")
              .charAt(0);
      decimalFormatSymbols.setGroupingSeparator(groupingSeparator);
    }

    final char decimalSeparator =
        Util.resolvePropertyPlaceholders(context, "edi.decimalformat.symbol.decimalSeparator")
            .charAt(0);
    decimalFormatSymbols.setDecimalSeparator(decimalSeparator);

    decimalFormat.setDecimalFormatSymbols(
        decimalFormatSymbols); // though it seems redundant, it won't be set otherwise for some
                               // reason...

    return decimalFormat;
  }
Example #3
0
  private void logBenchmark(String name, String action, long size, int amount, long expiredNanos) {
    double fraction = (double) expiredNanos / 1000000000;
    double eventsFraction = ((double) amount) / fraction;
    if (logger.isDebugEnabled()) logger.debug("{}: expired={}s", name, fraction);
    if (logger.isDebugEnabled()) logger.debug("{}: events/s={}", name, eventsFraction);
    if (logger.isDebugEnabled()) logger.debug("{}: size={} bytes", name, size);
    long eventAverage = size / amount;

    String formattedAverage =
        HumanReadable.getHumanReadableSize(eventAverage, true, false) + "bytes";
    String formattedLength = HumanReadable.getHumanReadableSize(size, true, false) + "bytes";
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setGroupingSeparator(',');
    symbols.setDecimalSeparator('.');
    DecimalFormat format = new DecimalFormat("#,##0.0#", symbols);
    String formattedEvents = format.format(eventsFraction);
    String formattedFraction = format.format(fraction);
    if (logger.isDebugEnabled()) logger.debug("average={}/event", name, formattedAverage);

    if (logger.isInfoEnabled()) {
      logger.info(
          "|| {} || {} || {} || {} || {} || {} ({}) || {} ||",
          new Object[] {
            name,
            action,
            amount,
            formattedFraction,
            formattedEvents,
            formattedLength,
            size,
            formattedAverage
          });
    }
  }
  /**
   * Metodo para formatear los valores obtenidos del servicio 123.
   *
   * @author FSW IDS :::JMFR:::
   * @since 09/2015.
   * @param d de tipo String valor a formatear.
   * @param dec de tipo int numero de decimales.
   * @param porcentaje de tipo boolean si es de tipo porcentaje.
   * @return el string formateado.
   */
  public String formatearDecimal(String d, int dec, boolean porcentaje) {
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator('.');
    dfs.setGroupingSeparator(',');
    DecimalFormat df = new DecimalFormat("###,##0.00", dfs);
    if (d.length() == dec) {
      d = "0" + d;
      d = d.substring(0, d.length() - dec) + "." + d.substring(d.length() - dec);
    } else if (d.length() < dec) {
      int ceros = 0;
      ceros = dec - d.length() + 1;
      for (int i = 0; i < ceros; i++) {
        d = "0" + d;
      }
      d = d.substring(0, d.length() - dec) + "." + d.substring(d.length() - dec);
    } else {
      d = d.substring(0, d.length() - dec) + "." + d.substring(d.length() - dec);
    }
    if (porcentaje) {
      d = String.valueOf(Double.parseDouble(d));
    } else {
      d = String.valueOf(df.format(Double.parseDouble(d)));
    }

    return d;
  }
  public static DecimalFormat getDecimalFormat() {

    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.ITALIAN);
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator('\0');
    DecimalFormat df = new DecimalFormat("#.00", otherSymbols);
    df.setGroupingUsed(false);
    return df;
  }
 @Override
 protected DecimalFormat initialValue() {
   symbols.setGroupingSeparator(',');
   symbols.setDecimalSeparator('.');
   String pattern = "#,##0.0#";
   DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
   decimalFormat.setParseBigDecimal(true);
   return decimalFormat;
 }
 /** @tests java.text.DecimalFormatSymbols#setGroupingSeparator(char) */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "setGroupingSeparator",
     args = {char.class})
 public void test_setGroupingSeparatorC() {
   dfs.setGroupingSeparator('*');
   assertEquals("Returned incorrect GroupingSeparator symbol", '*', dfs.getGroupingSeparator());
 }
  private void setDefaultValues() {
    pattern = patternDefault;
    decimalSeparator = decimalSeparatorDefault;
    groupingSeparator = groupingSeparatorDefault;

    DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
    dfs.setDecimalSeparator(decimalSeparator);
    dfs.setGroupingSeparator(groupingSeparator);
    decimalFormat = new DecimalFormat(pattern, dfs);
  }
Example #9
0
  public static String numberToCommaNumber(long num) throws Exception {

    DecimalFormat df = new DecimalFormat();
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setGroupingSeparator(',');

    df.setDecimalFormatSymbols(dfs);

    return df.format(num);
  }
Example #10
0
  private String doubleToPrice(double dbl) {
    Locale locale = new Locale("fr", "FR");
    DecimalFormatSymbols sym = new DecimalFormatSymbols(locale);
    sym.setGroupingSeparator('.');
    DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale);

    decimalFormat.applyPattern("##,###.00");
    decimalFormat.setDecimalFormatSymbols(sym);
    return decimalFormat.format(dbl);
  }
Example #11
0
  public static String formatCurrencyValueString(BigDecimal bigDecimal) {
    // RETURNS '$ X.XXX,XX'
    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator(',');
    symbols.setGroupingSeparator('.');

    DecimalFormat formatter = new DecimalFormat("#,##0.00", symbols);
    String formated = formatter.format(bigDecimal);

    return NumberFormat.getCurrencyInstance().getCurrency().getSymbol() + " " + formated;
  }
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater =
        (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    HutangHolder holder = null;

    if (convertView == null) {
      holder = new HutangHolder();
      convertView = inflater.inflate(R.layout.hutang_fragment_list_rows, null);
      holder.nama = (TextView) convertView.findViewById(R.id.hutang_fragment_list_rows_judul);
      holder.tanggal_deadline =
          (TextView) convertView.findViewById(R.id.hutang_fragment_list_rows_tanggal_deadline);
      holder.nominalAtas =
          (TextView) convertView.findViewById(R.id.hutang_fragment_list_rows_nominal_atas);
      holder.nominalBawah =
          (TextView) convertView.findViewById(R.id.hutang_fragment_list_rows_nominal_bawah);
      holder.bar = (ProgressBar) convertView.findViewById(R.id.hutang_fragment_list_rows_bar);
      convertView.setTag(holder);
    } else {
      holder = (HutangHolder) convertView.getTag();
    }

    HutangObject hutangObject = values.get(position);

    // set nama
    holder.nama.setText(hutangObject.nama);

    // set tanggal
    holder.tanggal_deadline.setText(hutangObject.tanggal_deadline);

    //// nominal format
    DecimalFormatSymbols simbol = new DecimalFormatSymbols();
    simbol.setGroupingSeparator('.');
    DecimalFormat customFormat = new DecimalFormat("###,###,###", simbol);

    // set nominal atas dengan jumlah pengeluaran yang telah dikeluarkan
    holder.nominalAtas.setText(customFormat.format(hutangObject.jumlah_cicilan));

    // set nominal bawah dengan jumlah anggaran
    holder.nominalBawah.setText(customFormat.format(hutangObject.jumlah_hutang));

    // set seekbar
    holder.bar.setMax(hutangObject.jumlah_hutang);
    holder.bar.setProgress(hutangObject.jumlah_cicilan);

    // membuat warna zebra di rows
    if (position % 2 == 0) {
      convertView.setBackgroundResource(R.drawable.listview_rows_color_1);
    } else {
      convertView.setBackgroundResource(R.drawable.listview_rows_color_2);
    }

    return convertView;
  }
Example #13
0
 /**
  * Convert a string cash amount to {@link Number}
  *
  * @param input Cash amount as {@link String}
  * @return {@link Number}
  * @throws ParseException
  */
 public static Number parseMoney(String input) throws ParseException {
   // We will use Locale.US on recommendation from:
   // Be wary of the default locale
   // http://developer.android.com/reference/java/util/Locale.html#default_locale
   // otherwise devices with different locales e.g. Locale.FR expect number in different format.
   // like 10,00 while we use 10.00
   DecimalFormatSymbols dfs = new DecimalFormatSymbols();
   dfs.setDecimalSeparator('.');
   dfs.setGroupingSeparator(',');
   return new DecimalFormat("\u20AC#,###.##", dfs).parse(input);
 }
Example #14
0
 public GCodeReader(File gCodeFile) throws IOException {
   if (!(gCodeFile.exists())) {
     throw new IOException("file does not exist");
   }
   rawFile = gCodeFile;
   this.gCodeFile = new BufferedReader(new FileReader(gCodeFile));
   symbols.setDecimalSeparator('.');
   symbols.setGroupingSeparator(',');
   localFormat.setDecimalFormatSymbols(symbols);
   createArea();
 }
Example #15
0
 static {
   FIAT_FORMAT = new DecimalFormat();
   FIAT_FORMAT.setGroupingSize(3);
   FIAT_FORMAT.setGroupingUsed(true);
   FIAT_FORMAT.setMaximumFractionDigits(2);
   FIAT_FORMAT.setMinimumFractionDigits(2);
   DecimalFormatSymbols symbols = FIAT_FORMAT.getDecimalFormatSymbols();
   symbols.setDecimalSeparator('.');
   symbols.setGroupingSeparator(' ');
   FIAT_FORMAT.setDecimalFormatSymbols(symbols);
 }
Example #16
0
 public static double adjDecimalSep(double value) {
   mylogger.log(Level.FINE, "Adjusting valu {0}", new Object[] {value});
   // Bug fix:
   //        For german locale 3.333 => 3,33 which would raise an error
   DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault());
   otherSymbols.setDecimalSeparator('.');
   otherSymbols.setGroupingSeparator(',');
   // Bug fix
   DecimalFormat newFormat = new DecimalFormat();
   newFormat.setDecimalFormatSymbols(otherSymbols);
   return Double.valueOf(newFormat.format(value));
 }
 public AbstractDataMatrixConverter(
     String datatype, Hashtable<String, String> lookup, String investigationURI) {
   this.investigationURI = investigationURI;
   this.lookup = lookup;
   if (datatype != null) {
     int p = datatype.indexOf(prefix);
     if (p >= 0) datatype = datatype.substring(prefix.length());
     this.datatype = datatype;
   }
   nf = new DecimalFormat();
   DecimalFormatSymbols symbols = new DecimalFormatSymbols();
   symbols.setDecimalSeparator('.');
   symbols.setGroupingSeparator(' ');
   nf.setDecimalFormatSymbols(symbols);
 }
  public void setUp() {
    DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
    otherSymbols.setDecimalSeparator('.');
    otherSymbols.setGroupingSeparator(',');
    decimalFormat = new DecimalFormat("#.##", otherSymbols);

    matchingDifferentialBuilder = new MatchingFinder();
    complexityCalculator = new ComplexityCalculator();
    parser = new BicliqueXMLParser();
    renderer = new MatchingPhaseRenderer();

    if (matchingContext == null) {
      matchingContext = new MatchingContext(biclique, cipher, counter);
    }

    loadAndParseXML(xmlPathname);
    matchingContext.biclique = biclique;
    // logger.info("Biclique {0}", biclique);
  }
  @Override
  public void setConfig(String[] params) {
    if (params == null || params.length == 0) {
      setDefaultValues();
      return;
    }
    for (String s : params) {
      String[] keyValue = s.split("=");
      if (keyValue.length > 0) {
        String key = keyValue[0].trim();
        String value;
        if (keyValue.length > 1) {
          value = keyValue[1].trim();
        } else {
          value = "";
        }
        switch (key) {
          case "pattern":
            pattern = value;
            break;
          case "decimalSeparator":
            if (value.length() > 0) {
              decimalSeparator = value.charAt(0);
            }
            break;
          case "groupingSeparator":
            if (value.length() > 0) {
              groupingSeparator = value.charAt(0);
            }
            break;
          default:
            pattern = key;
        }
      }
    }

    DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
    dfs.setDecimalSeparator(decimalSeparator);
    dfs.setGroupingSeparator(groupingSeparator);
    decimalFormat = new DecimalFormat(pattern, dfs);
  }
Example #20
0
  /**
   * Gets the number format if in use.
   *
   * @return the number format, or <tt>null</tt> if not in use
   */
  protected NumberFormat getNumberFormat() {
    if (locale == null) {
      return null;
    }

    NumberFormat format = NumberFormat.getNumberInstance(locale);
    if (format instanceof DecimalFormat) {
      DecimalFormat df = (DecimalFormat) format;
      if (decimalSeparator != null && groupingSeparator != null) {
        if (!decimalSeparator.isEmpty() && !groupingSeparator.isEmpty()) {
          DecimalFormatSymbols dfs = new DecimalFormatSymbols(locale);
          dfs.setDecimalSeparator(decimalSeparator.charAt(0));
          dfs.setGroupingSeparator(groupingSeparator.charAt(0));
          df.setDecimalFormatSymbols(dfs);
        }
      }
      if (!pattern.isEmpty()) {
        df.applyPattern(pattern);
      }
    }
    return format;
  }
Example #21
0
  @Override
  public void bindView(View view, Context context, Cursor cursor) {
    ViewHolder viewHolder = (ViewHolder) view.getTag();

    ShapeDrawable drawable = new ShapeDrawable(new OvalShape());
    drawable.setIntrinsicHeight(24);
    drawable.setIntrinsicWidth(24);
    drawable.getPaint().setColor(Color.parseColor("#BCAAA4"));
    viewHolder.statusView.setBackground(drawable);

    String status =
        cursor.getString(cursor.getColumnIndex(LikeWorkContract.OperationEntry.COLUMN_STATUS));
    viewHolder.statusView.setText(status);

    String name =
        cursor.getString(cursor.getColumnIndex(LikeWorkContract.OperationEntry.COLUMN_NAME));
    viewHolder.nameView.setText(name);

    String catnumber =
        cursor.getString(cursor.getColumnIndex(LikeWorkContract.OperationEntry.COLUMN_CODE_1C));
    viewHolder.catnumberView.setText(catnumber);

    double amount =
        cursor.getDouble(cursor.getColumnIndex(LikeWorkContract.OperationEntry.COLUMN_AMOUNT));
    DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols();
    unusualSymbols.setDecimalSeparator('.');
    unusualSymbols.setGroupingSeparator(' ');

    DecimalFormat myFormatter = new DecimalFormat("###,###.##", unusualSymbols);
    myFormatter.setGroupingSize(3);
    viewHolder.amountView.setText(myFormatter.format(amount));

    double sum =
        cursor.getDouble(cursor.getColumnIndex(LikeWorkContract.OperationEntry.COLUMN_SUM));
    myFormatter = new DecimalFormat("###,##0.00", unusualSymbols);
    myFormatter.setGroupingSize(3);
    viewHolder.sumView.setText(myFormatter.format(sum));
  }
 @Test
 public void norwegianFormat() {
   FieldTypeLong fieldType = new FieldTypeLong();
   DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance();
   decimalFormatSymbols.setDecimalSeparator(',');
   decimalFormatSymbols.setGroupingSeparator('.');
   fieldType.setDecimalFormatSymbols(decimalFormatSymbols);
   for (String value : new String[] {"123.345", "123", "1", "1.234.567", "-1.234.567"}) {
     assertEquals(value, fieldType.format(fieldType.parse(value)));
   }
   long d = -12345678;
   String str = fieldType.format(d);
   assertEquals("-12.345.678", str);
   long number = fieldType.parse("-12345678");
   assertEquals("" + d, "" + number);
   long d2 = fieldType.parse("-12345678");
   assertEquals("" + d, "" + d2);
   long i = -1234;
   long i2 = fieldType.parse("-1234");
   assertEquals("" + i, "" + i2);
   assertEquals("", fieldType.format(fieldType.parse("")));
   assertEquals("", fieldType.format(fieldType.parse(null)));
 }
Example #23
0
  public Gadget(final UUID owner, final GadgetType type) {
    this.permission = type.permission;
    this.type = type;
    this.affectPlayers = type.affectPlayers();
    if (!type.isEnabled()) return;

    this.useTwoInteractMethods = false;
    if (owner != null) {
      this.owner = owner;
      if (Core.getCustomPlayer(getPlayer()).currentGadget != null)
        Core.getCustomPlayer(getPlayer()).removeGadget();
      if (!getPlayer().hasPermission(permission)) {
        getPlayer().sendMessage(MessageManager.getMessage("No-Permission"));
        return;
      }
      DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
      otherSymbols.setDecimalSeparator('.');
      otherSymbols.setGroupingSeparator('.');
      otherSymbols.setPatternSeparator('.');
      final DecimalFormat decimalFormat = new DecimalFormat("0.0", otherSymbols);
      BukkitRunnable runnable =
          new BukkitRunnable() {
            @Override
            public void run() {
              try {
                if (Bukkit.getPlayer(owner) != null
                    && Core.getCustomPlayer(Bukkit.getPlayer(owner)).currentGadget != null
                    && Core.getCustomPlayer(Bukkit.getPlayer(owner)).currentGadget.getType()
                        == type) {
                  onUpdate();
                  if (Core.cooldownInBar) {
                    if (getPlayer().getItemInHand() != null
                        && itemStack != null
                        && getPlayer().getItemInHand().hasItemMeta()
                        && getPlayer().getItemInHand().getItemMeta().hasDisplayName()
                        && getPlayer()
                            .getItemInHand()
                            .getItemMeta()
                            .getDisplayName()
                            .contains(getType().getName())
                        && Core.getCustomPlayer(getPlayer()).canUse(type) != -1) sendCooldownBar();
                    double left = Core.getCustomPlayer(getPlayer()).canUse(type);
                    if (left > -0.1) {
                      String leftRounded = decimalFormat.format(left);
                      double decimalRoundedValue = Double.parseDouble(leftRounded);
                      if (decimalRoundedValue == 0) {
                        PlayerUtils.sendInActionBar(
                            getPlayer(),
                            MessageManager.getMessage("Gadgets.Gadget-Ready-ActionBar")
                                .replace(
                                    "%gadgetname%",
                                    (Core.placeHolderColor)
                                        ? getName()
                                        : Core.filterColor(getName())));
                        getPlayer().playSound(getPlayer().getLocation(), Sound.NOTE_STICKS, 1f, 1f);
                      }
                    }
                  }
                } else {
                  cancel();
                  unregisterListeners();
                }
              } catch (NullPointerException exc) {
                removeItem();
                onClear();
                removeListener();
                getPlayer()
                    .sendMessage(
                        MessageManager.getMessage("Gadgets.Unequip")
                            .replace(
                                "%gadgetname%",
                                (Core.placeHolderColor) ? getName() : Core.filterColor(getName())));
                cancel();
              }
            }
          };
      runnable.runTaskTimerAsynchronously(Core.getPlugin(), 0, 1);
      listener = new GadgetListener(this);
      Core.registerListener(listener);
      Core.registerListener(this);
      if (getPlayer().getInventory().getItem((int) SettingsManager.getConfig().get("Gadget-Slot"))
          != null) {
        getPlayer()
            .getWorld()
            .dropItem(
                getPlayer().getLocation(),
                getPlayer()
                    .getInventory()
                    .getItem((int) SettingsManager.getConfig().get("Gadget-Slot")));
        getPlayer().getInventory().remove((int) SettingsManager.getConfig().get("Gadget-Slot"));
      }
      String d =
          Core.isAmmoEnabled() && getType().requiresAmmo()
              ? "§f§l"
                  + Core.getCustomPlayer(getPlayer()).getAmmo(type.toString().toLowerCase())
                  + " "
              : "";
      itemStack =
          ItemFactory.create(
              type.getMaterial(),
              type.getData(),
              d + getName(),
              MessageManager.getMessage("Gadgets.Lore"));
      getPlayer()
          .getInventory()
          .setItem((int) SettingsManager.getConfig().get("Gadget-Slot"), itemStack);
      getPlayer()
          .sendMessage(
              MessageManager.getMessage("Gadgets.Equip")
                  .replace(
                      "%gadgetname%",
                      (Core.placeHolderColor) ? getName() : Core.filterColor(getName())));
      Core.getCustomPlayer(getPlayer()).currentGadget = this;
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.pestanya_libre);

    // Obtengo el tipo de moneda a tulizar
    singleton_tm = SingletonTipoMoneda.getInstance();
    tipoMoneda = singleton_tm.obtenerTipoMoneda(getApplicationContext());

    animacionBotonPulsado = AnimationUtils.loadAnimation(this, R.anim.animacion_boton_pulsado);
    animacionBotonLevantado = AnimationUtils.loadAnimation(this, R.anim.animacion_boton_levantado);

    rlBarraListadoIngresos =
        (RelativeLayout) findViewById(R.id.relativeLayoutBarraListadoIngresosLibre);
    rlBarraListadoGastos =
        (RelativeLayout) findViewById(R.id.relativeLayoutBarraListadoGastosLibre);
    llListadoIngresos = (LinearLayout) findViewById(R.id.linearLayoutListadoIngresosLibre);
    llListadoGastos = (LinearLayout) findViewById(R.id.linearLayoutListadoGastosLibre);
    ivFlechaListadoIngresos = (ImageView) findViewById(R.id.imageViewListadoIngresosLibre);
    ivFlechaListadoGastos = (ImageView) findViewById(R.id.imageViewListadoGastosLibre);
    tvTotalIngresos = (TextView) findViewById(R.id.textViewTotalIngresosLibre);
    tvTotalGastos = (TextView) findViewById(R.id.textViewTotalGastosLibre);
    tvTotalBalance = (TextView) findViewById(R.id.textViewTotalBalanceLibre);
    ivSearchDate = (ImageView) findViewById(R.id.imageViewSearchFechaLibre);

    // Instancio las fechas
    tvStartDate = (TextView) findViewById(R.id.textViewPestanyaILibreFechaDe);
    tvEndDate = (TextView) findViewById(R.id.textViewPestanyaILibreFechaHasta);
    // Instancio las variables Calendar al día de hoy
    cInicio = Calendar.getInstance();
    cFin = Calendar.getInstance();

    tvStartDate.setText(obtenerFechaInicio());
    tvEndDate.setText(obtenerFechaFin());

    /*
     * Método onClick para plegar/desplegar el listado de Ingresos
     */
    rlBarraListadoIngresos.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Veo cual es el estado del listado de ingresos y luego lo
            // abro o lo cierro
            if (llListadoIngresos.getVisibility() == View.VISIBLE) {
              llListadoIngresos.setVisibility(View.GONE);
              ivFlechaListadoIngresos.setImageDrawable(
                  getResources().getDrawable(android.R.drawable.arrow_down_float));
            } else {
              llListadoIngresos.setVisibility(View.VISIBLE);
              ivFlechaListadoIngresos.setImageDrawable(
                  getResources().getDrawable(android.R.drawable.arrow_up_float));
            }
          }
        });

    /*
     * Método onClick para plegar/desplegar el listado de Gastos
     */
    rlBarraListadoGastos.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // TODO Veo cual es el estado del listado de ingresos y luego lo
            // abro o lo cierro
            if (llListadoGastos.getVisibility() == View.VISIBLE) {
              llListadoGastos.setVisibility(View.GONE);
              ivFlechaListadoGastos.setImageDrawable(
                  getResources().getDrawable(android.R.drawable.arrow_down_float));
            } else {
              llListadoGastos.setVisibility(View.VISIBLE);
              ivFlechaListadoGastos.setImageDrawable(
                  getResources().getDrawable(android.R.drawable.arrow_up_float));
            }
          }
        });

    ivSearchDate.setOnTouchListener(
        new OnTouchListener() {

          @Override
          public boolean onTouch(View v, MotionEvent event) {
            // TODO Método onTouch del botón de buscar en un Rango de Fechas
            switch (event.getAction()) {
              case MotionEvent.ACTION_DOWN:
                tiempoDePulsacionInicial = event.getEventTime();
                ivSearchDate.startAnimation(animacionBotonPulsado);
                break;
              case MotionEvent.ACTION_UP:
                if (event.getEventTime() - tiempoDePulsacionInicial <= 2000) {
                  // lanzo el dialog con la fecha a buscar por el usuario
                  ivSearchDate.startAnimation(animacionBotonLevantado);
                  Dialog dialogo;
                  dialogo = crearDialogoBuscarFecha();
                  dialogo.show();
                }
                // Si he mantenido el botón pulsado más de dos segundos
                // cancelo la operación
                ivSearchDate.startAnimation(animacionBotonLevantado);
                break;
              case MotionEvent.ACTION_CANCEL:
                ivSearchDate.startAnimation(animacionBotonLevantado);
                break;
            }

            return true;
          }
        });

    // Instancio los formateadores de números
    separadores = new DecimalFormatSymbols();
    separadores.setDecimalSeparator(',');
    separadores.setGroupingSeparator('.');
    numeroAFormatear = new DecimalFormat("###,###.##", separadores);

    // Instancio la Base de Datos
    dba = DBAdapter.getInstance(this);

    // Abro la Base de Datos solo en modo lectura
    dba.openREADWRITE();

    // Obtengo los valores de los datos de las Listas de Ingresos y Gastos
    listadoValoresIngresos =
        dba.listadoValoresIngresosPorFecha(obtenerEnteroFechaInicio(), obtenerEnteroFechaFin());
    listadoValoresGastos =
        dba.listadoValoresGastosPorFecha(obtenerEnteroFechaInicio(), obtenerEnteroFechaFin());

    /*
     * Agrupo las Lista por TRIMESTRES y luego cargo los layouts
     */
    cargarLayoutListadoIngresos();
    cargarLayoutListadoGastos();
    /*
     * Calculo los totales y la diferencia y los actualizo en sus variables
     */
    setTotalIngresos(calcularTotalIngresos());
    setTotalGastos(calcularTotalGastos());
    /*
     * Actualizo los TextView que contienen los totales
     */
    actualizarTotales();

    // Pongo los listados plegados
    llListadoIngresos.setVisibility(View.GONE);
    llListadoGastos.setVisibility(View.GONE);

    // Cierro la Base de datos
    dba.close();
  }
 public NumberFormatter(String formatPattern) {
   DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols();
   unusualSymbols.setDecimalSeparator('.');
   unusualSymbols.setGroupingSeparator(',');
   this.format = new DecimalFormat(formatPattern, unusualSymbols);
 }
Example #26
0
 static {
   DecimalFormatSymbols symbols = new DecimalFormatSymbols();
   symbols.setDecimalSeparator('.');
   symbols.setGroupingSeparator(',');
   DF.setDecimalFormatSymbols(symbols);
 }
Example #27
0
  public void guessType() {
    nf = NumberFormat.getInstance();
    df = (DecimalFormat) nf;
    dfs = new DecimalFormatSymbols();
    daf = new SimpleDateFormat();

    daf.setLenient(false);

    // Start with a string...
    type = ValueMetaInterface.TYPE_STRING;

    // If we have no samples, we assume a String...
    if (samples == null) return;

    //////////////////////////////
    // DATES
    //////////////////////////////

    // See if all samples can be transformed into a date...
    int datefmt_cnt = date_formats.length;
    boolean datefmt[] = new boolean[date_formats.length];
    for (int i = 0; i < date_formats.length; i++) {
      datefmt[i] = true;
    }
    int datenul = 0;

    for (int i = 0; i < samples.length; i++) {
      if (samples[i].length() > 0 && samples[i].equalsIgnoreCase(nullString)) {
        datenul++;
      } else
        for (int x = 0; x < date_formats.length; x++) {
          if (samples[i] == null || Const.onlySpaces(samples[i]) || samples[i].length() == 0) {
            datefmt[x] = false;
            datefmt_cnt--;
          }

          if (datefmt[x]) {
            try {
              daf.applyPattern(date_formats[x]);
              Date date = daf.parse(samples[i]);

              Calendar cal = Calendar.getInstance();
              cal.setTime(date);
              int year = cal.get(Calendar.YEAR);

              if (year < 1800 || year > 2200) {
                datefmt[x] = false; // Don't try it again in the future.
                datefmt_cnt--; // One less that works..
              }
            } catch (Exception e) {
              datefmt[x] = false; // Don't try it again in the future.
              datefmt_cnt--; // One less that works..
            }
          }
        }
    }

    // If it is a date, copy info over to the format etc. Then return with the info.
    // If all samples where NULL values, we can't really decide what the type is.
    // So we're certainly not going to take a date, just take a string in that case.
    if (datefmt_cnt > 0 && datenul != samples.length) {
      int first = -1;
      for (int i = 0; i < date_formats.length && first < 0; i++) {
        if (datefmt[i]) first = i;
      }

      type = ValueMetaInterface.TYPE_DATE;
      format = date_formats[first];

      return;
    }

    //////////////////////////////
    // NUMBERS
    //////////////////////////////

    boolean isnumber = true;

    // Set decimal symbols to default
    decimalSymbol = "" + dfs.getDecimalSeparator();
    groupSymbol = "" + dfs.getGroupingSeparator();

    boolean numfmt[] = new boolean[number_formats.length];
    int maxprecision[] = new int[number_formats.length];
    for (int i = 0; i < numfmt.length; i++) {
      numfmt[i] = true;
      maxprecision[i] = -1;
    }
    int numfmt_cnt = number_formats.length;
    int numnul = 0;

    for (int i = 0; i < samples.length && isnumber; i++) {
      boolean contains_dot = false;
      boolean contains_comma = false;

      String field = samples[i];

      if (field.length() > 0 && field.equalsIgnoreCase(nullString)) {
        numnul++;
      } else {
        for (int x = 0; x < field.length() && isnumber; x++) {
          char ch = field.charAt(x);
          if (!Character.isDigit(ch)
              && ch != '.'
              && ch != ','
              && (ch != '-' || x > 0)
              && ch != 'E'
              && ch != 'e' // exponential
          ) {
            isnumber = false;
            numfmt_cnt = 0;
          } else {
            if (ch == '.') {
              contains_dot = true;
              // containsDot  = true;
            }
            if (ch == ',') {
              contains_comma = true;
              // containsComma  = true;
            }
          }
        }
        // If it's still a number, try to parse it as a double
        if (isnumber) {
          if (contains_dot && !contains_comma) // American style 174.5
          {
            dfs.setDecimalSeparator('.');
            decimalSymbol = ".";
            dfs.setGroupingSeparator(',');
            groupSymbol = ",";
          } else if (!contains_dot && contains_comma) // European style 174,5
          {
            dfs.setDecimalSeparator(',');
            decimalSymbol = ",";
            dfs.setGroupingSeparator('.');
            groupSymbol = ".";
          } else if (contains_dot && contains_comma) // Both appear!
          {
            // What's the last occurance: decimal point!
            int idx_dot = field.indexOf('.');
            int idx_com = field.indexOf(',');
            if (idx_dot > idx_com) {
              dfs.setDecimalSeparator('.');
              decimalSymbol = ".";
              dfs.setGroupingSeparator(',');
              groupSymbol = ",";
            } else {
              dfs.setDecimalSeparator(',');
              decimalSymbol = ",";
              dfs.setGroupingSeparator('.');
              groupSymbol = ".";
            }
          }

          // Try the remaining possible number formats!
          for (int x = 0; x < number_formats.length; x++) {
            if (numfmt[x]) {
              boolean islong = true;

              try {
                int prec = -1;
                // Try long integers first....
                if (!contains_dot && !contains_comma) {
                  try {
                    Long.parseLong(field);
                    prec = 0;
                  } catch (Exception e) {
                    islong = false;
                  }
                }

                if (!islong) // Try the double
                {
                  df.setDecimalFormatSymbols(dfs);
                  df.applyPattern(number_formats[x]);

                  double d = df.parse(field).doubleValue();
                  prec = guessPrecision(d);
                }
                if (prec > maxprecision[x]) maxprecision[x] = prec;
              } catch (Exception e) {
                numfmt[x] = false; // Don't try it again in the future.
                numfmt_cnt--; // One less that works..
              }
            }
          }
        }
      }
    }

    // Still a number?  Grab the result and return.
    // If all sample strings are empty or represent NULL values we can't take a number as type.
    if (numfmt_cnt > 0 && numnul != samples.length) {
      int first = -1;
      for (int i = 0; i < number_formats.length && first < 0; i++) {
        if (numfmt[i]) first = i;
      }

      type = ValueMetaInterface.TYPE_NUMBER;
      format = number_formats[first];
      precision = maxprecision[first];

      // Wait a minute!!! What about Integers?
      // OK, only if the precision is 0 and the length <19 (java long integer)
      /*
      if (length<19 && precision==0 && !containsDot && !containsComma)
      {
      	type=ValueMetaInterface.TYPE_INTEGER;
      	decimalSymbol="";
      	groupSymbol="";
      }
               */

      return;
    }

    //
    // Assume it's a string...
    //
    type = ValueMetaInterface.TYPE_STRING;
    format = "";
    precision = -1;
    decimalSymbol = "";
    groupSymbol = "";
    currencySymbol = "";
  }