Example usage for java.text DecimalFormat applyPattern

List of usage examples for java.text DecimalFormat applyPattern

Introduction

In this page you can find the example usage for java.text DecimalFormat applyPattern.

Prototype

public void applyPattern(String pattern) 

Source Link

Document

Apply the given pattern to this Format object.

Usage

From source file:fr.paris.lutece.portal.web.upload.UploadFilter.java

/**
 *
 * @return the size of the request to display in the error message
 *//*  w  ww.  ja va 2s.  co m*/
private String getDisplaySize() {
    long lSizeMax = getRequestSizeMax();
    DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance();
    decimalFormat.applyPattern("#");

    String strMessage = (lSizeMax >= KILO_BYTE) ? (String.valueOf(lSizeMax / KILO_BYTE))
            : (decimalFormat.format(lSizeMax / KILO_BYTE));

    return strMessage;
}

From source file:org.jbpm.formModeler.core.processing.fieldHandlers.RangeInputTextFieldHandlerFormatter.java

protected Object applyPattern(Field field, Object value) {
    if (value != null) {
        if (value instanceof Double) {
            String pattern = field.getPattern();
            if (pattern == null || "".equals(pattern))
                pattern = field.getFieldType().getPattern();
            if (pattern != null && !"".equals(value)) {
                DecimalFormat nf = (DecimalFormat) DecimalFormat.getInstance(getLocale());
                nf.applyPattern(pattern);
                value = nf.format(((Double) value).doubleValue());
            }/*w  w w  .j  a  v  a2  s  .c om*/
        }
        if (value instanceof Object[]) {
            String pattern = field.getPattern();
            if (pattern == null || "".equals(pattern))
                pattern = field.getFieldType().getPattern();
            if (pattern != null) {
                DecimalFormat nf = (DecimalFormat) DecimalFormat.getInstance(getLocale());
                nf.applyPattern(pattern);
                Object[] values = (Object[]) value;
                for (int i = 0; i < values.length; i++) {
                    Object object = values[i];
                    if (object != null && object instanceof Double) {
                        Double aDouble = (Double) object;
                        values[i] = nf.format(aDouble.doubleValue());
                    }
                }
                value = values;
            }
        }
    }
    return value;
}

From source file:chibi.gemmaanalysis.CorrelationAnalysisCLI.java

@Override
protected Exception doWork(String[] args) {
    Exception exc = processCommandLine(args);
    if (exc != null) {
        return exc;
    }// www  .j a v  a  2s . com

    Collection<Gene> queryGenes, targetGenes;
    try {
        queryGenes = getQueryGenes();
        targetGenes = getTargetGenes();
    } catch (IOException e) {
        return e;
    }

    // calculate matrices
    CoexpressionMatrices matrices = coexpressionAnalysisService.calculateCoexpressionMatrices(
            expressionExperiments, queryGenes, targetGenes, filterConfig, CorrelationMethod.SPEARMAN);
    DenseDouble3dMatrix<Gene, Gene, BioAssaySet> correlationMatrix = matrices.getCorrelationMatrix();
    // DenseDoubleMatrix3DNamed sampleSizeMatrix = matrices
    // .getSampleSizeMatrix();

    // DoubleMatrixNamed maxCorrelationMatrix = coexpressionAnalysisService
    // .getMaxCorrelationMatrix(correlationMatrix, kMax);
    // DoubleMatrixNamed pValMatrix = coexpressionAnalysisService
    // .calculateMaxCorrelationPValueMatrix(maxCorrelationMatrix,
    // kMax, ees);
    // DoubleMatrixNamed effectSizeMatrix = coexpressionAnalysisService
    // .calculateEffectSizeMatrix(correlationMatrix, sampleSizeMatrix);

    // get row/col name maps
    Map<Gene, String> geneNameMap = matrices.getGeneNameMap();
    Map<ExpressionExperiment, String> eeNameMap = matrices.getEeNameMap();

    DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    formatter.applyPattern("0.0000");
    DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
    symbols.setNaN("NaN");
    formatter.setDecimalFormatSymbols(symbols);

    try {
        MatrixWriter<Gene, Gene> matrixOut;
        matrixOut = new MatrixWriter<Gene, Gene>(outFilePrefix + ".corr.txt", formatter);
        matrixOut.setSliceNameMap(eeNameMap);
        matrixOut.setRowNameMap(geneNameMap);
        matrixOut.setColNameMap(geneNameMap);
        matrixOut.writeMatrix(correlationMatrix, false);

        try (PrintWriter out = new PrintWriter(new FileWriter(outFilePrefix + ".corr.row_names.txt"));) {
            List<Gene> rows = correlationMatrix.getRowNames();
            for (Gene row : rows) {
                out.println(row);
            }
        }

        try (PrintWriter out = new PrintWriter(new FileWriter(outFilePrefix + ".corr.col_names.txt"));) {
            Collection<BioAssaySet> cols = correlationMatrix.getSliceNames();
            for (BioAssaySet bas : cols) {
                ExpressionExperiment ee = (ExpressionExperiment) bas;
                out.println(ee.getShortName());
            }
        }
    } catch (IOException e) {
        return e;
    }
    // out = new MatrixWriter(outFilePrefix + ".max_corr.txt", formatter,
    // geneNameMap, geneNameMap);
    // out.writeMatrix(maxCorrelationMatrix, true);
    // out.close();
    //
    // out = new MatrixWriter(outFilePrefix + ".max_corr.pVal.txt",
    // formatter, geneNameMap, geneNameMap);
    // out.writeMatrix(pValMatrix, true);
    // out.close();
    //
    // out = new MatrixWriter(outFilePrefix + ".effect_size.txt",
    // formatter, geneNameMap, geneNameMap);
    // out.writeMatrix(effectSizeMatrix, true);
    // out.close();

    return null;
}

