天气预报app

Posted 星⁠辞归也

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了天气预报app相关的知识,希望对你有一定的参考价值。

一、在Java代码中初始化界面

在MainActivity中初始化ViewPager界面

    private void initPager() {
        //创建Fragment对象添加到ViewPager数据源当中
        for (int i=0;i<cityList.size();i++){  //使用for循环将城市集合中的内容添加到fragment集合中
            WeatherFragment weatherFragment = new WeatherFragment(); 
            Bundle bundle = new Bundle();    
            bundle.putString("city",cityList.get(i));  //使用bundle存储城市名,传到fragment中
            weatherFragment.setArguments(bundle);
            fragmentList.add(weatherFragment);
        }
        //将fragment集合传入fragment适配器中
                FragmentPagerAdapter fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager(),fragmentList);
        showVp.setAdapter(fragmentPagerAdapter);
    }

在WeatherFragment中获取从MainActivity中传入的城市

//通过activity传值获取到当前fragment加载的是哪个地方的天气情况
Bundle arguments = getArguments();
String city=arguments.getString("city");
getWeatherCity(city);

编写FragmentPagerAdapter用于fragment的显示

public class FragmentPagerAdapter extends FragmentStatePagerAdapter {
    List<Fragment> fragmentList;  //主界面传入的fragmenr的集合
    public FragmentPagerAdapter(FragmentManager fragmentManager,List<Fragment> fragments) {
        super(fragmentManager);
        this.fragmentList=fragments;
    }
    @NonNull
    @Override
    public Fragment getItem(int position) {  //根据位置获取集合条目内容
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {   //获取集合条目个数
        return fragmentList.size();
    }
}

二、子线程中开启网络请求

编写NetUtil类,在类中编写两个静态方法doGet和getWeatherOfCity

doGet方法用于从网络中获取数据,getWeatherOfCity方法用于拼接url之后,调用doGet方法传入url获取天气信息

    public static final String URL_WEATHER="https://tianqiapi.com/api?unescape=1&version=v1&appid=22444194&appsecret=EG7XHDop";
    public static String doGet(String urlString){
        String result="";
        String line;
        StringBuilder stringBuilder=null;
        BufferedReader bufferedReader=null;
        //连接网络
        HttpURLConnection connection=null;
        InputStreamReader isr=null;
        try {
            URL url=new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");  //链接方式
            connection.setConnectTimeout(5000);   //超时时间
            //从连接中读取数据(二进制)
            InputStream inputStream=connection.getInputStream();
            //对数据流进行加工
            isr=new InputStreamReader(inputStream);
            //创建缓冲区,将二进制流送入
            bufferedReader=new BufferedReader(isr);
            //从缓冲区一行一行读取字符串
            stringBuilder=new StringBuilder();
            while ((line=bufferedReader.readLine())!=null){
                stringBuilder.append(line); //进行拼接
            }
            result=stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭流
                connection.disconnect();
                bufferedReader.close();
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    //拼接出来获取天气的url
    public static String getWeatherOfCity(String city){
        String url=URL_WEATHER+"&city="+city;
        Log.i("Aye","URL:"+url);
        Log.i("Aye","URLResult:"+doGet(url));
        return  doGet(url);
    }

编写getWeatherCity方法,开启子线程,调用NetUtil类中的静态方法getWeatherOfCity来获取天气数据,并通过handler将数据传递给主线程

private void getWeatherCity(String selectCity) {
    //开启子线程,请求网络
    new Thread(new Runnable() {
        @Override
        public void run() {
            //请求网络
            String weatherOfCity=NetUtil.getWeatherOfCity(selectCity);
            //使用handler将数据传递给主线程
            Message message=Message.obtain();
            message.what=0;
            message.obj=weatherOfCity;
            handler.sendMessage(message);
        }
    }).start();
}

三、网络请求返回Json数据解析

使用在线工具解析Json数据并生成JavaBean导入包中

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zEJn14mR-1632214033044)(C:\\Users\\paranoia\\AppData\\Roaming\\Typora\\typora-user-images\\image-20210915094807564.png)]

接收子线程传递的数据并使用gson解析

    private Handler handler=new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                //主线程收到的天气数据
                String weather= (String) msg.obj;
                Log.i("Aye","主线程收到的天气数据:"+weather);
                //使用gson解析
                Gson gson=new Gson();
                JsonRootBean jsonRootBean=gson.fromJson(weather, JsonRootBean.class);
               updateWeather(jsonRootBean); //更新天气数据并显示
            }
        }
    };

四、界面呈现

1. 获取天气数据并展示

