create account

How to Build A Weather App on Android - Hive Programmers by skyehi

View this thread on: hive.blogpeakd.comecency.com
· @skyehi ·
$2.47
How to Build A Weather App on Android - Hive Programmers
Greetings to my favorite science community online, StemSocial.

I'm always excited to be back to continue my series on Android programming and app development tutorials. We've been making a lot of progress and I wanted to teach you how to build a bit more complex apps.

For today's tutorial we'll be working on a simple Weather application which the user can use to check weather information. 


![Polish_20231121_152103739.jpg](https://files.peakd.com/file/peakd-hive/skyehi/23tbPh311uptKAQC3jndVHZrrjiAs1etzXCVeWHyYm8hPPCRqhveE4gSg83SA4WLLZAzz.jpg)[Original Image Source](https://pixabay.com/photos/code-coding-web-development-944499/) by lmonk72 from Pixabay


![YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png](https://files.peakd.com/file/peakd-hive/skyehi/23swrbKc3yjMYSUJMwmHkXUC71AufZXrkQ315XAST7nXzaKhpkvsAScnV3nBnpS55SJ2r.png)


#### Setting Up Your Development Environment

As usual guys, we need to ensure that Android Studio and Java Development kit are both downloaded and installed on the computer.

> For the newcomers of my tutorial if you're having trouble downloading or installing the softwares, please let me know and I'll either share the download link or assist you through the setup process. 

Open Android studio and create a new app project. You can name it "The Weather App" or any name of your choice. Please ensure that you select "Empty Activity" as the app template and also choose Java as the programming language.

In future tutorials after we've gone through the basics, I'll start teaching with Kotlin. Click finish and we're all set and ready to write our code and build our weather app. 

---

#### Designing Our User Interface

Well guys, we would need to create our frontend first which is the part of the app that our users will see and interact with. We'll be writing the code in the `activity_main.xml`page. Our design page would include a text editor, a button and a textview.

> Here's how your code should look like. 

```xml
<!-- activity_main.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editTextCity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter City"/>

    <Button
        android:id="@+id/buttonGetWeather"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Weather"/>

    <TextView
        android:id="@+id/textViewWeatherInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/buttonGetWeather"
        android:layout_marginTop="16dp"/>
</RelativeLayout>
```


![YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png](https://files.peakd.com/file/peakd-hive/skyehi/23swrbKc3yjMYSUJMwmHkXUC71AufZXrkQ315XAST7nXzaKhpkvsAScnV3nBnpS55SJ2r.png)


#### Getting Our API Key

Alright guys so one of my main purpose for this particular tutorial was to introduce you to API keys in Android Programming. 

In order for our app to be able to fetch weather data, we'll need an API key from a weather service provider.

Some very popular weather service provider choices include OpenWeatherMap, Weatherbit, or AccuWeather. 

> First sign up on their website and obtain your API key and also remember to keep it secure.

---

#### Fetching The Weather Data

Now that we're done with the layout and obtaining the API key, we can start working on the backend of our application. We would now need to write the code that would fetch the weather Data. This code will be written in `MainActivity.java`

> Here's how your code should look like. 

```java
// Inside MainActivity.java
// Retrofit dependencies should be added to your app's build.gradle file

// Imports
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private static final String BASE_URL = "https://api.openweathermap.org/data/2.5/";
    private static final String API_KEY = "YourAPIKey";

    // Retrofit instance
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    // Interface for API calls
    interface WeatherApi {
        @GET("weather")
        Call<WeatherResponse> getWeather(
            @Query("q") String city,
            @Query("appid") String apiKey
        );
    }

    // API call example
    WeatherApi weatherApi = retrofit.create(WeatherApi.class);
    Call<WeatherResponse> call = weatherApi.getWeather("CityName", API_KEY);

    call.enqueue(new Callback<WeatherResponse>() {
        @Override
        public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
            if (response.isSuccessful()) {
                WeatherResponse weatherResponse = response.body();
                // Extract and display weather information
            }
        }

        @Override
        public void onFailure(Call<WeatherResponse> call, Throwable t) {
            // Handle failure
        }
    });
}
```


![YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png](https://files.peakd.com/file/peakd-hive/skyehi/23swrbKc3yjMYSUJMwmHkXUC71AufZXrkQ315XAST7nXzaKhpkvsAScnV3nBnpS55SJ2r.png)



#### Displaying The Weather Information 

Since we have successfully been able to write the code to retrieve the weather data or information, it's now time to write the code that displays the information in our application. This code will also be written in the `MainActivity.java` page. 

> Here's how the code should look like 

```java
// Inside onResponse() method
String weatherInfo = "Temperature: " + weatherResponse.getMain().getTemp() + "°C\n"
        + "Description: " + weatherResponse.getWeather().get(0).getDescription();
textViewWeatherInfo.setText(weatherInfo);
```

---

#### Handling The User Input 

Now it's time for us to write the code that gives functionality to our button and handles the user's input.

When the user presses the button, the app can retrieve the weather information and display it. The weather information is based on the city name that our user will type in the edit text field. 

We'll be doing this in `MainActivity.java` and we'll need the `OnClickListener` to make the button work.

> Here's exactly how your code should look like. 

```java
// Inside onCreate() method
Button buttonGetWeather = findViewById(R.id.buttonGetWeather);
EditText editTextCity = findViewById(R.id.editTextCity);

buttonGetWeather.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String cityName = editTextCity.getText().toString();
        // Make API call with the entered city name
    }
});
```

---

#### Our Final Step - Error Handling 

This tutorial was also designed for me to introduce you to error handling in App development. It's always necessary to write codes that handles errors. If you avoid this step as a programmer, you may end up developing apps that would always crash when there's an error. 

The Error handling will be done in `MainActivity.java` as well.

> Here's how to handle an error with a toast message. 

```java
// Inside onFailure() method
Toast.makeText(MainActivity.this, "Failed to fetch weather data", Toast.LENGTH_SHORT).show();
```


![2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png](https://files.peakd.com/file/peakd-hive/skyehi/EoAYDi9ZKfkBZi7rMWbojnS8KytoTpbSepvPmfeZmL2V2h8FDZ3xRpC58MZDkf1LeRQ.png)


That's all guys, we're now ready to run our weather app. You can connect your physical Android device and ensure that USB debugging is turned on. 

If you prefer the Android Emulator, you can select the emulator and run your app. The codes we wrote are great and the app should run just fine.

When the App runs, you can input a city name and you'll get the weather information of the city. Thank you so much for taking the time to read this blog.

I hope it was both entertaining and educative. If you're having issues writing the code or running the app, please let me know in the comments section and I'll try to assist you.

As we keep building more apps, we'll soon become professional Android app developers.

> Have a lovely day and catch you next time on StemSocial. Goodbye 👨‍💻

<center>
You Can Follow Me @skyehi For More Like This And Others 
</center>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 201 others
properties (23)
authorskyehi
permlinkhow-to-build-a-weather-app-on-android-hive-programmers
categoryhive-196387
json_metadata{"app":"peakd/2023.10.1","format":"markdown","tags":["health","stemng","stemgeeks","neoxian","waivio","cent","proofofbrain","chessbrothers","alive","stemsocial"],"users":["GET","Query","Override","skyehi"],"image":["https://files.peakd.com/file/peakd-hive/skyehi/23tbPh311uptKAQC3jndVHZrrjiAs1etzXCVeWHyYm8hPPCRqhveE4gSg83SA4WLLZAzz.jpg","https://files.peakd.com/file/peakd-hive/skyehi/23swrbKc3yjMYSUJMwmHkXUC71AufZXrkQ315XAST7nXzaKhpkvsAScnV3nBnpS55SJ2r.png","https://files.peakd.com/file/peakd-hive/skyehi/EoAYDi9ZKfkBZi7rMWbojnS8KytoTpbSepvPmfeZmL2V2h8FDZ3xRpC58MZDkf1LeRQ.png"]}
created2023-11-21 15:12:21
last_update2023-11-21 15:12:21
depth0
children2
last_payout2023-11-28 15:12:21
cashout_time1969-12-31 23:59:59
total_payout_value1.224 HBD
curator_payout_value1.242 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9,168
author_reputation103,283,026,686,970
root_title"How to Build A Weather App on Android - Hive Programmers "
beneficiaries
0.
accountstemsocial
weight500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id129,054,819
net_rshares5,532,951,009,603
author_curate_reward""
vote details (265)
@chessbrotherspro ·
<h3>Congratulations!</h3><hr /><div class="pull-right"><img src="https://images.hive.blog/DQmQLssYuuJP2neoTVUbMRzvAu4Ptg7Vwt92aTM7Z3gNovg/cb-logo-150.png" alt="You have obtained a vote from CHESS BROTHERS PROJECT"/></div><div class="text-justify"><h3>✅ Good job. Your post has been appreciated and has received support from <a href="/@chessbrotherspro"><b>CHESS BROTHERS</b></a> ♔ 💪</h3><p><br>♟ We invite you to use our hashtag <b>#chessbrothers</b> and learn more <a href="/@chessbrotherspro/introducing-chess-brothers-project-the-most-innovative-community-combining-chess-fitness-and-more"><b>about us</b></a>.</p><p>♟♟ You can also reach us on our <a href="https://discord.gg/73sK9ZTGqJ" rel="noopener" title="This is going to take you to the Discord of Chess Brothers"><b>Discord server</b></a>  and promote your posts there.</p><p>♟♟♟  Consider <a href="/@chessbrotherspro/teamwork-is-worthwhile-join-the-chess-brothers-healing-trail-supporting-the-work-being-done-and-earning-rewards"><b>joining our curation trail</b></a> so we work as a team and you get rewards automatically.</p><p>♞♟ Check out our <a href="/@chessbrotherspro"><b>@chessbrotherspro</b></a> account to learn about the curation process carried out daily by our team.</p><p><br>🏅 If you want to earn profits with your HP delegation and support our project, we invite you to join the <i>Master Investor</i> plan. <a href='/@chessbrotherspro/master-investor-plan-or-programa'>Here you can learn how to do it.</a></p></div><div class="text-center"><p><br>Kindly</p><p><strong><em>The CHESS BROTHERS team</em></strong></p></div>
properties (22)
authorchessbrotherspro
permlinkre-how-to-build-a-weather-app-on-android-hive-programmers
categoryhive-196387
json_metadata""
created2023-11-22 11:18:09
last_update2023-11-22 11:18:09
depth1
children0
last_payout2023-11-29 11:18:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,598
author_reputation78,095,969,448,032
root_title"How to Build A Weather App on Android - Hive Programmers "
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id129,077,934
net_rshares0
@stemsocial ·
re-skyehi-how-to-build-a-weather-app-on-android-hive-programmers-20231122t015300803z
<div class='text-justify'> <div class='pull-left'>
 <img src='https://stem.openhive.network/images/stemsocialsupport7.png'> </div>

Thanks for your contribution to the <a href='/trending/hive-196387'>STEMsocial community</a>. Feel free to join us on <a href='https://discord.gg/9c7pKVD'>discord</a> to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support.&nbsp;<br />&nbsp;<br />
</div>
properties (22)
authorstemsocial
permlinkre-skyehi-how-to-build-a-weather-app-on-android-hive-programmers-20231122t015300803z
categoryhive-196387
json_metadata{"app":"STEMsocial"}
created2023-11-22 01:53:00
last_update2023-11-22 01:53:00
depth1
children0
last_payout2023-11-29 01:53:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length545
author_reputation22,918,836,157,020
root_title"How to Build A Weather App on Android - Hive Programmers "
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id129,068,901
net_rshares0