全球疫情統計APP圖表形式展示
全球疫情統計APP圖表展示:
將該任務分解成三部分來逐個實現:
①爬取全球的疫情資料儲存到雲伺服器的MySQL上
②在web專案裡新增一個servlet,通過引數的傳遞得到對應的json資料
③設計AndroidAPP,通過時間和地名來訪問伺服器上的對應的servlet來獲取json資料,然後將它與圖表聯絡
第一步:由前面的web專案的積累,爬取全球的資料就很容易,利用Python爬蟲爬取丁香醫生上的資料,儲存到伺服器上的MySQL
from os import path import requests from bs4 import BeautifulSoup import json import pymysql import numpy as np import time url = 'https://ncov.dxy.cn/ncovh5/view/pneumonia?from=timeline&isappinstalled=0' #請求地址 headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}#建立頭部資訊 response = requests.get(url,headers = headers) #傳送網路請求 #print(response.content.decode('utf-8'))#以位元組流形式列印網頁原始碼 content = response.content.decode('utf-8') soup = BeautifulSoup(content, 'html.parser') listB = soup.find_all(name='script',attrs={"id":"getListByCountryTypeService2true"}) world_messages = str(listB)[95:-21] world_messages_json = json.loads(world_messages) # print(listB) # print(world_messages) worldList = [] for k in range(len(world_messages_json)): worldvalue = (world_messages_json[k].get('id'),time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())), world_messages_json[k].get('continents'),world_messages_json[k].get('provinceName'), world_messages_json[k].get('cityName'),world_messages_json[k].get('currentConfirmedCount'), world_messages_json[k].get('suspectedCount'),world_messages_json[k].get('curedCount'),world_messages_json[k].get('deadCount'),world_messages_json[k].get('locationId'), world_messages_json[k].get('countryShortCode'),) worldList.append(worldvalue) db = pymysql.connect("139.129.221.11", "root", "fengge666", "yiqing", charset='utf8') cursor = db.cursor() #sql_clean_world = "TRUNCATE TABLE world_map" sql_world = "INSERT INTO world_map values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" worldTuple = tuple(worldList) # # try: # cursor.execute(sql_clean_world) # db.commit() # except: # print('執行失敗,進入回撥1') # db.rollback() try: cursor.executemany(sql_world,worldTuple) db.commit() except: print('執行失敗,進入回撥3') db.rollback() db.close()
第二步:在之前的web專案裡增加一個worldServlet來通過傳遞過來的引數(時間,地名)來獲取伺服器裡資料庫的資訊,然後以json的資料格式返回。
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import Bean.World; import Dao.predao; /** * Servlet implementation class worldServlet */ @WebServlet("/worldServlet") public class worldServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public worldServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); String date=request.getParameter("date"); String name=request.getParameter("name"); //System.out.println("666:"+date+" "+name); predao dao=new predao(); World bean=dao.findworld(date,name); //if(bean==null) // System.out.println("world為空"); Gson gson = new Gson(); String json = gson.toJson(bean); response.getWriter().write(json); //System.out.println(json); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
第三步:Android端的設計,也要細分成兩部分。第一部分設計介面的樣式以及圖表的展示,第二部分就是實現Android端訪問遠端伺服器裡的資料獲取對應的資訊,然後再配置到Android的圖表裡。
第一部分實現介面的設計,以及圖表。
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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" tools:context=".MainActivity"> <TextView android:id="@+id/tv_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginLeft="16dp" android:layout_marginTop="16dp" android:text="時間" android:textSize="25dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/et_time" android:layout_width="250dp" android:layout_height="46dp" android:layout_marginEnd="100dp" android:layout_marginRight="100dp" android:gravity="center" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="@+id/tv_time" /> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="99dp" android:paddingTop="110dp" android:text="國家名" android:textSize="25dp" app:layout_constraintBottom_toTopOf="@+id/chartshow_wb" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/et_name" android:layout_width="250dp" android:layout_height="60dp" android:gravity="center" android:paddingLeft="120dp" app:layout_constraintBottom_toBottomOf="@+id/bt_ly" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="@+id/bt_ly" app:layout_constraintTop_toTopOf="@+id/tv_time" /> <LinearLayout android:id="@+id/bt_ly" android:layout_width="409dp" android:layout_height="209dp" android:layout_marginTop="16dp" android:gravity="center_horizontal" android:paddingTop="150dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <Button android:id="@+id/linechart_bt" style="?android:attr/buttonStyleSmall" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="折線圖" /> <Button android:id="@+id/barchart_bt" style="?android:attr/buttonStyleSmall" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="柱狀圖" /> <Button android:id="@+id/piechart_bt" style="?android:attr/buttonStyleSmall" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="餅狀圖" /> </LinearLayout> <WebView android:id="@+id/chartshow_wb" android:layout_width="408dp" android:layout_height="0dp" android:layout_gravity="center" android:layout_marginBottom="4dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/tv_name"> </WebView> </androidx.constraintlayout.widget.ConstraintLayout>
介面有三部分組成:其一是時間選擇框和地名選擇,其二就是三個按鈕(折線,柱狀,圓餅),其三就是webview來展示我們的圖表介面
圖表的設計,首先要將echart.min.js放在AndroidStudio裡的assets裡,然後再放入自己的圖表html程式碼,通過json資料來給圖表進行賦值。同樣在主頁面對webview進行一堆設定,允許執行指令碼,設定它的loadURL,然後設計三個按鈕的點選方式,同時啟動不同的指令碼。
<!DOCTYPE html> <!-- release v4.3.6, copyright 2014 - 2017 Kartik Visweswaran --> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Android使用Echarts示例</title> </head> <body> <div id="main" style="width: 100%; height: 350px;"></div> <script src="./echarts.min.js"></script> <script type="text/javascript"> window.addEventListener("resize",function(){ option.chart.resize(); }); //初始化路徑 var myChart; // 通用屬性定義 var options = { title : { text : "Echart測試" }, tooltip : { show : false }, toolbox : { show : false }, }; function doCreatChart(type,jsondata){ // 基於準備好的dom,初始化echarts例項 var myChart = echarts.init(document.getElementById('main')); if(type=='line'||type=='bar') { // 指定圖表的配置項和資料 options = { title: { text: '人數' }, tooltip: {}, legend: { data:['疫情狀況'] }, xAxis: { data: ["確診","疑似","治癒","死亡"] }, yAxis: {}, series: [{ name: '患者數', type: type, data: jsondata }] }; }else{ options = { series : [ { type:type, radius : '55%', center: ['50%', '60%'], data:[ {value:335, name:'確診'}, {value:310, name:'疑似'}, {value:234, name:'治癒'}, {value:135, name:'死亡'} ] } ] }; } // 使用剛指定的配置項和資料顯示圖表。 myChart.setOption(options); } </script> </body> </html>View Code
第二部分就是通過Android端的http訪問來獲取伺服器端的json資料,在將該資料傳到圖表的資料格式裡。
MainActivity
package com.example.yiqing; import android.app.Activity; import android.app.DatePickerDialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.webkit.WebView; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Calendar; public class MainActivity extends Activity implements View.OnClickListener { private EditText meditText,etname; private Button linechart_bt,barchart_bt,piechart_bt; private WebView chartshow_wb; private String name; private String data; private world bean; private String[] url; private String[] json = {new String()}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); bean=new world(); } private void getJson(final String address) { new Thread(new Runnable(){ @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL(address); Log.d("address",address); connection=(HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(10000); connection.setReadTimeout(5000); connection.connect(); int code=connection.getResponseCode(); if(code==200){ Log.i("accept:","連結成功"); InputStream is=connection.getInputStream(); String state = getStringFromInputStream(is); JSONObject jsonObject = new JSONObject(state); //String json=jsonObject.toString(); bean.setConfirmed(jsonObject.getString("confirmed")); bean.setCured(jsonObject.getString("cured")); bean.setDead(jsonObject.getString("dead")); bean.setSuspected(jsonObject.getString("suspected")); json[0] ="["+bean.getConfirmed()+","+bean.getSuspected()+","+bean.getCured()+","+bean.getDead()+"]"; //Log.i(etname.getText().toString(),json[0]); } } catch (Exception e) { e.printStackTrace(); }finally{ if(connection!=null){ connection.disconnect(); } } } }).start(); } private static String getStringFromInputStream(InputStream is) throws Exception{ ByteArrayOutputStream baos=new ByteArrayOutputStream(); byte[] buff=new byte[1024]; int len=-1; while((len=is.read(buff))!=-1){ baos.write(buff, 0, len); } is.close(); String html=baos.toString(); baos.close(); return html; } /** * 初始化頁面元素 */ private void initView(){ linechart_bt=(Button)findViewById(R.id.linechart_bt); barchart_bt=(Button)findViewById(R.id.barchart_bt); piechart_bt=(Button)findViewById(R.id.piechart_bt); etname=(EditText) findViewById(R.id.et_name); meditText=(EditText) findViewById(R.id.et_time); meditText.setOnClickListener(this); linechart_bt.setOnClickListener(this); barchart_bt.setOnClickListener(this); piechart_bt.setOnClickListener(this); chartshow_wb=(WebView)findViewById(R.id.chartshow_wb); //進行webwiev的一堆設定 //開啟本地檔案讀取(預設為true,不設定也可以) chartshow_wb.getSettings().setAllowFileAccess(true); //開啟指令碼支援 chartshow_wb.getSettings().setJavaScriptEnabled(true); chartshow_wb.loadUrl("file:///android_asset/echarts.html"); name=etname.getText().toString().trim(); data=meditText.getText().toString().trim(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.et_time: Calendar calendar = Calendar.getInstance(); DatePickerDialog datePickerDialog=new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { if(month<10) MainActivity.this.meditText.setText(year + "-" +"0"+(month+1) + "-" + dayOfMonth); else MainActivity.this.meditText.setText(year + "-" + (month+1) + "-" + dayOfMonth); } },calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); datePickerDialog.show(); break; case R.id.linechart_bt: url = new String[]{"http://139.129.221.11/yiqing/worldServlet?date="}; url[0] = url[0] + meditText.getText().toString()+"&name="+etname.getText().toString(); getJson(url[0]); //Log.i("json:",json[0]); //String json="["+bean.getConfirmed()+","+bean.getSuspected()+","+bean.getCured()+","+bean.getDead()+"]"; Log.i("jsonline:",json[0]); chartshow_wb.loadUrl("javascript:doCreatChart('line',"+json[0]+");"); //Toast.makeText(MainActivity.this,"折線圖",Toast.LENGTH_SHORT).show(); break; case R.id.barchart_bt: url = new String[]{"http://139.129.221.11/yiqing/worldServlet?date="}; url[0] = url[0] + meditText.getText().toString()+"&name="+etname.getText().toString(); getJson(url[0]); chartshow_wb.loadUrl("javascript:doCreatChart('bar',"+json[0]+");"); break; case R.id.piechart_bt: url = new String[]{"http://139.129.221.11/yiqing/worldServlet?date="}; url[0] = url[0] + meditText.getText().toString()+"&name="+etname.getText().toString(); getJson(url[0]); chartshow_wb.loadUrl("javascript:doCreatChart('pie',"+json[0]+");"); break; default: break; } } }View Code
製作中遇到的困難以及解決方案:
①遠端資料庫的連線無法訪問,發現自己的伺服器3306埠未開放同時要對伺服器裡的mysql裡的一些東西進行配置:我參考的部落格是-->遠端連線資料庫
②本來想的是進行jdbc訪問遠端資料庫,奈何整了大半天硬是連不上,最終換了一種方式採取http訪問伺服器裡的資料。
③安卓新版本預設不允許使用明文網路傳輸,
解決辦法如下,在AndroidManifest.xml檔案的<application標籤中,加入一句"android:usesCleartextTraffic="true",允許應用進行明文傳輸即可。
或者採用:
更改 AndroidManifest 的 application 標籤下的配置。
新增 networkSecurityConfig(網路安全配置)。
android:networkSecurityConfig="@xml/network_security_config"
network_security_config 檔案內容如下:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>
&n