CoolWeather


第一行代码-第二版的酷欧天气

  • 首先创建数据库类继承LitePal,用来存储城市数据
    • Province.java
      public class Province extends DataSupport {
      private int id;
    
      private String provinceName;
    
      private int provinceCode;
    
     ...//getter and setter
    

}

- City.java
public class City extends DataSupport {
private int id;

private String CityName;

private int cityCode;

private int provinceId;

...//getter and setter

}

- County.java

public class County extends DataSupport {
private int id;

private String countyName;

private String weatherId;

private int cityId;

...//getter and setter
}

- 创建选择城市的ChooseAreaFragment.java

public class ChooseAreaFragment extends Fragment {
private static final String TAG = "ChooseAreaFragment";
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private Button backButton;
private ListView listView;
private ArrayAdapter<String> adapter;
private List<String> dataList = new ArrayList<>();
//省列表
private List<Province> provinceList;
// 市列表
private List<City> cityList;
//县列表
private List<County> countyList;
//选中的省份
private Province selectedProvice;
//选中的城市
private City selectedCity;
//当前选中的级别
private int currentLevel;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_area,container, false);
titleText = (TextView) view.findViewById(R.id.title_text);
backButton = (Button) view.findViewById(R.id.back_button);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1,dataList);
listView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//初始化省级数据
queryProvince();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvice = provinceList.get(position);
queryCity();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(position);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY) {
String weatherId = countyList.get(position).getWeatherId();
if (getActivity() instanceof MainActivity) {
Intent intent = new Intent(getActivity(), WeatherActivity.class);
intent.putExtra("weather_id",weatherId);
startActivity(intent);
getActivity().finish();
} else if (getActivity() instanceof WeatherActivity) {
WeatherActivity activity = (WeatherActivity) getActivity();
activity.drawerLayout.closeDrawers();
activity.swipeRefreshLayout.setRefreshing(true);
activity.requestWeather(weatherId);
} else if (getActivity() instanceof WeatherChooseAreaActivity) {
Intent intent = new Intent(getActivity(), WeatherActivity.class);
intent.putExtra("weather_choose_id",weatherId);
startActivity(intent);
getActivity().finish();
}
}
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (currentLevel == LEVEL_COUNTY) {
queryCity();
} else if (currentLevel == LEVEL_CITY) {
queryProvince();
}
}
});
}
//查询选中省的数据,优先从数据库查询,如果没有查询到再从数据库上查询
private void queryProvince() {
titleText.setText("中国");
backButton.setVisibility(View.GONE);
provinceList = DataSupport.findAll(Province.class);
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_PROVINCE;
} else {
String address = "http://guolin.tech/api/china";
queryFromServer(address, "province");
}
}
// 查询选中市内所有的县,优先从数据库查询,如果没有查询到再从数据库上查询
private void queryCounties() {
titleText.setText(selectedCity.getCityName());
backButton.setVisibility(View.VISIBLE);
countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_COUNTY;
} else {
int provinceCode = selectedProvice.getProvinceCode();
int cityCode = selectedCity.getCityCode();
String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
queryFromServer(address, "county");
}

}

// 查询选中省内所有的市,优先从数据库查询,如果没有查询到再从数据库上查询
private void queryCity() {
titleText.setText(selectedProvice.getProvinceName());
backButton.setVisibility(View.VISIBLE);
cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvice.getId())).find(City.class);
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_CITY;
} else {
int provinceCode = selectedProvice.getProvinceCode();
String address = "http://guolin.tech/api/china/" + provinceCode;
queryFromServer(address, "city");
}

}

/**
 * 根据传入的地址和类型从服务器上查询市县数据
 * @param address
 * @param type
 */
private void queryFromServer(String address, final String type) {
    showProgressDialog();
    HttpUtil.sendOkHttpRequest(address, new Callback() {
        // 通过runOnUiThread()方法回到主线程处理逻辑
        @Override
        public void onFailure(Call call, IOException e) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    closeProgressDialog();
                    Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show();
                }
            });

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String json = response.body().string();
            boolean result = false;
            if ("province".equals(type)) {
                result = Util.handleProvinceResponce(json);
            } else if ("city".equals(type)) {
                result = Util.handleCityResponse(json, selectedProvice.getId());
            } else if ("county".equals(type)) {
                result = Util.handleCountyResponse(json, selectedCity.getId());
            }
            if (result) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        if ("province".equals(type)) {
                            queryProvince();
                        }else if ("city".equals(type)) {
                            queryCity();
                        }else if ("county".equals(type)) {
                            queryCounties();
                        }
                    }
                });
            }
        }
    });
}
/**
 * 显示对话框
 */
private void showProgressDialog() {
    if (progressDialog == null) {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("数据加载中...");
        progressDialog.setCanceledOnTouchOutside(false);
    }
    progressDialog.show();
}
/**
 * 关闭对话框
 */
private void closeProgressDialog(){
    if (progressDialog != null) {
        progressDialog.dismiss();
    }
}

}


- 显示天气的Activity,WeatherActivity.java
         public class WeatherActivity extends AppCompatActivity {
        private List<Menu> menuLists = new ArrayList<Menu>();
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View decorView = getWindow().getDecorView();
       decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN|
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_weather);

        initStatus();
        //navViewToTop();

        //初始化各控件
        bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
        weatherLayout = (NestedScrollView) findViewById(R.id.weather_layout);
        titleCity = (TextView) findViewById(R.id.title_city);
        titleUpdateTime = (TextView) findViewById(R.id.title_update_time);

        degreeText = (TextView) findViewById(R.id.degree_text);
        weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
        weather_icon = (ImageView) findViewById(R.id.weather_icon);

        forecastLinearLayout = (LinearLayout) findViewById(R.id.forecast_layout);
        aqiText = (TextView) findViewById(R.id.aqi_text);
        pm25Text = (TextView) findViewById(R.id.pm25_text);

        comfortText = (TextView) findViewById(R.id.comfort_text);
        carWashText = (TextView) findViewById(R.id.car_wash_text);
        sportText = (TextView) findViewById(R.id.sport_text);

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navButton = (Button) findViewById(R.id.nav_button);
        chartButton = (Button) findViewById(R.id.set_up_button);
        recyclerView = (RecyclerView) findViewById(R.id.menu_recycleview);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        menuLists.add(new Menu(R.mipmap.home,"天气"));
        menuLists.add(new Menu(R.mipmap.favorite,"每小时天气"));
        menuLists.add(new Menu(R.mipmap.about,"关于"));

        MenuAdapter menuAdapter = new MenuAdapter(menuLists);
        menuAdapter.setMenuItemOnClickListener(new MenuAdapter.MenuItemOnClickListener<Menu>() {
            @Override
            public void itemOnClickListener(Menu item) {
                clickMenuItem(item);
            }
        });

        recyclerView.setAdapter(menuAdapter);

        if (getIntent().getStringExtra("weather_choose_id") != null) {
            mWeatherId = getIntent().getStringExtra("weather_choose_id");
            weatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(mWeatherId);
        }

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = preferences.getString("weather", null);
        if (weatherString != null) {
            //有缓存时直接解析天气数据
            Weather weather = Util.handleWeatherResponse(weatherString);
            mWeatherId = weather.basic.weatherId;
            showWeatherInfo(weather);

        }else {
            //无缓存时去服务器查询天气
            mWeatherId = getIntent().getStringExtra("weather_id");
            weatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(mWeatherId);
        }

        //根据缓存的id查询天气
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeather(mWeatherId);
            }
        });
        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });

        chartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(WeatherActivity.this, WeatherChooseAreaActivity.class);
                startActivity(intent);
            }
        });
        String bingPic = preferences.getString("bing_pic", null);
        if (bingPic != null) {
            Glide.with(this).load(bingPic).into(bingPicImg);
        } else {
            loadBingPic();
        }
       }
       //点击菜单项的处理函数
      private void clickMenuItem(Menu item) {
        drawerLayout.closeDrawers();
        switch (item.getIcon()) {
            case R.mipmap.home:
                Intent intent = new Intent(this, WeatherActivity.class);
                startActivity(intent);
                break;
            case R.mipmap.favorite:
                Intent ChartIntent = new Intent(this, WeatherChartActivity.class);
                startActivity(ChartIntent);
              break;
            default:
                break;

        }
       }
      @Override
      public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
      }
      private void initStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
      }

      /**
       * 对系统返回键进行监听,定义一个变量记录按键时间,通过计算时间差来判断是否退出程序
       * @param keyCode
       * @param event
       * @return
       */
      @Override
      public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK && event.getAction()==KeyEvent.ACTION_DOWN){
            if (System.currentTimeMillis()-firstTime>2000){
                Toast.makeText(WeatherActivity.this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
                firstTime=System.currentTimeMillis();
            }else{
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
      }
      //加载每天必应图片
      private void loadBingPic() {
        final String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                editor.putString("bing_pic", null);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
                    }
                });
            }
        });
      }

      //根据天气id请求城市天气信息
      public void requestWeather(final String weatherId) {
        String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9";
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
              }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                final Weather weather = Util.handleWeatherResponse(responseText);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weather != null && "ok".equals(weather.status)) {
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather", responseText);
                            editor.apply();
                            mWeatherId = weather.basic.weatherId;
                            showWeatherInfo(weather);
                        } else {
                            Toast.makeText(WeatherActivity.this,"获取天气信息失败", Toast.LENGTH_SHORT).show();
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
          });
        }

      //处理并显示Weather实体类中的数据
      private void showWeatherInfo(Weather weather) {
        String ctiyName = weather.basic.cityName;
        String updateTime = weather.basic.update.updateTime;
        String degree = weather.now.temperature;
        String weatherInfo = weather.now.more.info;

        titleCity.setText(ctiyName);
        titleUpdateTime.setText(updateTime);
        degreeText.setText(degree);
        weatherInfoText.setText(weatherInfo);
        setWeatherIcon(weatherInfo);
        forecastLinearLayout.removeAllViews();

        for (Forecast forecast : weather.forecastList) {
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item,forecastLinearLayout, false);
            TextView dataText = (TextView) view.findViewById(R.id.date_text);
            TextView infoText = (TextView) view.findViewById(R.id.info_text);
            TextView maxText = (TextView) view.findViewById(R.id.max_text);
            TextView minText = (TextView) view.findViewById(R.id.min_text);
            infoicon = (ImageView) view.findViewById(R.id.info_icon);

            dataText.setText(forecast.date);
            infoText.setText(forecast.more.info);
            setInfoIcon(forecast.more.info);
            maxText.setText(forecast.temperature.max);
            minText.setText(forecast.temperature.min);

            forecastLinearLayout.addView(view);

        }
        if (weather.aqi != null) {
            aqiText.setText(weather.aqi.city.aqi);
            pm25Text.setText(weather.aqi.city.pm25);
        }
        String comfort = "舒适度:" + weather.suggestion.comfort.info;
        String carWash = "洗车指数:" + weather.suggestion.carWash.info;
        String sport = "运动指数:" + weather.suggestion.sport.info;
        comfortText.setText(comfort);
        carWashText.setText(carWash);
        sportText.setText(sport);
        weatherLayout.setVisibility(View.VISIBLE);
        Intent intent = new Intent(this, AutoUpdateService.class);
        startService(intent);
       }
       ...
      }


