Examp ứng dụng xem dự báo thời tiết
Đầu tiên chúng ta tao project và đến build.gradle (Module: app) thêm thư viện Retrofit, Gson, Glide rồi bấm Sync now để Android Studio tự động download thư viện về cho chúng ta.
compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' compile 'com.github.bumptech.glide:glide:3.7.0'
Tiếp theo ở bài này ta tạo ứng dụng xem thời tiết. Vì vậy cần cấp quyền INTERNET
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
URI: http://dataservice.accuweather.com/forecasts/v1/daily/1day/353412?apikey=oHxjrezmWVb7EFb80Ad6kxxQ3Lv4Sl2r&language=vi-vn&metric=true
{
"Headline": {
"EffectiveDate": "2017-01-17T01:00:00+07:00",
"EffectiveEpochDate": 1484589600,
"Severity": 3,
"Text": "Dự kiến thời tiết mưa nhiều cuối đêm Thứ Hai liên tục đến chiều Thứ Ba",
"Category": "rain",
"EndDate": "2017-01-17T19:00:00+07:00",
"EndEpochDate": 1484654400,
"MobileLink": "http://m.accuweather.com/vi/vn/hanoi/353412/extended-weather-forecast/353412?unit=c&lang=vi-vn",
"Link": "http://www.accuweather.com/vi/vn/hanoi/353412/daily-weather-forecast/353412?unit=c&lang=vi-vn"
},
"DailyForecasts": [
{
"Date": "2017-01-14T07:00:00+07:00",
"EpochDate": 1484352000,
"Temperature": {
"Minimum": {
"Value": 14,
"Unit": "C",
"UnitType": 17
},
"Maximum": {
"Value": 18.6,
"Unit": "C",
"UnitType": 17
}
},
"Day": {
"Icon": 8,
"IconPhrase": "Ảm đạm"
},
"Night": {
"Icon": 8,
"IconPhrase": "Ảm đạm"
},
"Sources": [
"AccuWeather"
],
"MobileLink": "http://m.accuweather.com/vi/vn/hanoi/353412/daily-weather-forecast/353412?day=1&unit=c&lang=vi-vn",
"Link": "http://www.accuweather.com/vi/vn/hanoi/353412/daily-weather-forecast/353412?day=1&unit=c&lang=vi-vn"
}
]
}
-Để có được URI - API ở trên chúng ta cần đăng ký tài khoản và tạo mới ở trên Website http://developer.accuweather.com/-Hoặc các bạn có thể sử dụng lại URI của tôi thay đoạn key trong tài khoản của bạn vào phần bôi đậm màu mận chín URI phía trên.
-Sử dụng tiện ích Chrome Boomerang để test và hiển thị dữ liệu JSON của URI đó
Tiếp theo tạo package model
Nhìn vào cấu trúc dữ liệu JSON phía trên thì chúng ta tạo lần lượt các class theo thứ tự:
-Chú ý: Tạo class nhanh dự vào ToolSite http://pojo.sodhanalibrary.com/
Maximum.java
Java Android 2017
package com.example.lonely.demojson.model;
/**
* Created by Lonely on 1/14/2017.
*/
public class Maximum {
private String Value;
private String UnitType;
private String Unit;
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
}
public String getUnitType() {
return UnitType;
}
public void setUnitType(String unitType) {
UnitType = unitType;
}
public String getUnit() {
return Unit;
}
public void setUnit(String unit) {
Unit = unit;
}
}
Minimum.java
Java Android 2017
package com.example.lonely.demojson.model;
/**
* Created by Lonely on 1/14/2017.
*/
public class Minimum {
private String Value;
private String UnitType;
private String Unit;
public String getValue() {
return Value;
}
public void setValue(String value) {
Value = value;
}
public String getUnitType() {
return UnitType;
}
public void setUnitType(String unitType) {
UnitType = unitType;
}
public String getUnit() {
return Unit;
}
public void setUnit(String unit) {
Unit = unit;
}
}
Temperature.java
Java Android 2017
package com.example.lonely.demojson.model;
/**
* Created by Lonely on 1/14/2017.
*/
public class Temperature {
private Maximum Maximum;
private Minimum Minimum;
public Maximum getMaximum() {
return Maximum;
}
public void setMaximum(Maximum maximum) {
Maximum = maximum;
}
public Minimum getMinimum() {
return Minimum;
}
public void setMinimum(Minimum minimum) {
Minimum = minimum;
}
}
Day.java
Java Android 2017
package com.example.lonely.demojson.model;
/**
* Created by Lonely on 1/14/2017.
*/
public class Day {
private String IconPhrase;
private String Icon;
public String getIconPhrase() {
return IconPhrase;
}
public void setIconPhrase(String iconPhrase) {
IconPhrase = iconPhrase;
}
public String getIcon() {
return Icon;
}
public void setIcon(String icon) {
Icon = icon;
}
}
Night.java
Java Android 2017
package com.example.lonely.demojson.model; /** * Created by Lonely on 1/14/2017. */ public class Night { private String IconPhrase; private String Icon; public String getIconPhrase() { return IconPhrase; } public void setIconPhrase(String iconPhrase) { IconPhrase = iconPhrase; } public String getIcon() { return Icon; } public void setIcon(String icon) { Icon = icon; } }
DailyForecasts.java
Java Android 2017
package com.example.lonely.demojson.model; /** * Created by Lonely on 1/14/2017. */ public class DailyForecasts { private Temperature Temperature; private Night Night; private Day Day; public Night getNight() { return Night; } public void setNight(Night Night) { this.Night = Night; } public Temperature getTemperature() { return Temperature; } public void setTemperature(Temperature Temperature) { this.Temperature = Temperature; } public Day getDay() { return Day; } public void setDay(Day Day) { this.Day = Day; } }
Headline.java
Java Android 2017
package com.example.lonely.demojson.model;
/**
* Created by Lonely on 1/14/2017.
*/
public class Headline {
private String Text;
private String Category;
private String EndDate;
public String getText() {
return Text;
}
public void setText(String text) {
Text = text;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getEndDate() {
return EndDate;
}
public void setEndDate(String endDate) {
EndDate = endDate;
}
}
MyPojo.java
Java Android 2017
package com.example.lonely.demojson.model;
import java.util.List;
/**
* Created by Lonely on 1/14/2017.
*/
public class MyPojo {
private List<DailyForecasts> DailyForecasts;
private Headline Headline;
public List<com.example.lonely.demojson.model.DailyForecasts> getDailyForecasts() {
return DailyForecasts;
}
public void setDailyForecasts(List<com.example.lonely.demojson.model.DailyForecasts> dailyForecasts) {
DailyForecasts = dailyForecasts;
}
public Headline getHeadline() {
return Headline;
}
public void setHeadline(Headline Headline) {
this.Headline = Headline;
}
}
Tạo package network
APIManager.java
Java Android 2017
package com.example.lonely.demojson.network; import com.example.lonely.demojson.model.MyPojo; import retrofit2.Call; import retrofit2.http.GET; /** * Created by anhtran on 1/13/17. */ public interface APIManager { public static String BASE_URL = "http://dataservice.accuweather.com/"; @GET("forecasts/v1/daily/1day/353412?apikey=oHxjrezmWVb7EFb80Ad6kxxQ3Lv4Sl2r&language=vi-vn&metric=true") Call<MyPojo> apiGetNews(); }
activity_main.xml
Java Android 2017
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.lonely.demojson.activity.MainActivity">
<TextView
android:id="@+id/dubao"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Dự Báo Thời Tiết Ngày Tới"
android:textSize="25sp"
android:textColor="#FFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_below="@id/dubao"
android:id="@+id/date"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textColor="#fff"
android:textSize="30dp"
android:text="1-1-2017"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_text"
android:layout_below="@id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Thông tin thời tiết"
android:textColor="#fff" />
<TextView
android:id="@+id/tv_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_text"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Nắng - Mưa"
android:textColor="#33ff00"
android:textSize="30sp" />
<TextView
android:id="@+id/homnay"
android:text="Thời Tiết Ngày Hôm Nay"
android:textColor="#fff"
android:textSize="25sp"
android:layout_below="@id/tv_category"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:id="@+id/line_1"
android:gravity="center"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/homnay"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<RelativeLayout
android:layout_weight="1"
android:layout_width="200dp"
android:layout_height="wrap_content">
<TextView
android:layout_marginBottom="10dp"
android:id="@+id/day"
android:textColor="#fff"
android:text="Trưa Nay"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="Bầu trời"
android:textColor="#fff"
android:layout_below="@id/day"
android:id="@+id/iconphrase_1"
android:layout_width="wrap_content"
android:layout_marginBottom="10dp"
android:layout_height="wrap_content" />
<ImageView
android:src="@mipmap/ic_launcher"
android:id="@+id/icon_1"
android:layout_marginLeft="30dp"
android:layout_toRightOf="@id/iconphrase_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<RelativeLayout
android:layout_weight="1"
android:layout_width="200dp"
android:layout_height="wrap_content">
<TextView
android:id="@+id/night"
android:layout_marginBottom="10dp"
android:textColor="#fff"
android:text="Đêm Nay"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="Bầu trời"
android:layout_marginBottom="10dp"
android:textColor="#fff"
android:layout_below="@id/night"
android:id="@+id/iconphrase_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:src="@mipmap/ic_launcher"
android:id="@+id/icon_2"
android:layout_marginLeft="30dp"
android:layout_toRightOf="@id/iconphrase_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:gravity="center"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/line_1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<RelativeLayout
android:layout_weight="1"
android:layout_width="200dp"
android:layout_height="wrap_content">
<TextView
android:id="@+id/day_2"
android:textColor="#fff"
android:text="Nhiệt Độ Ban Ngày"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="0"
android:id="@+id/nhietdo_1"
android:textColor="#fff"
android:layout_below="@id/day_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="C"
android:layout_marginLeft="10dp"
android:textColor="#fff"
android:layout_below="@id/day_2"
android:layout_toRightOf="@id/nhietdo_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<RelativeLayout
android:layout_weight="1"
android:layout_width="200dp"
android:layout_height="wrap_content">
<TextView
android:id="@+id/night_2"
android:textColor="#fff"
android:text="Nhiệt Độ Về Đêm"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="0"
android:id="@+id/nhietdo_2"
android:textColor="#fff"
android:layout_below="@id/night_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="C"
android:layout_marginLeft="10dp"
android:textColor="#fff"
android:layout_below="@id/night_2"
android:layout_toRightOf="@id/nhietdo_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
Tạo package activity
MainActivity.java
Java Android 2017
package com.example.lonely.demojson.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.lonely.demojson.R;
import com.example.lonely.demojson.model.MyPojo;
import com.example.lonely.demojson.network.APIManager;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private TextView date;
private TextView tv_text;
private TextView tv_category;
private TextView iconphrase_1;
private TextView iconphrase_2;
private ImageView icon_1;
private ImageView icon_2;
private TextView nhietdo_1;
private TextView nhietdo_2;
private Date ngayDate;
private String icon_01, icon_02;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
date = (TextView) findViewById(R.id.date);
tv_text = (TextView) findViewById(R.id.tv_text);
tv_category = (TextView) findViewById(R.id.tv_category);
iconphrase_1 = (TextView) findViewById(R.id.iconphrase_1);
iconphrase_2 = (TextView) findViewById(R.id.iconphrase_2);
icon_1 = (ImageView) findViewById(R.id.icon_1);
icon_2 = (ImageView) findViewById(R.id.icon_2);
nhietdo_1 = (TextView) findViewById(R.id.nhietdo_1);
nhietdo_2 = (TextView) findViewById(R.id.nhietdo_2);
getData();
}
private void getData() {
//Chú ý đoạn code màu xanh lá cây này lấy từ https://square.github.io/retrofit/
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APIManager.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIManager service = retrofit.create(APIManager.class);
service.apiGetNews().enqueue(new Callback<MyPojo>() {
@Override
public void onResponse(Call<MyPojo> call, Response<MyPojo> response) {
// Get data from server
MyPojo myPojo = response.body();
//convert date
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
String date_s = myPojo.getHeadline().getEndDate();
try {
ngayDate = formatDate.parse(date_s);
} catch (ParseException e) {
e.printStackTrace();
}
String ngay = formatDate.format(ngayDate);
//Set data text
date.setText(ngay);
tv_text.setText(myPojo.getHeadline().getText());
tv_category.setText(myPojo.getHeadline().getCategory());
iconphrase_1.setText(myPojo.getDailyForecasts().get(0).getNight().getIconPhrase());
iconphrase_2.setText(myPojo.getDailyForecasts().get(0).getDay().getIconPhrase());
nhietdo_1.setText(myPojo.getDailyForecasts().get(0).getTemperature().getMaximum().getValue());
nhietdo_2.setText(myPojo.getDailyForecasts().get(0).getTemperature().getMinimum().getValue());
// Set data image
String linkImage1 = myPojo.getDailyForecasts().get(0).getDay().getIcon();
String linkImage2 = myPojo.getDailyForecasts().get(0).getDay().getIcon();
if (linkImage1.length() == 1) {
icon_01 = 0 + linkImage1;
} else {
icon_01 = linkImage1;
}
if (linkImage1.length() == 1) {
icon_02 = 0 + linkImage2;
} else {
icon_02 = linkImage2;
}
String url_img1 = "https://apidev.accuweather.com/developers/Media/Default/WeatherIcons/" + icon_01 + "-s.png";
String url_img2 = "https://apidev.accuweather.com/developers/Media/Default/WeatherIcons/" + icon_02 + "-s.png";
Glide.with(MainActivity.this).load(url_img1).into(icon_1);
Glide.with(MainActivity.this).load(url_img2).into(icon_2);
}
@Override
public void onFailure(Call<MyPojo> call, Throwable t) {
Toast.makeText(MainActivity.this, "On Fail", Toast.LENGTH_SHORT).show();
}
});
}
}
Cấu trúc của project đã hoàn thiện
Backgroud Image
chào bạn. cho mình hỏi sao mình chạy bài của bạn nó cứ hiện app lên xong nó tự động tắt liền. bạn có thể giúp mình ko. cảm ơn
ReplyDelete