当前位置:网站首页>Androi weather
Androi weather
2022-06-13 00:45:00 【A happy wild pointer~】
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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" android:orientation="vertical" tools:context=".ui.me.WeatherFragment">
<TextView android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/appintro_bar_color" android:gravity="center" android:text=" The weather " android:textColor="@android:color/white" android:textSize="24sp" android:textStyle="bold" />
<LinearLayout android:layout_margin="20dp" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content">
<RelativeLayout android:layout_margin="10dp" android:gravity="center" android:layout_width="match_parent" android:layout_height="50dp">
<TextView android:id="@+id/province_tv" android:text=" Province :" android:gravity="center" android:layout_width="wrap_content" android:layout_height="match_parent"/>
<EditText android:id="@+id/province_edit" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@+id/province_tv" android:hint=" Please enter the weather province you want to query " />
</RelativeLayout>
<RelativeLayout android:layout_margin="10dp" android:gravity="center" android:layout_width="match_parent" android:layout_height="50dp">
<TextView android:id="@+id/city_tv" android:text=" City :" android:gravity="center" android:layout_width="wrap_content" android:layout_height="match_parent"/>
<EditText android:id="@+id/city_edit" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@+id/city_tv" android:hint=" Please enter the city of the province " />
</RelativeLayout>
<Button android:id="@+id/search" android:text=" Inquire about " android:layout_alignParentRight="true" android:layout_width="match_parent" android:layout_height="wrap_content"/>
</LinearLayout>
<TextView android:id="@+id/city_weather" android:text=" The weather in the city " android:gravity="center" android:layout_width="match_parent" android:layout_height="50dp" android:visibility="gone"/>
<LinearLayout android:id="@+id/weather_info" android:layout_margin="10dp" android:orientation="vertical" android:visibility="gone" android:layout_width="match_parent" android:layout_height="wrap_content">
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView android:text=" The weather :" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<TextView android:id="@+id/weather" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView android:text=" humidity :" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<TextView android:id="@+id/shidu" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView android:text=" Life advice :" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<TextView android:id="@+id/suggestion" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
public class WeatherFragment extends Fragment implements View.OnClickListener {
private String weatherCountry = "http://guolin.tech/api/china/";// Provinces and cities in China api
private String weatherProvince, weatherCity;// Obtained provinces id And the city id
private ArrayList<Province> provinceList;// China's provinces converge
private ArrayList<City> cityList;// A collection of cities in specific provinces
private String weatherUrl = "https://free-api.heweather.net/s6/weather/now?location=%s&key=%s";// Wind weather Free of charge api Interface
private String cityId;// Specific city weather id, Such as Zhanjiang ,"weather_id"=CN101281001
// Sign up with the wind weather Developer https://dev.heweather.com/
// Created apk Of user id as well as The apk Of key( The package name should be consistent )
private String userName = "HE2205202149311119";
private String key = "4c0f7dccc80748e49e20d0b99f27c43c";// I applied for key
private EditText mCityEdit;
/** * Inquire about */
private Button mSearch;
/** * The weather in the city */
private TextView mCityWeather;
private TextView mWeather;
private TextView mShidu;
/** * Province : */
private TextView mProvinceTv;
/** * Please enter the weather province you want to query */
private EditText mProvinceEdit;
String province, city;// Receive the string used by the input province and city
private LinearLayout mWeatherInfo;
private TextView mSuggestion;
private String TAG = "WeatherFragment";
private LocationClient mLocationClient = null;
@Override
public void onDestroy() {
mLocationClient.stop();
super.onDestroy();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyLocationListenner myListener = new MyLocationListenner();
mLocationClient = new LocationClient(getContext());
LocationClientOption option = new LocationClientOption();
option.setIsNeedAddress(true);
option.setAddrType("all");
mLocationClient.setLocOption(option);
mLocationClient.registerLocationListener(myListener);
mLocationClient.start();
}
private class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
try {
String province = location.getProvince();
String city = location.getCity();
mCityEdit.setText(city.substring(0,city.length()-1));
mProvinceEdit.setText(province.substring(0,province.length()-1
));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// Use SDK when , Account initialization is required in advance ( One global execution is enough )
HeConfig.init(userName, key);
// Personal developers 、 Enterprise developer 、 Ordinary users and other users who use free data need to switch to the free service domain name namely https://free-api.heweather.net/s6/sdk/
HeConfig.switchToFreeServerNode();
View root=inflater.inflate(R.layout.fragment_weather, container, false);
initView(
root
);
return root;
}
private void initView(View root) {
mCityEdit = (EditText) root.findViewById(R.id.city_edit);
mSearch = (Button) root.findViewById(R.id.search);
mSearch.setOnClickListener(this);
mCityWeather = (TextView) root.findViewById(R.id.city_weather);
mWeather = (TextView) root.findViewById(R.id.weather);
mShidu = (TextView) root.findViewById(R.id.shidu);
mProvinceTv = (TextView) root.findViewById(R.id.province_tv);
mProvinceEdit = (EditText) root.findViewById(R.id.province_edit);
mWeatherInfo = (LinearLayout) root.findViewById(R.id.weather_info);
mSuggestion = (TextView) root.findViewById(R.id.suggestion);
}
public void onClick(View v) {
System.out.println("111");
switch (v.getId()) {
default:
break;
case R.id.search:
province = mProvinceEdit.getText().toString().trim();
city = mCityEdit.getText().toString().trim();
queryWeather();
break;
}
}
private void queryWeather() {
provinceList = new ArrayList<Province>();// Provinces gather
cityList = new ArrayList<City>();// A collection of cities in specific provinces
new Thread() {
@Override
public void run() {
try {
//weatherCountry = "http://guolin.tech/api/china/"
URL url = new URL(weatherCountry);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();// To start a url The connection of , use HttpURLConnection Connection mode processing
connection.setRequestMethod("GET");// Set the method of requesting data for the connection object
connection.setConnectTimeout(3000);// Set the timeout time for the request of the connection object
// Convert the data stream returned by the request into a byte input stream object
InputStream is = connection.getInputStream();
// Converts a byte input stream object to a character input stream object
InputStreamReader isr = new InputStreamReader(is);
// Create character input buffer stream object
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String string;
// Read the text
while ((string = br.readLine()) != null) {
sb.append(string);
}
String result = sb.toString();
Log.d("WeatherFragment", "" + result);
JSONArray provinceArray = new JSONArray(result);
for (int i = 0; i < provinceArray.length(); i++) {
JSONObject provinceInfo = provinceArray.getJSONObject(i);// Get information about each province
Province provinceBean = new Province();// Create a province entity class object
Gson gson = new Gson();// establish Gson Parse object
// Reverse instantiation , take json The data is converted to the member variable value of the entity class object
provinceBean = gson.fromJson(provinceInfo.toString(), Province.class);
// Add the saved province object data into the province collection
provinceList.add(provinceBean);
}
for (Province pro : provinceList) {
// If the province is the province entered by the user
if (pro.getName().equals(province)) {
// Then splice Links
// Such as : Beijing weatherProvince = "http://guolin.tech/api/china/1/"
weatherProvince = weatherCountry + pro.getId() + "/";
}
}
Log.d("WeatherProvince", "" + weatherProvince);
// Such as : Beijing weatherProvince = "http://guolin.tech/api/china/1/"
url = new URL(weatherProvince);
connection = (HttpURLConnection) url.openConnection();// To start a url For the connection of HttpURLConnection Connection mode processing
connection.setRequestMethod("GET");// Set the method of requesting data for the connection object
connection.setConnectTimeout(3000);// Set the timeout time for the request of the connection object
// Convert the data stream returned by the request into a byte input stream object
is = connection.getInputStream();
// Converts a byte input stream object to a character input stream object
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
StringBuffer sb2 = new StringBuffer();
// Read the text
while ((string = br.readLine()) != null) {
sb2.append(string);
}
String result2 = sb2.toString();
Log.d("MainActivity2", "" + result2);
JSONArray cityArray = new JSONArray(result2);
for (int i = 0; i < cityArray.length(); i++) {
JSONObject cityInfo = cityArray.getJSONObject(i);// Get information about specific provinces and cities
City cityBean = new City();// Create a city entity class object
Gson gson = new Gson();// establish Gson Parse object
// Reverse instantiation , take json The data is converted to the member variable value of the entity class object
cityBean = gson.fromJson(cityInfo.toString(), City.class);
// Add the saved city object data into the city collection
cityList.add(cityBean);
}
for (City c : cityList) {
// If the city is the city entered by the user
if (c.getName().equals(city)) {
// Then splice Links
// Such as : Beijing weatherCity = "http://guolin.tech/api/china/1/1/"
weatherCity = weatherProvince + c.getId() + "/";
}
}
Log.d("WeatherCity", ""+weatherCity);
// Such as : Beijing weatherCity = "http://guolin.tech/api/china/1/1/"
url = new URL(weatherCity);
connection = (HttpURLConnection) url.openConnection();// To start a url For the connection of HttpURLConnection Connection mode processing
connection.setRequestMethod("GET");// Set the method of requesting data for the connection object
connection.setConnectTimeout(3000);// Set the timeout time for the request of the connection object
// Convert the data stream returned by the request into a byte input stream object
is = connection.getInputStream();
// Converts a byte input stream object to a character input stream object
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
StringBuffer sb3 = new StringBuffer();
// Read the text
while ((string = br.readLine()) != null) {
sb3.append(string);
}
String result3 = sb3.toString();
Log.d("MainActivity3", "" + result3);
JSONArray jsonArray = new JSONArray(result3);
JSONObject cityIdInfo = jsonArray.getJSONObject(0);
cityId=cityIdInfo.getString("weather_id");
// String concatenation
String weatherApi = String.format(weatherUrl, cityId, key);
Log.d("WeatherApi", "" + weatherApi);
queryWeather2();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public void queryWeather2(){
/** * Live weather * The actual weather is the weather conditions at the current time point and meteorological indexes such as temperature, humidity and wind pressure , Specific data included : Body feeling temperature 、 * Measured temperature 、 weather condition 、 wind 、 The wind speed 、 wind direction 、 Relative humidity 、 Atmospheric pressure 、 precipitation 、 Visibility, etc . * * @param context Context * @param location Address details * @param lang Multilingual , The default is simplified Chinese , Overseas cities default to English * @param unit Unit selection , Metric system (m) Or British system (i), The default is metric * @param listener Network access callback interface */
HeWeather.getWeatherNow(getContext(), cityId, Lang.CHINESE_SIMPLIFIED , Unit.METRIC , new HeWeather.OnResultWeatherNowBeanListener() {
@Override
public void onError(Throwable e) {
Log.i(TAG, "Weather Now onError: ", e);
}
@Override
public void onSuccess(Now dataObject) {
Log.i(TAG, " Weather Now onSuccess: " + new Gson().toJson(dataObject));
// First judge the returned status Whether it is right , When status Get data when correct , if status Incorrect , You can see status Corresponding Code Value to find the reason
if ( Code.OK.getCode().equalsIgnoreCase(dataObject.getStatus()) ){
// The data is returned
Basic basic=dataObject.getBasic();
String location=basic.getLocation();
mCityWeather.setText(location+" The weather of ");
NowBase now = dataObject.getNow();
String tmp=now.getTmp();
String cond_txt=now.getCond_txt();
String wind_dir=now.getWind_dir();
mWeather.setText(" Current temperature :"+tmp+"℃,"+cond_txt+","+wind_dir);
String hum=now.getHum();
mShidu.setText(hum+"%");
} else {
// Check the reason why the returned data failed
String status = dataObject.getStatus();
Code code = Code.toEnum(status);
Log.i(TAG, "failed code: " + code);
}
}
});
HeWeather.getWeatherLifeStyle(getContext(),cityId, new HeWeather.OnResultWeatherLifeStyleBeanListener() {
@Override
public void onError(Throwable throwable) {
}
@Override
public void onSuccess(Lifestyle lifestyle) {
List<LifestyleBase> lifestyleBases=lifestyle.getLifestyle();
String shushidu=lifestyleBases.get(0).getBrf();// Comfort index
String shushidu2=lifestyleBases.get(0).getTxt();// Comfort recommendations
String sport=lifestyleBases.get(3).getBrf();// Motor index
String sport2=lifestyleBases.get(3).getTxt();// Sports advice
String cw=lifestyleBases.get(6).getBrf();// Car wash index
String cw2=lifestyleBases.get(6).getTxt();// Car washing suggestions
System.out.println("sdfsdf");
mSuggestion.setText(" Comfort index :"+shushidu+"\n" +
" Comfort recommendations :"+shushidu2+"\n" +
" Motor index :"+sport+"\n" +
" Sports advice :"+sport2+"\n" +
" Car wash index :"+cw+"\n" +
" Car washing suggestions :"+cw2+"\n");
mCityWeather.setVisibility(View.VISIBLE);
mWeatherInfo.setVisibility(View.VISIBLE);
}
});
}
}
public class Province {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class City {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".ui.video.VideoFragment" >
<LinearLayout android:layout_width="match_parent" android:layout_height="200dp" android:gravity="center" android:orientation="vertical" android:background="@color/purple_500">
<de.hdodenhof.circleimageview.CircleImageView android:id="@+id/circleImageView" android:layout_width="96dp" android:layout_height="96dp" android:src="@drawable/default_head" app:civ_border_color="#fff" app:civ_border_width="2dp" />
<TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" Click login " android:textColor="#fff" android:textSize="18sp" android:layout_marginTop="10dp"/>
</LinearLayout>
<androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" app:cardCornerRadius="10dp" app:cardElevation="10dp" android:layout_margin="10dp">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<LinearLayout android:id="@+id/linearLayout_run" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:orientation="vertical" android:padding="10dp">
<ImageView android:layout_width="30dp" android:layout_height="30dp" app:srcCompat="@drawable/calendar_icon" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:text=" The calendar " />
</LinearLayout>
<View android:layout_width="1dp" android:layout_height="match_parent" android:background="#ebebeb" />
<LinearLayout android:id="@+id/linearLayout_star" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:orientation="vertical" android:padding="10dp">
<ImageView android:layout_width="30dp" android:layout_height="30dp" app:srcCompat="@drawable/constellation_icon" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:text=" The constellation " />
</LinearLayout>
<View android:layout_width="1dp" android:layout_height="match_parent" android:background="#ebebeb" />
<LinearLayout android:id="@+id/linearLayout_ty" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:orientation="vertical" android:padding="10dp">
<ImageView android:layout_width="30dp" android:layout_height="30dp" app:srcCompat="@drawable/scraw_icon" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:text=" Doodle " />
</LinearLayout>
<View android:layout_width="1dp" android:layout_height="match_parent" android:background="#ebebeb" />
<LinearLayout android:id="@+id/linearLayout_map" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:orientation="vertical" android:padding="10dp">
<ImageView android:layout_width="30dp" android:layout_height="30dp" app:srcCompat="@drawable/map_icon" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:text=" Map " />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" app:cardCornerRadius="10dp" app:cardElevation="10dp" android:layout_margin="10dp">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<LinearLayout android:id="@+id/linearLayout_weather" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="horizontal" android:padding="10dp">
<ImageView android:layout_width="30dp" android:layout_height="30dp" app:srcCompat="@drawable/collection_icon" />
<TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text=" The weather " android:layout_marginStart="10dp"/>
<ImageView android:layout_width="20dp" android:layout_height="20dp" app:srcCompat="@drawable/iv_right_arrow" />
</LinearLayout>
<View android:layout_width="match_parent" android:layout_height="1dp" android:background="#ebebeb"/>
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="horizontal" android:padding="10dp">
<ImageView android:layout_width="30dp" android:layout_height="30dp" app:srcCompat="@drawable/setting_icon" />
<TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text=" Set up " android:layout_marginStart="10dp"/>
<ImageView android:layout_width="20dp" android:layout_height="20dp" app:srcCompat="@drawable/iv_right_arrow" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
边栏推荐
- Assembly language learning
- RCC clock configuration of stm32f401
- Hard (magnetic) disk (II)
- MySQL lpad() and rpad() concatenate string functions with specified length
- Basic operations of FreeMarker
- 6.824 Lab 3A: Fault-tolerant Key/Value Service
- 6.824 Lab 2: Raft
- Oceanbase is the leader in the magic quadrant of China's database in 2021
- Opencv face recognition of ros2 foxy~galactic~humble
- 单片机串口中断以及消息收发处理——对接受信息进行判断实现控制
猜你喜欢

人神共愤,唐山“群殴女性事件”细节...

Development notes of Mongoose
![[imx6ull] video monitoring project (USB camera +ffmepeg)](/img/f9/1a7b68083b52c973336db9044b52c2.jpg)
[imx6ull] video monitoring project (USB camera +ffmepeg)

Static analysis of malicious code

RCC clock configuration of stm32f401

Summary of openstack installation problems

Arduino control soil moisture sensor

Druid reports an error connection holder is null
![[Error] invalid use of incomplete type 使用了未定义的类型](/img/8a/7cb5d270cfd8831ddc146687fe4499.png)
[Error] invalid use of incomplete type 使用了未定义的类型

Maybe we can figure out the essence of the Internet after the dust falls
随机推荐
[ciscn2019 North China Day2 web1]hack world --buuctf
Ad14 component pin name disappeared
JPA execution failed in scheduled task -executing an update/delete query transactionrequiredexception
从ADK的WinPE自己手动构建自己的PE
Arduino controls tb6600 driver +42 stepper motor
Stack overflow learning summary
pytorch是什么?解释pytorch的基本概念
Kotlin 协程挂起函数 suspend 关键字
单片机串口中断以及消息收发处理——对接受信息进行判断实现控制
6.824 Lab 3B: Fault-tolerant Key/Value Service
Kotlin 协程的作用域构建器 coroutineScope与runBlocking 与supervisorScope,协程同步运行,协程挂掉的时候其他协程如何不被挂掉。
6.824 Lab 3A: Fault-tolerant Key/Value Service
人神共愤,唐山“群殴女性事件”细节...
Leetcode weekly -- April to May
深度学习每周期的步数多少合适?
三栏简约typecho主题Lanstar/蓝星typecho主题
[JS] solve the problem that removeeventlistener is invalid after the class listening event from new is bound to this
What are the conditions of index invalidation?
Blinker FAQs
Win10 home vs pro vs enterprise vs enterprise LTSC