I. Link JSON từ NewsAPI
- Trang chủ NewsAPI: https://newsapi.org/
- NewsAPI search: https://newsapi.org/v2/everything?language=vi&apiKey=061a72b6057144bcac23934a0ab49842&q=Messi
- q=Messi: Thay "Messi" bằng cụm từ khóa tìm kiếm bất kỳ
- apiKey=061a72b6057144bcac23934a0ab49842: apiKey chính là key của NewsAPI cung cấp khi đăng ký tài khoản.
- Kết quả trả về ở dạng Json như sau
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
{ "status": "ok", "totalResults": 100, "articles": [ { "source": { "id": null, "name": "Vnexpress.net" }, "author": "VnExpress", "title": "Messi phải tập riêng", "description": "Siêu sao Lionel Messi phải tập hồi phục chấn thương bắp chân phải, trong phòng gym của CLB Barca hôm qua 3/6, theo Marca.", "url": "https://vnexpress.net/messi-phai-tap-rieng-4110043.html", "urlToImage": "https://vcdn-thethao.vnecdn.net/2020/06/04/messi-1591207736-7113-1591207844_1200x0.jpg?w=0&h=0&q=100&dpr=2&fit=crop&s=-YXVQmJ4P7YaOtqaHKo4nQ", "publishedAt": "2020-06-03T22:15:24Z", "content": "Siêu sao Lionel Messi phi tp hi phc chn thng bp chân phi, trong phòng gym ca CLB Barca hôm qua 3/6, theo Marca.Các cu th còn li ca Barca tp cùng nhau trên khu tp luyn Tito Vilanova, chun b cho vòng 2… [+863 chars]" }, { "source": { "id": null, "name": "Vnexpress.net" }, "author": "VnExpress", "title": "Setien: 'Messi không chỉ ghi bàn'", "description": "HLV Barca Quique Setien ca ngợi đóng góp của Lionel Messi trên nhiều khía cạnh.", "url": "https://vnexpress.net/setien-messi-khong-chi-ghi-ban-4116153.html", "urlToImage": "https://vcdn-thethao.vnecdn.net/2020/06/16/untitled-1592250193-3876-1592250235_1200x0.jpg?w=0&h=0&q=100&dpr=2&fit=crop&s=l4l5TtyGwbM9G6aIEk4Xxg", "publishedAt": "2020-06-15T23:15:11Z", "content": "HLV Barca Quique Setien ca ngi óng góp ca Lionel Messi trên nhiu khía cnh.\"Bn không th ch ánh giá Messi qua nhng bàn thng cu y ghi. Messi còn có nhng óng góp khác, nh kin to. iu ó mang li nhiu im s c… [+1648 chars]" }, { "key": "value" }, { "key": "value" }, { "key": "value" } ] } |
II. Cấp quyền thư viện Retrofit 2
- Trang chủ: https://square.github.io/retrofit/
1. Implement thư viện
1 2 3 4 |
compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } |
1 2 |
implementation 'com.squareup.retrofit2:retrofit:+' implementation 'com.squareup.retrofit2:converter-gson:+' |
2. Cấp quyền Internet
1 |
<uses-permission android:name="android.permission.INTERNET"/> |
III. Tạo các Class theo JSON
1. JsonArticles.class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.example.firstproject; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class JsonArticles{ @SerializedName("articles") private ArrayList<JsonItem> items; public ArrayList<JsonItem> getItems() { return items; } } |
3. JsonItem.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
package com.example.firstproject; import com.google.gson.annotations.SerializedName; public class JsonItem{ @SerializedName("title") private String title; @SerializedName("description") private String desc; @SerializedName("url") private String url; @SerializedName("urlToImage") private String image; @SerializedName("publishedAt") private String pubDate; public String getTitle() { return title; } public String getDesc() { return desc; } public String getUrl() { return url; } public String getImage() { return image; } public String getPubDate() { return pubDate; } @Override public String toString() { return title + '\n'; } } |
III. Tạo class của Retrofit 2
1. interface RetrofitAPI.class
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.example.firstproject; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface RetrofitAPI{ @GET("everything?language=vi") Call<JsonArticles> getArticles( @Query("qInTitle") String q, @Query("apiKey") String apiKey ); } |
2. RetrofitBuilder.class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.example.firstproject; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RetrofitBuilder { private static RetrofitAPI retrofitAPI; public static RetrofitAPI getInstance(){ if (retrofitAPI == null){ Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://newsapi.org/v2/") .client(new OkHttpClient()) .addConverterFactory(GsonConverterFactory.create()) .build(); retrofitAPI = retrofit.create(RetrofitAPI.class); } return retrofitAPI; } } |
V. Sử dụng
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
String apiKey = "061a72b6057144bcac23934a0ab49842"; String search = "Messi" RetrofitBuilder.getInstance().getArticles(search,apiKey).enqueue(new Callback<JsonArticles>() { @Override public void onResponse(Call<JsonArticles> call, Response<JsonArticles> response) { if (response.isSuccessful()){ JsonArticles jsonArticles= response.body(); ArrayList<JsonItem> items = jsonArticles.getItems(); //items chính là List danh sách nhận được để dùng cho RecycleView Toast.makeText(MainActivity.this, items.toString(), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Request Error", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<JsonArticles> call, Throwable t) { if (call.isCanceled()){ Toast.makeText(MainActivity.this, "Call was cancelled forcefully", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Network Error", Toast.LENGTH_SHORT).show(); } } }); |