编写updateWeather方法,用于获取数据并显示在界面上

    //数据显示
    private void updateWeather(JsonRootBean jsonRootBean) {
        if (jsonRootBean!=null){
            List<Data> dayWeather = jsonRootBean.getData(); //获取每一天的数据
            Data todayWeather = dayWeather.get(0);//获取今天的数据
            //不为空则显示今天天气数据
            if (todayWeather!=null){
                tempTv.setText(todayWeather.getTem1());
                mainWeatherTv.setText(todayWeather.getWea());;
                todayTv.setText("今天:"+todayWeather.getWea());
                todayAirTv.setText("空气:"+todayWeather.getAir_level());
                todayTempTv.setText(todayWeather.getTem()+"~"+todayWeather.getTem2());
                todayIconIv.setImageResource(getImg(todayWeather.getWea_img()));
                windTv.setText(todayWeather.getWin_speed());
                humidityTv.setText(todayWeather.getHumidity());
                pressureTv.setText(todayWeather.getPressure()+"hPa");
                windTv1.setText(todayWeather.getWin().get(0));
                sunriseTv.setText("日出:"+todayWeather.getSunrise());
                sunsetTv.setText("日落:"+todayWeather.getSunset());
            }
            //获取明天的数据
            Data tomorrowWeather = dayWeather.get(1);
            //不为空则显示明天数据
            if (tomorrowWeather!=null){
                tomorrowTv.setText("明天:"+tomorrowWeather.getWea());
                tomorrowAirTv.setText("空气:"+tomorrowWeather.getAir_level());
                tomorrowTempTv.setText(tomorrowWeather.getTem()+"~"+tomorrowWeather.getTem2());
                tomorrowIconIv.setImageResource(getImg(tomorrowWeather.getWea_img()));
            }
            //获取后天的数据
            Data afterWeather = dayWeather.get(2);
            //不为空则显示后天天气数据
            if (afterWeather!=null){
                afterTv.setText("后天:"+afterWeather.getWea());
                afterAirTv.setText("空气:"+afterWeather.getAir_level());
                afterTempTv.setText(afterWeather.getTem()+"~"+afterWeather.getTem2());
                afterIconIv.setImageResource(getImg(afterWeather.getWea_img()));
            }
            //获取指数信息
            List<Index> index = todayWeather.getIndex();
            //不为空则显示
            if (index!=null) {
                //紫外线指数
                UVTitle = index.get(0).getTitle();
                UVLevel = index.get(0).getLevel();
                UVDesc = index.get(0).getDesc();
                //穿衣指数
                clotheTitle = index.get(3).getTitle();
                clotheLevel = index.get(3).getLevel();
                clotheDesc = index.get(3).getDesc();
                //运动指数
                sportTitle=index.get(1).getTitle();
                sportLevel=index.get(1).getLevel();
                sportDesc=index.get(1).getDesc();
                //洗车指数
                carTitle=index.get(4).getTitle();
                carLevel=index.get(4).getLevel();
                carDesc=index.get(4).getDesc();
                //血糖指数
                sickTitle=index.get(2).getTitle();
                sickLevel=index.get(2).getLevel();
                sickDesc=index.get(2).getDesc();
                //空气污染指数
                airTitle=index.get(5).getTitle();
                airLevel=index.get(5).getLevel();
                airDesc=index.get(5).getDesc();
            }
            //获取逐小时天气情况,传递给Adapter用于显示
            List<Hours> timeBean = todayWeather.getHours();
            weatherAdapter=new WeatherAdapter(getActivity(),timeBean);
            LinearLayoutManager manager=new LinearLayoutManager(getActivity(), RecyclerView.HORIZONTAL,false);
            hoursRv.setAdapter(weatherAdapter);
            hoursRv.setLayoutManager(manager);
        }
    }

2. 根据天气情况显示对应图片

编写getImg方法用于根据天气情况显示图片

    private int getImg(String wea_img) {
        int result = 0;
        switch (wea_img) {
            case "qing": //晴天
                result=R.mipmap.sun;
                break;
            case "yin":  //阴天
                result=R.mipmap.yin;
                break;
            case "yu":  //雨天
                result=R.mipmap.yu;
                break;
            case "yun":    //多云
                result=R.mipmap.yun;
                break;
            case "bingbao":   //冰雹
                result=R.mipmap.bingbao;
                break;
            case "wu":   //雾
                result=R.mipmap.wu;
                break;
            case "shachen":  //沙尘暴
                result=R.mipmap.shachen;
                break;
            case "lei":    //雷
                result=R.mipmap.lei;
                break;
            case "xue":  //雪
                result=R.mipmap.xue;
                break;
            default:  //如果都不是则显示晴
                result=R.mipmap.sun;
                break;
        }
        return result;
    }

3. 显示逐小时天气情况

编写WeatherAdapter,用于显示逐小时天气情况

public class WeatherAdapter extends RecyclerView.Adapter<WeatherAdapter.WeatherViewHolder> {
    private Context context;  //上下文
    private List<Hours>  timeBean;   //天气信息

    public WeatherAdapter(Context context, List<Hours> timeBean) {
        this.context = context;
        this.timeBean = timeBean;
    }
    @NonNull
    @Override  //创建ViewHolder
    public WeatherViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(context).inflate(R.layout.recylerview_item,parent,false);
        WeatherViewHolder weatherViewHolder=new WeatherViewHolder(view);
        return weatherViewHolder;
    }
    @Override   //绑定ViewHolder,显示数据
    public void onBindViewHolder(@NonNull WeatherViewHolder holder, int position) {
        Hours hoursBean = timeB

以上是关于天气预报app的主要内容,如果未能解决你的问题,请参考以下文章

一个简单的天气预报APP

一个简单的天气预报APP

天气预报APP

天气预报APP----教程一

天气预报app

Android 天气APP获取定位信息