移动端疫情展示

移动端疫情展示,第1张

概述设计思想:首先利用python爬取疫情情况,然后用Androidstudio制作可视化界面。爬取代码:fromosimportpathimportrequestfrombs4importBeautifulSoupimportjsonimportpymysqlimportnumpyasnpimporttimeimportrequestsurl='https:/cov.dxy.cncovh5/view/

设计思想:

首先利用python爬取疫情情况,然后用AndroID studio制作可视化界面。

爬取代码:

from os import path

import request

from bs4 import BeautifulSoup

import Json

import pyMysqL

import numpy as np

import time

import requests

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)  # 发送网络请求

content = response.content.decode('utf-8')

soup = BeautifulSoup(content, 'HTML.parser')

ListA = soup.find_all(name='script', attrs={"ID": "getAreaStat"})

# 世界确诊

ListB = soup.find_all(name='script', attrs={"ID": "getListByCountryTypeService2"})

account = str(ListA)

messages = account[52:-21]

messages_Json = Json.loads(messages)

valuesList = []

cityList = []

con = len(messages_Json)

k = 0

for i in range(len(messages_Json)):

    k = k + 1

    value = (

    k, time.strftime('%Y-%m-%d %H:%M:%s', time.localtime(time.time())), messages_Json[i].get('provinceShortname'), None,

    messages_Json[i].get('confirmedCount'), messages_Json[i].get('SUSPECTedCount'), messages_Json[i].get('curedCount'),

    messages_Json[i].get('deadCount'), messages_Json[i].get('locationID'))

    valuesList.append(value)

    cityValue = messages_Json[i].get('citIEs')

    for j in range(len(cityValue)):

        con = con + 1

        cityValueList = (

        con, time.strftime('%Y-%m-%d %H:%M:%s', time.localtime(time.time())), messages_Json[i].get('provinceShortname'),

        cityValue[j].get('cityname'), cityValue[j].get('confirmedCount'), cityValue[j].get('SUSPECTedCount'),

        cityValue[j].get('curedCount'), cityValue[j].get('deadCount'), cityValue[j].get('locationID'))

        cityList.append(cityValueList)

db = pyMysqL.connect("localhost", "root", "123456", "yiqing1", charset='utf8')

cursor = db.cursor()

array = np.asarray(valuesList[0])

sql_clean_province = "TruncATE table info3"

sql = "INSERT INTO info3 values (%s,%s,%s,%s,%s,%s,%s,%s,%s) "

cityTuple = tuple(cityList)

try:

    cursor.execute(sql_clean_province)

    db.commit()

except:

    print('执行失败,进入回调1')

    db.rollback()

try:

    cursor.executemany(sql, value_tuple)

    db.commit()

except:

    print('执行失败,进入回调3')

    db.rollback()

try:

    cursor.executemany(sql, cityTuple)

    db.commit()

except:

    print('执行失败,进入回调4')

    db.rollback()

db.close()

 

截图:

 

 

AndroID studio代码:

package com.example.application;

 

import androIDx.appcompat.app.AppCompatActivity;

 

import androIDx.appcompat.app.AppCompatActivity;

 

import androID.annotation.Suppresslint;

import androID.app.Activity;

import androID.icu.lang.UCharacter;

import androID.os.Bundle;

import androID.os.Handler;

import androID.os.Message;

import androID.text.Editable;

import androID.text.TextWatcher;

import androID.vIEw.VIEw;

import androID.Widget.AdapterVIEw;

import androID.Widget.ArrayAdapter;

import androID.Widget.button;

import androID.Widget.EditText;

import androID.Widget.ListVIEw;

import androID.Widget.Spinner;

import androID.Widget.TextVIEw;

 

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;

 

public class MainActivity extends AppCompatActivity {

    private button bt_send;

    private EditText et_content;

    private static final int TEST_USER_SELECT = 1;

    private String content;

    private Spinner conditionSpinner;

    private String condition;

    private ListVIEw lv;

    String[] strs = new String[]{};

    @Suppresslint("HandlerLeak")

    private Handler mHandler = new Handler(){

        @OverrIDe

        public voID handleMessage(Message msg){

 

            switch(msg.what){

                case TEST_USER_SELECT:

                    String s = (String)msg.obj;

                    strs = s.split("  ");

                    lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,R.layout.support_simple_spinner_dropdown_item,strs));

                    break;

            }

        }

    };

    @OverrIDe

    protected voID onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentVIEw(R.layout.activity_main);

        bt_send = findVIEwByID(R.ID.bt_send);

        et_content = findVIEwByID(R.ID.et_content);

        et_content.addTextChangedListener(new TextWatcher() {

            @OverrIDe

            public voID beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @OverrIDe

            public voID onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @OverrIDe

            public voID afterTextChanged(Editable s) {

                content = s.toString();

            }

        });

        conditionSpinner = findVIEwByID(R.ID.condition);

        final String [] data = {"国家","时间"};

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,data);

        conditionSpinner.setAdapter(adapter);

        conditionSpinner.setonItemSelectedListener(new Spinner.OnItemSelectedListener(){

 

            @OverrIDe

            public voID onItemSelected(AdapterVIEw<?> parent, VIEw vIEw, int position, long ID) {

                //取得选中的值

                condition = data[position];

                //设置显示当前选择的项

                parent.setVisibility(VIEw.VISIBLE);

            }

            @OverrIDe

            public voID onnothingSelected(AdapterVIEw<?> parent) {

 

            }

        });

        System.out.println(condition);

        lv = findVIEwByID(R.ID.lv);

 

    }

    @OverrIDe

    protected voID onStart(){

        super.onStart();

        bt_send.setonClickListener(new VIEw.OnClickListener() {

            @OverrIDe

            public voID onClick(VIEw v) {

                //执行查询 *** 作

                //连接数据库进行 *** 作需要在主线程 *** 作

                new Thread(new Runnable() {

                    @OverrIDe

                    public voID run() {

                        //调用数据库帮助类中的方法取数据

                        List<Data> List = DB.searchDataByCountry(condition,content);

                        Message message = mHandler.obtainMessage();

                        String s = "";

                        for(int i=0;i<List.size();i++){

                            s += "时间:"+List.get(i).getLastUpdateTime()+"  ";

                            s += List.get(i).getCountryname()+"确诊人数为:  ";

                            s += List.get(i).getConfirmed()+"  ";

                        }

                        message.what = TEST_USER_SELECT;

                        message.obj = s;

                        mHandler.sendMessage(message);

                    }

                }).start();

            }

        });

    }

}

 

