build a Weather App in Android Studio using the OpenWeatherMap API

To build a Weather App in Android Studio using the OpenWeatherMap API, follow this step-by-step guide. The app will include features like local weather, search by city, hourly and daily forecasts, and detailed weather information.

 

Step 1: Set Up Android Studio Project

Open Android Studio and create a new project.

Choose Empty Activity as the template.

Name the project (e.g., WeatherApp).

Set the minimum SDK to API 21 (Android 5.0 Lollipop).

Click Finish.

Step 2: Add Dependencies

Add the following dependencies to your build.gradle (Module: app) file:

dependencies { implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.google.android.material:material:1.10.0' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0' implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.7.0' implementation 'androidx.activity:activity-ktx:1.8.2' implementation 'com.github.bumptech.glide:glide:4.12.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0' }

Sync the project to download the dependencies.

 

Step 3: Get OpenWeatherMap API Key

Go to OpenWeatherMap and sign up for a free account.

Get your API key from the dashboard.

Step 4: Create Retrofit Service

Create a Retrofit service to fetch weather data from the API.

interface WeatherService {@GET("data/2.5/weather")suspendfungetCurrentWeather(@Query("q") cityName: String,@Query("appid") apiKey: String,@Query("units") units: String ="metric"): Response<WeatherResponse> @GET("data/2.5/forecast")suspendfungetForecast(@Query("q") cityName: String,@Query("appid") apiKey: String,@Query("units") units: String ="metric"): Response<ForecastResponse>}

 

Step 5: Define Data Classes

Create data classes for the API response.

dataclassWeatherResponse(val main: Main,val weather: List<Weather>,val wind: Wind,val sys: Sys,val name: String ) dataclassMain(val temp: Double,val humidity: Int,val pressure: Int ) dataclassWeather(val id: Int,val main: String,val description: String,val icon: String ) dataclassWind(val speed: Double,val deg: Int ) dataclassSys(val sunrise: Long,val sunset: Long ) dataclassForecastResponse(val list: List<Forecast>) dataclassForecast(val dt: Long,val main: Main,val weather: List<Weather>,val wind: Wind )

Step 6: ViewModel and Repository

Create a WeatherViewModel and WeatherRepository to manage data fetching.

class WeatherViewModel :ViewModel(){privateval repository =WeatherRepository() val weatherLiveData: LiveData<WeatherResponse>= repository.weatherLiveData val forecastLiveData: LiveData<List<Forecast>>= repository.forecastLiveData funfetchWeather(cityName: String, apiKey: String){ viewModelScope.launch{ repository.fetchWeather(cityName, apiKey)}} funfetchForecast(cityName: String, apiKey: String){ viewModelScope.launch{ repository.fetchForecast(cityName, apiKey)}}} class WeatherRepository {privateval weatherService = RetrofitInstance.getService() val weatherLiveData = MutableLiveData<WeatherResponse>()val forecastLiveData = MutableLiveData<List<Forecast>>() suspendfunfetchWeather(cityName: String, apiKey: String){try{val response = weatherService.getCurrentWeather(cityName, apiKey)if(response.isSuccessful){ weatherLiveData.postValue(response.body())}}catch(e: Exception){ e.printStackTrace()}} suspendfunfetchForecast(cityName: String, apiKey: String){try{val response = weatherService.getForecast(cityName, apiKey)if(response.isSuccessful){ forecastLiveData.postValue(response.body()?.list)}}catch(e: Exception){ e.printStackTrace()}}}

Step 7: Design UI

Create a simple UI in activity_main.xml:

 

A TextView to display the city name.

A TextView to display the temperature.

A TextView to display the weather description.

A RecyclerView for the forecast.

Step 8: Bind Data to UI

In MainActivity, observe the LiveData from the ViewModel and update the UI.

class MainActivity :AppCompatActivity(){privateval viewModel: WeatherViewModel byviewModels() overridefunonCreate(savedInstanceState: Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_main) val apiKey ="YOUR_API_KEY"val cityName ="London" viewModel.fetchWeather(cityName, apiKey) viewModel.fetchForecast(cityName, apiKey) viewModel.weatherLiveData.observe(this){ weather -> cityNameTextView.text = weather.name temperatureTextView.text ="${weather.main.temp}°C" descriptionTextView.text = weather.weather[0].description } viewModel.forecastLiveData.observe(this){ forecastList ->val adapter =ForecastAdapter(forecastList) recyclerView.adapter = adapter recyclerView.layoutManager =LinearLayoutManager(this)}}}

