F32


Source link: https://github.com/igormatyushkin014/F32-for-Android

F32

At a Glance

F32 is a library for temperature conversions and weather forecasts. It includes wrapper for OpenWeatherMap API and provides developer with super-simple way to obtain weather information by geographic coordinates, city name and ZIP code.

Components included in F32:

How To Get Started

  • Copy content from Source/F32ForAndroid/f32/src/main/java/com/visuality/f32 folder to your project.

or

  • Use gradle dependency: compile 'com.visuality.f32forandroid:f32:2.3.1'

Requirements

  • Android Studio 2.3 or later
  • Java 7 or later
  • Android 4.0.3 or later

Usage

Preparations For Weather Requests

Before making requests for weather forecast, sign up here and get API key (if you don't already have one).

Also, don't forget to append INTERNET permission to your application's manifest file:

<uses-permission android:name="android.permission.INTERNET"/>

Current weather

Below you can see how to make request for current weather:

/*  * Request for current weather using coordinates.  */  new WeatherManager("INSERT_YOUR_API_KEY_HERE").getCurrentWeatherByCoordinates(

47.2257, // latitude

38.9383, // longitude

new WeatherManager.CurrentWeatherHandler() {

 @Override

 public void onReceivedCurrentWeather(WeatherManager manager, Weather weather) {

  // Handle current weather information

 
}

  @Override

 public void onFailedToReceiveCurrentWeather(WeatherManager manager) {

  // Handle error

 
}

}
 );
  /*  * Request for current weather using city name.  */  new WeatherManager("INSERT_YOUR_API_KEY_HERE").getCurrentWeatherByCityName(

"New York", // city name

new WeatherManager.CurrentWeatherHandler() {

 @Override

 public void onReceivedCurrentWeather(WeatherManager manager, Weather weather) {

  // Handle current weather information

 
}

  @Override

 public void onFailedToReceiveCurrentWeather(WeatherManager manager) {

  // Handle error

 
}

}
 );
  /*  * Request for current weather using city ID.  */  new WeatherManager("INSERT_YOUR_API_KEY_HERE").getCurrentWeatherByCityId(

2172797, // city id

new WeatherManager.CurrentWeatherHandler() {

 @Override

 public void onReceivedCurrentWeather(WeatherManager manager, Weather weather) {

  // Handle current weather information

 
}

  @Override

 public void onFailedToReceiveCurrentWeather(WeatherManager manager) {

  // Handle error

 
}

}
 );
  /*  * Request for current weather using ZIP code.  */  new WeatherManager("INSERT_YOUR_API_KEY_HERE").getCurrentWeatherByZipCode(

"94040", // ZIP code

"us", // country code

new WeatherManager.CurrentWeatherHandler() {

 @Override

 public void onReceivedCurrentWeather(WeatherManager manager, Weather weather) {

  // Handle current weather information

 
}

  @Override

 public void onFailedToReceiveCurrentWeather(WeatherManager manager) {

  // Handle error

 
}

}
 );

Weather class

Object of Weather type can tell you a lot of information:

/*  * Location name.  */  String locationName = weather.getNavigation().getLocationName();
  /*  * Latitude of the place.  */  double latitude = weather.getNavigation().getCoordinate().getLatitude();
  /*  * Longitude of the place.  */  double longitude = weather.getNavigation().getCoordinate().getLongitude();
  /*  * Sea level.  */  double seaLevel = weather.getNavigation().getSeaLevel();
  /*  * Ground level.  */  double groundLevel = weather.getNavigation().getGroundLevel();
  /*  * Current temperature in Kelvin.  */  double currentTemperatureInKelvin = weather.getTemperature().getCurrent()
  .getValue(TemperatureUnit.KELVIN);
  /*  * Current temperature in Celcius.  */  double currentTemperatureInCelcius = weather.getTemperature().getCurrent()
  .getValue(TemperatureUnit.CELCIUS);
  /*  * Current temperature in Fahrenheit.  */  double currentTemperatureInFahrenheit = weather.getTemperature().getCurrent()
  .getValue(TemperatureUnit.FAHRENHEIT);
  /*  * Minimum temperature in Kelvin.  */  double minimumTemperatureInKelvin = weather.getTemperature().getMinimum()
  .getValue(TemperatureUnit.KELVIN);
  /*  * Minimum temperature in Celcius.  */  double minimumTemperatureInCelcius = weather.getTemperature().getMinimum()
  .getValue(TemperatureUnit.CELCIUS);
  /*  * Minimum temperature in Fahrenheit.  */  double minimumTemperatureInFahrenheit = weather.getTemperature().getMinimum()
  .getValue(TemperatureUnit.FAHRENHEIT);
  /*  * Maximum temperature in Kelvin.  */  double maximumTemperatureInKelvin = weather.getTemperature().getMaximum()
  .getValue(TemperatureUnit.KELVIN);
  /*  * Maximum temperature in Celcius.  */  double maximumTemperatureInCelcius = weather.getTemperature().getMaximum()
  .getValue(TemperatureUnit.CELCIUS);
  /*  * Maximum temperature in Fahrenheit.  */  double maximumTemperatureInFahrenheit = weather.getTemperature().getMaximum()
  .getValue(TemperatureUnit.FAHRENHEIT);
  /*  * Sunrise timestamp.  */  long sunriseTimestamp = weather.getLight().getSunriseTimestamp();
  /*  * Sunset timestamp.  */  long sunsetTimestamp = weather.getLight().getSunsetTimestamp();
  /*  * Pressure.  */  long pressure = weather.getAtmosphere().getPressure();
  /*  * Humidity.  */  int humidityPercentage = weather.getAtmosphere().getHumidityPercentage();
  /*  * Wind speed in meters per second.  */  double windSpeed = weather.getWind().getSpeed();
  /*  * Wind direction in degrees.  */  double direction = weather.getWind().getDirection();
  /*  * Cloudiness in percents.  */  int cloudinessPercentage = weather.getCloudiness().getPercentage();
  /*  * Rain volume for last three hours.  */  double rainThreeHoursVolume = weather.getRain().getThreeHoursVolume();
  /*  * Snow volume for last three hours.  */  double snowThreeHoursVolume = weather.getSnow().getThreeHoursVolume();
  /*  * Weather timestamp.  */  long weatherTimestamp = weather.getWeatherTimestamp();

Forecast

Example of request for 5 day forecast:

/*  * Request for 5 day forecast using coordinates.  */  new WeatherManager("INSERT_YOUR_API_KEY_HERE").getFiveDayForecastByCoordinates(

47.2257, // latitude

38.9383, // longitude

new WeatherManager.ForecastHandler() {

 @Override

 public void onReceivedForecast(WeatherManager manager, Forecast forecast) {

  // Handle forecast

 
}

  @Override

 public void onFailedToReceiveForecast(WeatherManager manager) {

  // Handle error...

 
}

}
 );
  /*  * Request for 5 day forecast using city name.  */  new WeatherManager("INSERT_YOUR_API_KEY_HERE").getFiveDayForecastByCityName(

"New York", // city name

new WeatherManager.ForecastHandler() {

 @Override

 public void onReceivedForecast(WeatherManager manager, Forecast forecast) {

  // Handle forecast

 
}

  @Override

 public void onFailedToReceiveForecast(WeatherManager manager) {

  // Handle error...

 
}

}
 );
  /*  * Request for 5 day forecast using city ID.  */  new WeatherManager("INSERT_YOUR_API_KEY_HERE").getFiveDayForecastByCityId(

2172797, // city id

new WeatherManager.ForecastHandler() {

 @Override

 public void onReceivedForecast(WeatherManager manager, Forecast forecast) {

  // Handle forecast

 
}

  @Override

 public void onFailedToReceiveForecast(WeatherManager manager) {

  // Handle error...

 
}

}
 );
  /*  * Request for 5 day forecast using ZIP code.  */  new WeatherManager("INSERT_YOUR_API_KEY_HERE").getFiveDayForecastByZipCode(

"94040", // ZIP code

"us", // country code

new WeatherManager.ForecastHandler() {

 @Override

 public void onReceivedForecast(WeatherManager manager, Forecast forecast) {

  // Handle forecast

 
}

  @Override

 public void onFailedToReceiveForecast(WeatherManager manager) {

  // Handle error...

 
}

}
 );

If request was successful, handler returns object of Forecast type. Forecast is a set of weathers for different timestamps. For example, forecast may include weather for today's 4 PM, today's 7 PM, tomorrow's 8 AM, etc. Below you can see example of usage:

new WeatherManager(API_KEY).getFiveDayForecastByCoordinates(

47.2257,

38.9383,

new WeatherManager.ForecastHandler() {

 @Override

 public void onReceivedForecast(WeatherManager manager, Forecast forecast) {

  // Example of handling forecast.

 int numberOfAvailableTimestamps = forecast.getNumberOfTimestamps();

 for (int timestampIndex = 0; timestampIndex < numberOfAvailableTimestamps; timestampIndex++) {

long timestamp = forecast.getTimestampByIndex(timestampIndex);

Weather weatherForTimestamp = forecast.getWeatherForTimestamp(timestamp);

// Do something with weather information...

  
}

 
}

  @Override

 public void onFailedToReceiveForecast(WeatherManager manager) {

  // Handle error...

 
}

}
 );

Also, you can request the most appropriate weather for random timestamp:

new WeatherManager(API_KEY).getFiveDayForecastByCoordinates(

47.2257,

38.9383,

new WeatherManager.ForecastHandler() {

 @Override

 public void onReceivedForecast(WeatherManager manager, Forecast forecast) {

  // Example of handling forecast.

 long rightNow = System.currentTimeMillis() / 1000;

 long inOneHour = rightNow + TimeUnit.HOURS.toSeconds(1);

  Weather weatherInOneHour = forecast.getWeatherForTimestamp(inOneHour);

 long afterTwoDays = rightNow + TimeUnit.DAYS.toSeconds(2);

  Weather weatherInTwoDays = forecast.getWeatherForTimestamp(afterTwoDays);

 
}

  @Override

 public void onFailedToReceiveForecast(WeatherManager manager) {

  // Handle error...

 
}

}
 );

You can simply check earliest and latest available timestamp:

long earliestAvailableTimestamp = forecast.getEarliestTimestamp();
 long latestAvailableTimestamp = forecast.getLatestTimestamp();

Temperature Conversions

You can easily convert temperature from to Celcius, from Celcius to Fahrenheit, etc. Use Temperature class for that:

Temperature temperature = new Temperature(32, TemperatureUnit.FAHRENHEIT);
 double temperatureInFahrenheit = temperature.getValue(TemperatureUnit.FAHRENHEIT);
 // 32.0 degrees double temperatureInCelcius = temperature.getValue(TemperatureUnit.CELCIUS);
 // 0.0 degrees double temperatureInKelvin = temperature.getValue(TemperatureUnit.KELVIN);
 // 273.15 degrees

Full list of supported temperature scales:

  • Celcius
  • Delisle
  • Fahrenheit
  • Kelvin
  • Rankine
  • Réaumur
  • Rømer

Temperature Formatter

Before displaying temperature in the app, you need to convert it to string. It's recommended to use TemperatureFormatter class for this purpose:

/*  * Format temperature with no digits after decimal point.  */  String temperatureWithoutDecimalPoint = new TemperatureFormatter().getStringFromTemperature(

32.0,

TemperatureUnit.FAHRENHEIT );
  Log.d("TemperatureFormatter", temperatureWithoutDecimalPoint);
 // "32 °F"  /*  * Format temperature with digit after decimal point.  */  String temperatureWithDecimalPoint = new TemperatureFormatter().getStringFromTemperature(

273.15,

TemperatureUnit.KELVIN );
  Log.d("TemperatureFormatter", temperatureWithDecimalPoint);
 // "273.15 °K"

License

F32 is available under the MIT license. See the LICENSE file for more info.

Resources

Tempo is a Kotlin library for Android to get the current time from multiple sources: SNTP, GPS; or your own time source.

An OpenCV based library for Android to scan (detect and crop) ID documents or Passports.

An infinite scrolling timeline to pick a date.

Full Animation Control on Paths and VectorDrawables.

Smooth UI for Credit Card Entry on Android device, perform check for supported credit card types , pan length and luhn check. Inspired by Uber credit card entry interface.

An annotation processor which implements "Builder pattern" for your java classes using gradle.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes