用Android Studio寫的查看天氣的app(CoolWeather)

項目源碼在Github上面有Github項目源碼

在這裏節選一下兩個主要的Activity中的源碼
ChooseAreaActivity.java

package com.example.chencong.coolweather.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.chencong.coolweather.R;
import com.example.chencong.coolweather.db.CoolWeatherDB;
import com.example.chencong.coolweather.model.City;
import com.example.chencong.coolweather.model.County;
import com.example.chencong.coolweather.model.Province;
import com.example.chencong.coolweather.util.HttpCallbackListener;
import com.example.chencong.coolweather.util.HttpUtil;
import com.example.chencong.coolweather.util.Utility;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chencong on 2016/7/13.
 */
public class ChooseAreaActivity extends Activity {
    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 ListView listView;
    private ArrayAdapter<String> adapter;
    private CoolWeatherDB coolWeatherDB;
    private List<String> dataList = new ArrayList<String>();

    //省列表
    private List<Province> provinceList;

    //市列表
    private List<City> cityList;

    //縣列表
    private  List<County> countyList;

    //選中的省份
    private Province selectedProvince;

    //選中的市
    private City selectedCity;

    //當前選中的級別
    private int currentLevel;


    /*
    * 是否從WeatherActivity中跳轉過來*/
    private boolean isFromWeatherActivity;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity",false);
        //從ChooseAreaActivity跳轉到WeatherActivity
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        //對已經選擇了城市並且不是從WeatherActivity跳轉過來,纔會直接跳轉到WeatherActivity
        if (prefs.getBoolean("city_selected",false) && !isFromWeatherActivity){
            Intent intent = new Intent(this,WeatherActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.choose_area);
        listView = (ListView)findViewById(R.id.list_view);
        titleText = (TextView) findViewById(R.id.title_text);

        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,dataList);
        listView.setAdapter(adapter);
        coolWeatherDB = CoolWeatherDB.getInstance(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (currentLevel == LEVEL_PROVINCE){
                    selectedProvince = provinceList.get(position);  //index換position
                    queryCities();
                }else if (currentLevel == LEVEL_CITY){
                    selectedCity = cityList.get(position);
                    queryCounties();

                    //從ChooseAreaActivity跳轉到WeatherActivity
                }else if (currentLevel == LEVEL_COUNTY){
                    String countyCode = countyList.get(position).getCountyCode();
                    Intent intent = new Intent(ChooseAreaActivity.this,WeatherActivity.class);
                    intent.putExtra("county_code",countyCode);
                    startActivity(intent);
                    finish();
                }


            }
        });
        queryProvinces();   //加載省級數據
    }

    /*查詢全國所有省,先從數據庫中查詢,如果數據庫中沒有那麼再從服務器中查詢*/
    private void queryProvinces (){
        provinceList = coolWeatherDB.loadProvinces();
        if (provinceList.size() > 0){
            dataList.clear();
            for (Province province : provinceList){
                dataList.add(province.getProvinceName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            titleText.setText("中國");
            currentLevel = LEVEL_PROVINCE;
        }else {
            queryFromServer(null,"province");
        }
    }

    /*查詢選中省的所有市,先從市數據庫中查詢,如果沒有再從服務器中查詢*/
    private  void queryCities(){
        cityList = coolWeatherDB.loadCities(selectedProvince.getId());
        if (cityList.size() > 0){
            dataList.clear();
            for (City city : cityList){
                dataList.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            titleText.setText(selectedProvince.getProvinceName());
            currentLevel = LEVEL_CITY;
        }else {
            queryFromServer(selectedProvince.getProvinceCode(),"city");
        }
    }

    /*查詢選中市的所有縣,先從數據庫中查詢,如果沒有再從服務器中查詢*/
    private  void queryCounties(){
        countyList = coolWeatherDB.loadCounties(selectedCity.getId());
        if (countyList.size() >0 ){
            dataList.clear();
            for (County county : countyList){
                dataList.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            titleText.setText(selectedCity.getCityName());
            currentLevel = LEVEL_COUNTY;
        }else{
            queryFromServer(selectedCity.getCityCode(),"county");
        }
    }

    /*根據傳入的代號和類型從服務器上查詢省市縣的數據*/
    private void queryFromServer(final String code,final String type){
        String address;
        if (!TextUtils.isEmpty(code)){
            address = "http://www.weather.com.cn/data/list3/city"+code+".xml";
        }else{
            address = "http://www.weather.com.cn/data/list3/city.xml";
        }
        showProgressDialog();   //開啓線程
        HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
            //handle**Response()方法都是boolean類型的,判斷是否將數據存儲到表中
            @Override
            public void onFinish(String response) {
                boolean result = false;
                if ("province".equals(type)){
                    result = Utility.handleProvinceResponse(coolWeatherDB,response);
                }else if ("city".equals(type)){
                    result = Utility.handleCitiesResponse(coolWeatherDB,response,selectedProvince.getId());
                }else if ("county".equals(type)){
                    result = Utility.handleCountiesResponse(coolWeatherDB,response,selectedCity.getId());
                }

                if (result){
                    //通過runOnUiThread()方法回到主線程處理邏輯
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)){
                                queryProvinces();
                            }else if ("city".equals(type)){
                                queryCities();
                            }else if ("county".equals(type)){
                                queryCounties();
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {
                //通過runOnUiThread()方法回調主線程處理邏輯
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(ChooseAreaActivity.this,"加載失敗啦(╥╯^╰╥)",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    /*顯示進度對話框*/
    private void showProgressDialog(){
        if (progressDialog == null){
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("努力加載中.... ↖(^ω^)↗");
            progressDialog.setCanceledOnTouchOutside(false);
       }
        progressDialog.show();
    }

    /*
    * 關閉進度對話框*/
    private void closeProgressDialog(){
        if (progressDialog != null){
            progressDialog.dismiss();
        }
    }

    /*
    * 捕獲Back鍵,根據當前級別來判斷,是應該市列表、省列表,還是直接退出*/

    @Override
    public void onBackPressed() {
        if (currentLevel == LEVEL_COUNTY){
            queryCities();
        }else if (currentLevel == LEVEL_CITY){
            queryProvinces();
        }else {
            if (isFromWeatherActivity){
                Intent intent = new Intent(this,WeatherActivity.class);
                startActivity(intent);
            }
        }
            finish();
    }
}

WeatherActivity.java

package com.example.chencong.coolweather.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.chencong.coolweather.R;
import com.example.chencong.coolweather.util.HttpCallbackListener;
import com.example.chencong.coolweather.util.HttpUtil;
import com.example.chencong.coolweather.util.Utility;

/**
 * Created by chencong on 2016/7/14.
 */
public class WeatherActivity extends Activity implements View.OnClickListener {
    private LinearLayout weatherInfoLayout;
    private TextView cityNameText;   //顯示城市名
    private TextView publishText;   //顯示發佈時間
    private TextView weatherDespText;  //顯示天氣描述信息
    private TextView temp1Text;   //顯示氣溫1
    private TextView temp2Text;     //顯示氣溫2
    private TextView currentDateText;     //顯示當前時間日期

    /*
    * 切換城市按鈕*/
    private Button switchCity;

    /*
    * 更新天氣*/
    private Button refreshWeather;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.weather_layout);

        switchCity = (Button) findViewById(R.id.switch_city);
        refreshWeather = (Button) findViewById(R.id.refresh_weather);
        switchCity.setOnClickListener(this);
        refreshWeather.setOnClickListener(this);

        //初始化各種控件
        weatherInfoLayout = (LinearLayout) findViewById(R.id.weather_info_layout);
        cityNameText = (TextView) findViewById(R.id.city_name);
        publishText = (TextView) findViewById(R.id.publish_text);
        weatherDespText = (TextView) findViewById(R.id.weather_desp);
        temp1Text = (TextView) findViewById(R.id.temp1);
        temp2Text = (TextView) findViewById(R.id.temp2);
        currentDateText = (TextView) findViewById(R.id.current_date);
        String countycode = getIntent().getStringExtra("county_code");   //從Intent中取出縣級代號
        if (!TextUtils.isEmpty(countycode)){
            //有縣級代碼就去查詢天氣
            publishText.setText("天氣正在同步中.....");
            weatherInfoLayout.setVisibility(View.INVISIBLE);
            cityNameText.setVisibility(View.INVISIBLE);
            queryWeatherCode(countycode);
        }else{
            //沒有縣級代號就顯示本地天氣
            showWeather();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.switch_city:
                Intent intent = new Intent(this,ChooseAreaActivity.class);
                intent.putExtra("from_weather_activity",true);
                startActivity(intent);
                finish();
                break;
            case R.id.refresh_weather:
                publishText.setText("同步中....");
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                String weatherCode = prefs.getString("weather_code","");
                if (! TextUtils.isEmpty(weatherCode)){
                    queryWeatherInfo(weatherCode);
                }
                break;
            default:
                break;
        }
    }

    /*拿着縣級代號查詢天氣代號*/
    private void queryWeatherCode(String countyCode){
        String address = "http://www.weather.com.cn/data/list3/city"+countyCode+".xml";
        queryFromServer(address,"countyCode");
    }
    /*拿着天氣代號查詢天氣信息*/
    private  void  queryWeatherInfo(String weatherCode){
        String address = "http://www.weather.com.cn/data/cityinfo/"+weatherCode+".html";
        queryFromServer(address,"weatherCode");
    }

    /*
    * 根據傳入的地址和類型向服務器查詢天氣代號或者天氣信息*/
    private  void queryFromServer(final String address,final String type){
        HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
            @Override
            public void onFinish( final  String response) {
                if ("countyCode".equals(type)){
                    if (!TextUtils.isEmpty(response)){
                        //從服務器返回的數據中解析出天氣代號
                        String [] array = response.split("\\|");
                        if (array !=null && array.length == 2){
                            String weatherCode = array[1];
                            queryWeatherInfo(weatherCode);
                        }
                    }else if ("weatherCode".equals(type)){
                        //處理服務器返回的天氣信息
                        Utility.handleWeatherRespone(WeatherActivity.this,response);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showWeather();
                            }
                        });
                    }
                }
            }
            @Override
            public void onError(Exception e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        publishText.setText("同步失敗...(。・_・)/~~~");
                    }
                });
            }
        });
    }

    /*
    * 從SharedPreferences文件中讀取的天氣信息,並顯示到界面上*/
    private  void  showWeather(){
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        cityNameText.setText(prefs.getString("city_name",""));
        temp1Text.setText(prefs.getString("temp1",""));
        temp2Text.setText(prefs.getString("temp2",""));
        weatherDespText.setText(prefs.getString("weather_desp",""));
        publishText.setText("今天"+prefs.getString("publish_time","")+"發佈");
        currentDateText.setText(prefs.getString("current_date",""));
        weatherInfoLayout.setVisibility(View.VISIBLE);
        cityNameText.setVisibility(View.VISIBLE);
    }
}

詳細的項目源碼可以從Github中下載
還有Apk文件源碼中也有CoolWeather\app\build\outputs\apk
項目下載地址http://download.csdn.net/detail/chencong3139/9576447

2016年7月14日23:05:57
        by chencong
我揮舞着鍵盤和本子,
發誓要把世界寫個明明白白。
        《第一行代碼》郭霖
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章