How to Build A Weather App on Android - Hive Programmers

avatar

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.jpgOriginal Image Source by lmonk72 from Pixabay

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.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.xmlpage. Our design page would include a text editor, a button and a textview.

Here's how your code should look like.

(html comment removed:  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

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.

// 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

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

// 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.

// 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.

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

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.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 👨‍💻


You Can Follow Me @skyehi For More Like This And Others



0
0
0.000
2 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord 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. 
 

0
0
0.000
avatar

Congratulations!


You have obtained a vote from CHESS BROTHERS PROJECT

✅ Good job. Your post has been appreciated and has received support from CHESS BROTHERS ♔ 💪


♟ We invite you to use our hashtag #chessbrothers and learn more about us.

♟♟ You can also reach us on our Discord server and promote your posts there.

♟♟♟ Consider joining our curation trail so we work as a team and you get rewards automatically.

♞♟ Check out our @chessbrotherspro account to learn about the curation process carried out daily by our team.


🏅 If you want to earn profits with your HP delegation and support our project, we invite you to join the Master Investor plan. Here you can learn how to do it.


Kindly

The CHESS BROTHERS team

0
0
0.000