From source file:playground.jbischoff.carsharing.data.VBBRouteCatcher.java

private void run(Coord from, Coord to, long departureTime) {

    Locale locale = new Locale("en", "UK");
    String pattern = "###.000000";

    DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(locale);
    df.applyPattern(pattern);

    // Construct data
    //X&Y coordinates must be exactly 8 digits, otherwise no proper result is given. They are swapped (x = long, y = lat)

    //Verbindungen 1-n bekommen; Laufweg, Reisezeit & Umstiege ermitteln
    String text = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"
            + "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"
            + "<ReqC accessId=\"JBischoff2486b558356fa9b81b1rzum\" ver=\"1.1\" requestId=\"7\" prod=\"SPA\" lang=\"DE\">"
            + "<ConReq>" + "<ReqT date=\"" + VBBDAY.format(departureTime) + "\" time=\""
            + VBBTIME.format(departureTime) + "\">" + "</ReqT>" + "<RFlags b=\"0\" f=\"1\" >" + "</RFlags>"
            + "<Start>" + "<Coord name=\"START\" x=\"" + df.format(from.getY()).replace(".", "") + "\" y=\""
            + df.format(from.getX()).replace(".", "") + "\" type=\"WGS84\"/>"
            + "<Prod  prod=\"1111000000000000\" direct=\"0\" sleeper=\"0\" couchette=\"0\" bike=\"0\"/>"
            + "</Start>" + "<Dest>" + "<Coord name=\"ZIEL\" x=\"" + df.format(to.getY()).replace(".", "")
            + "\" y=\"" + df.format(to.getX()).replace(".", "") + "\" type=\"WGS84\"/>" + "</Dest>"
            + "</ConReq>" + "</ReqC>";
    PostMethod post = new PostMethod("http://demo.hafas.de/bin/pub/vbb/extxml.exe/");
    post.setRequestBody(text);//from   w ww.  ja  v  a2  s  . com
    post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
    HttpClient httpclient = new HttpClient();
    try {

        int result = httpclient.executeMethod(post);

        // Display status code
        //                     System.out.println("Response status code: " + result);

        // Display response
        //                     System.out.println("Response body: ");
        //                     System.out.println(post.getResponseBodyAsString());

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(post.getResponseBodyAsStream());

        if (writeOutput) {
            BufferedWriter writer = IOUtils.getBufferedWriter(filename);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            //initialize StreamResult with File object to save to file
            StreamResult res = new StreamResult(writer);
            DOMSource source = new DOMSource(document);
            transformer.transform(source, res);
            writer.flush();
            writer.close();

        }

        Node connectionList = document.getFirstChild().getFirstChild().getFirstChild();
        NodeList connections = connectionList.getChildNodes();
        int amount = connections.getLength();
        for (int i = 0; i < amount; i++) {
            Node connection = connections.item(i);
            Node overview = connection.getFirstChild();
            ;

            while (!overview.getNodeName().equals("Overview")) {
                overview = overview.getNextSibling();
            }

            System.out.println(overview.getChildNodes().item(3).getTextContent());
            int transfers = Integer.parseInt(overview.getChildNodes().item(3).getTextContent());
            String time = overview.getChildNodes().item(4).getFirstChild().getTextContent().substring(3);
            System.out.println(time);
            Date rideTime = VBBDATE.parse(time);
            int seconds = rideTime.getHours() * 3600 + rideTime.getMinutes() * 60 + rideTime.getSeconds();
            System.out.println(seconds + "s; transfers: " + transfers);
            if (seconds < this.bestRideTime) {
                this.bestRideTime = seconds;
                this.bestTransfers = transfers;
            }
        }
    } catch (Exception e) {
        this.bestRideTime = -1;
        this.bestTransfers = -1;
    }

    finally {
        // Release current connection to the connection pool 
        // once you are done
        post.releaseConnection();
        post.abort();

    }

}

From source file:br.com.wjaa.pagseguro.ws.PagSeguroWSImpl.java

private BigDecimal createBigDecimal(double value) {
    DecimalFormat df = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.ENGLISH);
    df.applyPattern("#,##0.00");
    String format = df.format(value);
    BigDecimal bigValue = new BigDecimal(format);

    return bigValue;

}

From source file:name.gumartinm.weather.information.notification.NotificationIntentService.java

private void showNotification(final Current current, final WeatherLocation weatherLocation) {
    // 1. Update units of measurement.
    final UnitsConversor tempUnitsConversor = new TempUnitsConversor(this.getApplicationContext());

    // 2. Formatters
    final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    tempFormatter.applyPattern("###.##");

    // 3. Prepare data for RemoteViews.
    String tempMax = "";
    if (current.getMain().getTemp_max() != null) {
        double conversion = (Double) current.getMain().getTemp_max();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMax = tempFormatter.format(conversion) + tempUnitsConversor.getSymbol();
    }/*from  w  ww  . j  ava  2s. c  om*/
    String tempMin = "";
    if (current.getMain().getTemp_min() != null) {
        double conversion = (Double) current.getMain().getTemp_min();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMin = tempFormatter.format(conversion) + tempUnitsConversor.getSymbol();
    }
    Bitmap picture;
    if ((current.getWeather().size() > 0) && (current.getWeather().get(0).getIcon() != null)
            && (IconsList.getIcon(current.getWeather().get(0).getIcon()) != null)) {
        final String icon = current.getWeather().get(0).getIcon();
        picture = BitmapFactory.decodeResource(this.getResources(),
                IconsList.getIcon(icon).getResourceDrawable());
    } else {
        picture = BitmapFactory.decodeResource(this.getResources(), R.drawable.weather_severe_alert);
    }
    final String city = weatherLocation.getCity();
    final String country = weatherLocation.getCountry();

    // 4. Insert data in RemoteViews.
    final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(),
            R.layout.weather_notification);
    remoteView.setImageViewBitmap(R.id.weather_notification_image, picture);
    remoteView.setTextViewText(R.id.weather_notification_temperature_max, tempMax);
    remoteView.setTextViewText(R.id.weather_notification_temperature_min, tempMin);
    remoteView.setTextViewText(R.id.weather_notification_city, city);
    remoteView.setTextViewText(R.id.weather_notification_country, country);

    // 5. Activity launcher.
    final Intent resultIntent = new Intent(this.getApplicationContext(), MainTabsActivity.class);
    // The PendingIntent to launch our activity if the user selects this notification.
    // The stack builder object will contain an artificial back stack for the started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext());
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(MainTabsActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    final PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);

    final NotificationManagerCompat notificationManager = NotificationManagerCompat
            .from(this.getApplicationContext());

    // 6. Create notification.
    final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
            this.getApplicationContext()).setContent(remoteView).setSmallIcon(R.drawable.ic_launcher)
                    .setAutoCancel(true).setLocalOnly(true).setWhen(System.currentTimeMillis())
                    .setContentIntent(resultPendingIntent).setPriority(NotificationCompat.PRIORITY_DEFAULT);

    final Notification notification = notificationBuilder.build();
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Send the notification.
    // Sets an ID for the notification, so it can be updated (just in case)
    int notifyID = 1;
    notificationManager.notify(notifyID, notification);
}

From source file:org.n52.oxf.render.sos.ProportionalCircleMapRenderer.java

private Image renderLegend(ObservationSeriesCollection obsValues, String observedProperty) {

    double lowestValue = (Double) obsValues.getMinimum(0);
    double highestValue = (Double) obsValues.getMaximum(0);

    double classDistance = (highestValue - lowestValue) / (NUMBER_OF_CLASSES - 2);
    int dotSizeDistance = (MAX_DOT_SIZE - MIN_DOT_SIZE) / (NUMBER_OF_CLASSES - 2);

    BufferedImage image = new BufferedImage(LEGEND_WIDTH, LEGEND_HEIGHT, BufferedImage.TYPE_INT_RGB);

    Graphics2D g = image.createGraphics();

    // draw white background:
    g.setColor(Color.WHITE);/*from  w  w  w . ja  va 2s  . c om*/
    g.fillRect(0, 0, LEGEND_WIDTH, LEGEND_HEIGHT);

    // draw information:
    observedProperty = observedProperty.split(":")[observedProperty.split(":").length - 1];
    g.setColor(Color.BLACK);
    g.drawString("Observed Property:   '" + observedProperty + "'", 25, 25);

    for (int i = 1; i <= NUMBER_OF_CLASSES; i++) {
        // draw text:
        int x_stringLocation = 100;
        int y_location = i * 60;
        g.setColor(Color.BLACK);

        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(Locale.GERMAN);
        df.applyPattern("#,###,##0.00");

        double lowerBorder = lowestValue + classDistance * (i - 1);
        double upperBorder = lowestValue + classDistance * i;

        g.drawString(i + ". class: " + df.format(lowerBorder) + " - " + df.format(upperBorder),
                x_stringLocation, y_location + 10);

        // draw symbol:
        int x_symbolLocation = 30;
        g.setColor(POINT_INNER_COLOR);
        g.fillOval(x_symbolLocation, y_location, i * dotSizeDistance, i * dotSizeDistance);
    }

    return image;
}

From source file:org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler.java

/**
 * Builds a correct paramValue for a given inputValue.
 *
 * @param value   Object value to build its paramValue
 * @param pattern pattern to apply if any
 * @return a String[] with the paramValue on it or null if the value received is null
 *//*from   w  ww . j  a va2 s  .co m*/
protected String[] buildParamValue(Object value, String pattern) {
    String[] result = null;
    if (value != null && Arrays.asList(getCompatibleClassNames()).contains(value.getClass().getName())) {
        if (pattern != null && !"".equals(pattern)) { // Float and Double fields type always have pattern
            try {
                DecimalFormat df = (DecimalFormat) DecimalFormat
                        .getInstance(new Locale(LocaleManager.currentLang()));
                if (value instanceof BigDecimal)
                    df.setParseBigDecimal(true);
                df.applyPattern(pattern);

                if (value instanceof Float) {
                    value = df.format((((Float) value).floatValue()));
                } else if (value instanceof BigDecimal) {
                    value = df.format(value);
                } else {
                    value = df.format((((Double) value)).doubleValue());
                }
            } catch (Exception e) {
                if (value instanceof Short || value instanceof Integer || value instanceof Long
                        || value instanceof BigInteger) {
                    return buildParamValue(value, null);
                }
                return result;
            }
        }
        result = new String[] { value.toString() };
    }
    return result;
}

From source file:name.gumartinm.weather.information.fragment.specific.SpecificFragment.java