Step 9: Test the App

Run the app on an emulator or a real device.

Ensure the weather data is displayed correctly.

Step 10: Add Advanced Features

Add a search bar to allow users to search for weather by city.

Implement a settings screen to switch between Celsius and Fahrenheit.

Add weather icons using Glide.

Step 11: Monetization (Optional)

Offer a paid version with additional features like:

Ad-free experience.

Extended forecasts (10 days).

Weather widgets for the home screen.

By following these steps, you can build a fully functional Weather App using Android Studio and the OpenWeatherMap API.

To integrate StartApp Ads into your Android app, follow these steps. StartApp is a popular monetization platform that offers banner, interstitial, and rewarded video ads. Below is a step-by-step guide to adding StartApp ads to your app.

Step 1: Add the StartApp SDK Dependency

Add the StartApp SDK to your app's build.gradle file.

dependencies { implementation 'com.startapp:inapp-sdk:4.11.0' // Use the latest version }

Sync your project after adding the dependency.

 

Step 2: Initialize StartApp in Your Application

Initialize StartApp in your Application class or MainActivity.

Example in MainActivity:

importcom.startapp.sdk.adsbase.StartAppSDK;importandroid.os.Bundle;importandroidx.appcompat.app.AppCompatActivity; publicclassMainActivityextendsAppCompatActivity{@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); // Initialize StartApp with your App IDStartAppSDK.init(this,"YOUR_APP_ID",true);// Replace with your App ID}}

Note: Replace "YOUR_APP_ID" with your actual StartApp App ID. You can find this in your StartApp dashboard.

 

Step 3: Add Banner Ads

To display banner ads, use the StartAppAd class.

Example:

importcom.startapp.sdk.ads.banner.Banner;importandroid.os.Bundle;importandroidx.appcompat.app.AppCompatActivity;importandroid.widget.LinearLayout; publicclassMainActivityextendsAppCompatActivity{@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); // Initialize StartAppStartAppSDK.init(this,"YOUR_APP_ID",true); // Add Banner AdBanner startAppBanner =newBanner(this);LinearLayout bannerContainer =findViewById(R.id.banner_container); bannerContainer.addView(startAppBanner);}}

Add the banner container to your layout XML file (activity_main.xml):

<LinearLayoutandroid:id="@+id/banner_container"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"android:gravity="center"/>

Step 4: Add Interstitial Ads

To show interstitial ads, use the StartAppAd class.

Example:

importcom.startapp.sdk.adsbase.StartAppAd;importandroid.os.Bundle;importandroidx.appcompat.app.AppCompatActivity; publicclassMainActivityextendsAppCompatActivity{privateStartAppAd startAppAd; @OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); // Initialize StartAppStartAppSDK.init(this,"YOUR_APP_ID",true); // Initialize Interstitial Ad startAppAd =newStartAppAd(this); // Show Interstitial Ad startAppAd.showAd();} @OverrideprotectedvoidonResume(){super.onResume();StartAppAd.onResume(this);} @OverrideprotectedvoidonPause(){super.onPause();StartAppAd.onPause(this);}}

Step 5: Add Rewarded Video Ads

To show rewarded video ads, use the StartAppAd class.

Example:

importcom.startapp.sdk.adsbase.StartAppAd;importandroid.os.Bundle;importandroidx.appcompat.app.AppCompatActivity; publicclassMainActivityextendsAppCompatActivity{privateStartAppAd startAppAd; @OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main); // Initialize StartAppStartAppSDK.init(this,"YOUR_APP_ID",true); // Initialize Rewarded Video Ad startAppAd =newStartAppAd(this); // Show Rewarded Video Ad startAppAd.setVideoListener(()->{// Handle reward logic here// Example: Give coins or points to the user}); startAppAd.loadAd(StartAppAd.AdMode.REWARDED_VIDEO, ad ->{if(ad !=null){ startAppAd.showAd(StartAppAd.AdMode.REWARDED_VIDEO);}});}}

Step 6: Test Your Ads

While testing, use the StartApp Test Mode to avoid serving real ads. Add this line after initializing the SDK:

StartAppSDK.setTestAdsEnabled(true);

Step 7: Publish Your App

Once you're satisfied with the integration, remove the test mode and publish your app. Monitor your ad performance in the StartApp dashboard.

This is a basic integration of StartApp ads. For advanced features like native ads or custom configurations, refer to the StartApp Documentation.

Enjoyed this article? Stay informed by joining our newsletter!

Comments

You must be logged in to post a comment.

About Author