Android retrofit 2 news api example

Here is an example of how to use Retrofit 2 to fetch news data from the News API (https://newsapi.org/) in an Android app:

Step 1: Add Retrofit 2 and OkHttp dependencies to your Android project

Add the following dependencies to your build.gradle file:

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.okhttp3:okhttp:4.9.0'
}

Step 2: Create a News API interface

Create a new Java interface that defines the API endpoint and the data types:

public interface NewsApi {
    @GET("v2/top-headlines")
    Call<NewsResponse> getTopHeadlines(
            @Query("country") String country,
            @Query("category") String category,
            @Query("apiKey") String apiKey
    );
}

In this example, we're defining a getTopHeadlines method that takes three query parameters: country, category, and apiKey. The Call object returns a NewsResponse object, which we'll define next.

Step 3: Define the NewsResponse object

Create a new Java class that represents the response from the News API:

public class NewsResponse {
    private List<NewsArticle> articles;

    public List<NewsArticle> getArticles() {
        return articles;
    }
}

public class NewsArticle {
    private String title;
    private String description;
    private String url;
    private String urlToImage;

    public String getTitle() {
        return title;
    }

    public String getDescription() {
        return description;
    }

    public String getUrl() {
        return url;
    }

    public String getUrlToImage() {
        return urlToImage;
    }
}

In this example, we're defining a NewsResponse object that contains a list of NewsArticle objects. Each NewsArticle object has properties for title, description, URL, and URL to image.

Step 4: Create a Retrofit instance

Create a new instance of Retrofit and pass it the News API interface:

Retrofit retrofit = new Retrofit.Builder()
       .baseUrl("https://newsapi.org/")
       .addConverterFactory(GsonConverterFactory.create())
       .build();

NewsApi newsApi = retrofit.create(NewsApi.class);

In this example, we're creating a Retrofit instance with a base URL of https://newsapi.org/ and adding the Gson converter factory to convert JSON responses to Java objects.

Step 5: Make a request to the News API

Use the NewsApi interface to make a request to the News API:

Call<NewsResponse> call = newsApi.getTopHeadlines("us", "technology", "YOUR_API_KEY");
call.enqueue(new Callback<NewsResponse>() {
    @Override
    public void onResponse(Call<NewsResponse> call, Response<NewsResponse> response) {
        if (response.isSuccessful()) {
            NewsResponse newsResponse = response.body();
            List<NewsArticle> articles = newsResponse.getArticles();
            // Process the news articles
        } else {
            // Handle error
        }
    }

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

In this example, we're making a request to the News API with the getTopHeadlines method, passing in the country, category, and API key. We're using the enqueue method to make the request asynchronously and handle the response.

Step 6: Process the news articles

In the onResponse method, we're processing the news articles by iterating over the list of articles and displaying the title, description, and URL:

for (NewsArticle article : articles) {
    Log.d("News", article.getTitle());
    Log.d("News", article.getDescription());
    Log.d("News", article.getUrl());
}

That's it! This is a basic example of how to use Retrofit 2 to fetch news data from the News API in an Android app. You can customize the request and response handling to fit your specific needs.