private void updateUI(final Forecast forecastWeatherData, final int chosenDay) {

    // 1. Update units of measurement.
    final UnitsConversor tempUnitsConversor = new TempUnitsConversor(
            this.getActivity().getApplicationContext());
    final UnitsConversor windConversor = new WindUnitsConversor(this.getActivity().getApplicationContext());
    final UnitsConversor pressureConversor = new PressureUnitsConversor(
            this.getActivity().getApplicationContext());

    // 2. Formatters
    final DecimalFormat numberFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    numberFormatter.applyPattern("###.##");

    // 3. Prepare data for UI.
    final name.gumartinm.weather.information.model.forecastweather.List forecast = forecastWeatherData.getList()
            .get((chosenDay));/*from  w  w  w  .ja  va2  s . c  o m*/

    final SimpleDateFormat dayFormatter = new SimpleDateFormat("EEEE - MMM d", Locale.US);
    final Calendar calendar = Calendar.getInstance();
    final Long forecastUNIXDate = (Long) forecast.getDt();
    calendar.setTimeInMillis(forecastUNIXDate * 1000L);
    final Date date = calendar.getTime();

    String tempMax = "";
    if (forecast.getTemp().getMax() != null) {
        double conversion = (Double) forecast.getTemp().getMax();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMax = numberFormatter.format(conversion) + tempUnitsConversor.getSymbol();
    }
    String tempMin = "";
    if (forecast.getTemp().getMin() != null) {
        double conversion = (Double) forecast.getTemp().getMin();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMin = numberFormatter.format(conversion) + tempUnitsConversor.getSymbol();
    }
    Bitmap picture;
    if ((forecast.getWeather().size() > 0) && (forecast.getWeather().get(0).getIcon() != null)
            && (IconsList.getIcon(forecast.getWeather().get(0).getIcon()) != null)) {
        final String icon = forecast.getWeather().get(0).getIcon();
        picture = BitmapFactory.decodeResource(this.getResources(),
                IconsList.getIcon(icon).getResourceDrawable());
    } else {
        picture = BitmapFactory.decodeResource(this.getResources(), R.drawable.weather_severe_alert);
    }

    String description = this.getString(R.string.text_field_description_when_error);
    if (forecast.getWeather().size() > 0) {
        description = forecast.getWeather().get(0).getDescription();
    }

    String humidityValue = "";
    if (forecast.getHumidity() != null) {
        final double conversion = (Double) forecast.getHumidity();
        humidityValue = numberFormatter.format(conversion);
    }
    String pressureValue = "";
    if (forecast.getPressure() != null) {
        double conversion = (Double) forecast.getPressure();
        conversion = pressureConversor.doConversion(conversion);
        pressureValue = numberFormatter.format(conversion);
    }
    String windValue = "";
    if (forecast.getSpeed() != null) {
        double conversion = (Double) forecast.getSpeed();
        conversion = windConversor.doConversion(conversion);
        windValue = numberFormatter.format(conversion);
    }
    String rainValue = "";
    if (forecast.getRain() != null) {
        final double conversion = (Double) forecast.getRain();
        rainValue = numberFormatter.format(conversion);
    }
    String cloudsValue = "";
    if (forecast.getRain() != null) {
        final double conversion = (Double) forecast.getClouds();
        cloudsValue = numberFormatter.format(conversion);
    }

    final String tempSymbol = tempUnitsConversor.getSymbol();
    String tempDay = "";
    if (forecast.getTemp().getDay() != null) {
        double conversion = (Double) forecast.getTemp().getDay();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempDay = numberFormatter.format(conversion) + tempSymbol;
    }
    String tempMorn = "";
    if (forecast.getTemp().getMorn() != null) {
        double conversion = (Double) forecast.getTemp().getMorn();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMorn = numberFormatter.format(conversion) + tempSymbol;
    }
    String tempEve = "";
    if (forecast.getTemp().getEve() != null) {
        double conversion = (Double) forecast.getTemp().getEve();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempEve = numberFormatter.format(conversion) + tempSymbol;
    }
    String tempNight = "";
    if (forecast.getTemp().getNight() != null) {
        double conversion = (Double) forecast.getTemp().getNight();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempNight = numberFormatter.format(conversion) + tempSymbol;
    }

    // 4. Update UI.
    this.getActivity().getActionBar().setSubtitle(dayFormatter.format(date).toUpperCase());

    final TextView tempMaxView = (TextView) getActivity().findViewById(R.id.weather_specific_temp_max);
    tempMaxView.setText(tempMax);
    final TextView tempMinView = (TextView) getActivity().findViewById(R.id.weather_specific_temp_min);
    tempMinView.setText(tempMin);
    final ImageView pictureView = (ImageView) getActivity().findViewById(R.id.weather_specific_picture);
    pictureView.setImageBitmap(picture);

    final TextView descriptionView = (TextView) getActivity().findViewById(R.id.weather_specific_description);
    descriptionView.setText(description);

    final TextView humidityValueView = (TextView) getActivity()
            .findViewById(R.id.weather_specific_humidity_value);
    humidityValueView.setText(humidityValue);
    ((TextView) getActivity().findViewById(R.id.weather_specific_pressure_value)).setText(pressureValue);
    ((TextView) getActivity().findViewById(R.id.weather_specific_pressure_units))
            .setText(pressureConversor.getSymbol());
    ((TextView) getActivity().findViewById(R.id.weather_specific_wind_value)).setText(windValue);
    ((TextView) getActivity().findViewById(R.id.weather_specific_wind_units))
            .setText(windConversor.getSymbol());
    final TextView rainValueView = (TextView) getActivity().findViewById(R.id.weather_specific_rain_value);
    rainValueView.setText(rainValue);
    final TextView cloudsValueView = (TextView) getActivity().findViewById(R.id.weather_specific_clouds_value);
    cloudsValueView.setText(cloudsValue);

    final TextView tempDayView = (TextView) getActivity().findViewById(R.id.weather_specific_day_temperature);
    tempDayView.setText(tempDay);
    final TextView tempMornView = (TextView) getActivity().findViewById(R.id.weather_specific_morn_temperature);
    tempMornView.setText(tempMorn);
    final TextView tempEveView = (TextView) getActivity().findViewById(R.id.weather_specific_eve_temperature);
    tempEveView.setText(tempEve);
    final TextView tempNightView = (TextView) getActivity()
            .findViewById(R.id.weather_specific_night_temperature);
    tempNightView.setText(tempNight);
}

