Android, get weather information based on the knowledge that the weather
Why write this blog, mainly to consolidate the knowledge about JSON, so we will see a lot of text partial explanation, of course, the final code I posted this point do not worry, you do not want to see the explanation can skip to achieve section, you can also download the source, free of charge .
JSON
Introducing JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format. Easy to read and write. It is easy for machines to parse and generate. It is based on JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999 a subset. Talking is " JSON is a there is a certain order of the array / object ."
JSON object
Characterized in that a plurality of JSON object attributes are {} enclosed, which is below a JSON object.
{
"Area": "Beijing Haidian",
"name": "Li Dazui",
"Age": 25
}
JSON array
JSON array actually comprises a plurality of objects in a collection of JSON, arrays are an array brackets [] enclosed, can see JSON array is the same JSON object composition. We can call it typical of JSON array
[{
"Area": "Guangdong",
"name": "Brother pheasant",
"Age": 25
}, {
"Area": "Guangxi",
"name": "Boo Boo",
"Age": 26 is
}]
with typical JSON array, there certainly atypical JSON array
[{
"Area": "Jiangsu",
"name": "Xuzhou",
"Age": 25
}, {
"City": "Jiangsu",
"Weather": "clear",
}]
JSON parsing
JSON parsing there are a lot of ways, the official is JSONObect parsing, Google's open source library GSON, there are some third-party open source libraries such as: Jackson, FastJSON. I choose here is the official JSONObject provided for resolution. Specific implementation will go into detail in a later section achieved.
Android obtaining Weather
The process of obtaining weather
1: find a free weather API (heart to know weather)
2: Access API (requires API Key), get JSON data
3: parsing JSON data to get weather information
Get heart to know the weather API key
First login knew that the weather's official website , of course you need to be registered, after login as shown below
After logging click on the upper right corner of the console , as shown below
to select product management under added products , choose Free , of course, if you have money select Developer Edition or enterprise Edition is also possible. Then back to the product interface, you can see that we get the public key , the private key is very important but we do not have access, a public key is enough , I am nothing to do has added a key.
Get heart to know the weather API
Click API documentation , you can view the API examples and explanations knew the weather, a direct shot me down here. The first line is an example of the API, following the example of the API parameter descriptions should be no need for me to explain it, pay attention to fill in behind the KEY is that we get the API public key
that we this API to access the next example, you can browse the search box is an example of the image above to see what it can get
What's this? Is not that JSON data? We can generally see which contains information about the city, weather, language, etc., and our task is to parse the JSON data will come out into the way normal people can understand the information.
Code section
OKhttp we use to access the API, so to add OKhttp closure, add the following code in build.Gradle the dependencies {}, after addition remember to synchronize files Gradle
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
AndroidMainfest.xml
add a line privileges (permissions apply network)
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
activity_main.xml
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/send_request"
android:text="Send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:hint="原始JSON数据"
android:id="@+id/response"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:hint="city"
android:id="@+id/City"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:hint="weather"
android:id="@+id/Weather"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:hint="temperature"
android:id="@+id/Temperature"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity.xml
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView responseText;
private EditText weather;
private EditText city;
private EditText temperature;
private String Weather;
private String CityName;
private String Tempeature;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response);
weather = (EditText) findViewById(R.id.Weather);
city = (EditText) findViewById(R.id.City);
temperature = (EditText) findViewById(R.id.Temperature);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithOkHttp();
}
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();//创建一个OkHttp实例
Request request = new Request.Builder().url("https://api.seniverse.com/v3/weather/now.json?key=SrvH71t8JeTOXNLJP&location=beijing&language=zh-Hans&unit=c").build();//创建Request对象发起请求,记得替换成你自己的key
Response response = client.newCall(request).execute();//创建call对象并调用execute获取返回的数据
String responseData = response.body().string();
showResPonse(responseData);//显示原始数据和解析后的数据
parseJSONWithJSONObject(responseData);//解析SSON数据
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseJSONWithJSONObject(String jsonData) {//用JSONObect解析JSON数据
try {
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray results = jsonObject.getJSONArray("results"); //得到键为results的JSONArray
JSONObject now = results.getJSONObject(0).getJSONObject("now");//得到键值为"now"的JSONObject
JSONObject location = results.getJSONObject(0).getJSONObject("location"); //得到键值为location的JSONObject
Weather = now.getString("text");//得到"now"键值的JSONObject下的"text"属性,即天气信息
CityName = location.getString("name"); //获得城市名
Tempeature = now.getString("temperature"); //获取温度
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showResPonse(final String response) {
runOnUiThread(new Runnable() {//切换到主线程,ui界面的更改不能出现在子线程,否则app会崩溃
@Override
public void run() {
responseText.setText(response);
city.setText(CityName);
weather.setText(Weather);
temperature.setText(Tempeature);
}
});
}
}
To achieve the following results
I only resolved weather, temperature and information among three cities, the other rigidly applied should not be difficult,
Advanced - Get weather information of any city
If I want to get any of the city's weather, how to achieve it? Actually very simple, as long as the value of the address of the location API can be changed to a value that can be entered. I do not want to repeat too much of code to write, I will upload the source code together, for your reference. achieve results is as follows.