package com.example.application;

 

public class Data {

    private int ID;

    private String countryname;

    private String confirmed;

    private String SUSPECTed;

    private String dead;

    private String healed;

    private String lastUpdateTime;

 

 

    public int getID() {

        return ID;

    }

 

    public voID setID(int ID) {

        this.ID = ID;

    }

 

    public String getCountryname() {

        return countryname;

    }

 

    public voID setCountryname(String countryname) {

        this.countryname = countryname;

    }

 

    public String getConfirmed() {

        return confirmed;

    }

 

    public voID setConfirmed(String confirmed) {

        this.confirmed = confirmed;

    }

 

    public String getSUSPECTed() {

        return SUSPECTed;

    }

 

    public voID setSUSPECTed(String SUSPECTed) {

        this.SUSPECTed = SUSPECTed;

    }

 

    public String getDead() {

        return dead;

    }

 

    public voID setDead(String dead) {

        this.dead = dead;

    }

 

    public String getHealed() {

        return healed;

    }

 

    public voID setHealed(String healed) {

        this.healed = healed;

    }

 

    public String getLastUpdateTime() {

        return lastUpdateTime;

    }

 

    public voID setLastUpdateTime(String lastUpdateTime) {

        this.lastUpdateTime = lastUpdateTime;

    }

}

 

package com.example.application;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.sqlException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

public class DB {

    private static String driver = "com.MysqL.jdbc.Driver";

    private static String url = "jdbc:MysqL://192.168.0.104:3306/yiqing1?characterEnCoding=utf-8";

    private static String user = "root";//用户名

    private static String password = "123456";//密码

 

    public static Connection getConn(){

        Connection conn = null;

        try {

            Class.forname(driver);

            conn = (Connection) DriverManager.getConnection(url,user,password);//获取连接

        } catch (ClassNotFoundException e) {

            e.printstacktrace();

        } catch (sqlException e) {

            e.printstacktrace();

        }

        return conn;

    }

    public static List<Data>  searchDataByCountry(String condition,String country_name){

        List<Data> List = new ArrayList<>();

        Connection connection = getConn();

        String sql = "";

        //System.out.println(condition);

        if(condition.equals("国家")){

            sql = "select * from worlddata where countryname like ?";

        }

        if(condition.equals("时间")){

            sql = "select * from worlddata where lastUpdateTime like ?";

        }

        System.out.println(country_name);

        if(connection !=null){

            try {

                PreparedStatement ps = connection.prepareStatement(sql);

                if(ps!=null){

                    ps.setString(1,"%"+country_name+"%");

                    ResultSet rs = ps.executequery();

                    if(rs!=null){

                        while(rs.next()){

                            Data data = new Data();

                            data.setID(rs.getInt("ID"));

                            data.setCountryname(rs.getString("countryname"));

                            data.setConfirmed(rs.getString("confirmed"));

                            data.setSUSPECTed(rs.getString("SUSPECTed"));

                            data.setDead(rs.getString("dead"));

                            data.setHealed(rs.getString("healed"));

                            data.setLastUpdateTime(rs.getString("lastUpdateTime"));

                            List.add(data);

                        }

                        connection.close();

                        ps.close();

                        return List;

                    }else{

                        return null;

                    }

                }else{

                    return null;

                }

            } catch (sqlException e) {

                e.printstacktrace();

                return null;

            }

        }else{

            return null;

        }

 

    }

}

 

<?xml version="1.0" enCoding="utf-8"?>

<relativeLayout 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">

 

    <Spinner

        androID:ID="@+ID/condition"

        androID:layout_wIDth="wrap_content"

        androID:layout_height="wrap_content"

        />

    <EditText

        androID:ID="@+ID/et_content"

        androID:layout_wIDth="180dp"

        androID:layout_height="40dp"

        androID:layout_toRightOf="@+ID/condition"

        />

    <button

        androID:ID="@+ID/bt_send"

        androID:layout_wIDth="match_parent"

        androID:layout_height="wrap_content"

        androID:text="查询"

        androID:layout_toRightOf="@+ID/et_content"

        />

 

    <ListVIEw

        androID:ID="@+ID/lv"

        androID:layout_wIDth="match_parent"

        androID:layout_height="match_parent"

        androID:layout_margintop="50dp"

        />

 

</relativeLayout>

总结

以上是内存溢出为你收集整理的移动端疫情展示全部内容,希望文章能够帮你解决移动端疫情展示所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1058639.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存