From source file:name.gumartinm.weather.information.fragment.overview.OverviewFragment.java

private void updateUI(final Forecast forecastWeatherData) {

    // 1. Update units of measurement.
    final UnitsConversor tempUnitsConversor = new TempUnitsConversor(
            this.getActivity().getApplicationContext());

    // 2. Update number day forecast.
    final SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this.getActivity().getApplicationContext());
    final String keyPreference = this.getResources().getString(R.string.weather_preferences_day_forecast_key);
    final String dayForecast = sharedPreferences.getString(keyPreference, "5");
    final int mDayForecast = Integer.valueOf(dayForecast);

    // 3. Formatters
    final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    tempFormatter.applyPattern("###.##");
    final SimpleDateFormat dayNameFormatter = new SimpleDateFormat("EEE", Locale.US);
    final SimpleDateFormat monthAndDayNumberormatter = new SimpleDateFormat("MMM d", Locale.US);

    // 4. Prepare data for UI.
    final List<OverviewEntry> entries = new ArrayList<OverviewEntry>();
    final OverviewAdapter adapter = new OverviewAdapter(this.getActivity(), R.layout.weather_main_entry_list);
    final Calendar calendar = Calendar.getInstance();
    int count = mDayForecast;
    for (final name.gumartinm.weather.information.model.forecastweather.List forecast : forecastWeatherData
            .getList()) {/*w  w w  . j ava 2  s.  c  o  m*/

        Bitmap picture;

        if ((forecast.getWeather().size() > 0) && (forecast.getWeather().get(0).getIcon() != null)
                && (IconsList.getIcon(forecast.getWeather().get(0).getIcon()) != null)) {
            final String icon = forecast.getWeather().get(0).getIcon();
            picture = BitmapFactory.decodeResource(this.getResources(),
                    IconsList.getIcon(icon).getResourceDrawable());
        } else {
            picture = BitmapFactory.decodeResource(this.getResources(), R.drawable.weather_severe_alert);
        }

        final Long forecastUNIXDate = (Long) forecast.getDt();
        calendar.setTimeInMillis(forecastUNIXDate * 1000L);
        final Date dayTime = calendar.getTime();
        final String dayTextName = dayNameFormatter.format(dayTime);
        final String monthAndDayNumberText = monthAndDayNumberormatter.format(dayTime);

        Double maxTemp = null;
        if (forecast.getTemp().getMax() != null) {
            maxTemp = (Double) forecast.getTemp().getMax();
            maxTemp = tempUnitsConversor.doConversion(maxTemp);
        }

        Double minTemp = null;
        if (forecast.getTemp().getMin() != null) {
            minTemp = (Double) forecast.getTemp().getMin();
            minTemp = tempUnitsConversor.doConversion(minTemp);
        }

        if ((maxTemp != null) && (minTemp != null)) {
            // TODO i18n?
            final String tempSymbol = tempUnitsConversor.getSymbol();
            entries.add(new OverviewEntry(dayTextName, monthAndDayNumberText,
                    tempFormatter.format(maxTemp) + tempSymbol, tempFormatter.format(minTemp) + tempSymbol,
                    picture));
        }

        count = count - 1;
        if (count == 0) {
            break;
        }
    }

    // 5. Update UI.
    adapter.addAll(entries);
    this.setListAdapter(adapter);
}