- 用到了解析json数据的工具类,Utils.java:

public class Util {
//解析和处理服务器返回的省级数据
public static boolean handleProvinceResponce(String response) {
if (!TextUtils.isEmpty(response)) {
try {
JSONArray allProvinces = new JSONArray(response);
for (int i = 0; i < allProvinces.length(); i++) {
JSONObject provinceObject = allProvinces.getJSONObject(i);
Province province = new Province();
province.setProvinceName(provinceObject.getString("name"));
province.setProvinceCode(provinceObject.getInt("id"));
//保存数据到数据表
province.save();
}
return true;
} catch (JSONException e) {
e.printStackTrace();
}
}
return false;
}
//解析和处理服务器返回的市级数据
public static boolean handleCityResponse(String reponse, int province){
if (!TextUtils.isEmpty(reponse)) {
try {
JSONArray jsonArray = new JSONArray(reponse);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
City city = new City();
city.setCityName(jsonObject.getString("name"));
city.setCityCode(jsonObject.getInt("id"));
city.setProvinceId(province);
city.save();
}
return true;
} catch (JSONException e) {
e.printStackTrace();
}
}
return false;
}
//解析和处理服务器返回的县级数据
public static boolean handleCountyResponse(String response, int cityId) {
if (!TextUtils.isEmpty(response)){
try {
JSONArray allCounties = new JSONArray(response);
for (int i = 0; i < allCounties.length(); i++) {
JSONObject countyObject = allCounties.getJSONObject(i);
County county = new County();
county.setCountyName(countyObject.getString("name"));
county.setWeatherId(countyObject.getString("weather_id"));
county.setCityId(cityId);
county.save();

            }
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    return false;
}
public static Weather handleWeatherResponse(String response) {
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray jsonArray = jsonObject.getJSONArray("HeWeather");
        String weatherContent = jsonArray.getJSONObject(0).toString();
        return new Gson().fromJson(weatherContent,Weather.class);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

}

推荐阅读更多精彩内容