Android Open Source - Weather Set City Activity






From Project

Back to project page Weather.

License

The source code is released under:

GNU General Public License

If you think the Android project Weather listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.imlongluo.weather.app;
//w w  w . j  av  a2s . co  m
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.imlongluo.weather.R;
import com.imlongluo.weather.db.DBHelper;
import com.imlongluo.weather.location.GPSListAdapter;
import com.imlongluo.weather.location.MyListAdapter;
import com.imlongluo.weather.utils.LocationXMLParser;
import com.imlongluo.weather.utils.WeaterInfoParser;
import com.imlongluo.weather.utils.WebAccessTools;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.appwidget.AppWidgetManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView.OnChildClickListener;

/**
 * 
 * @author longluo
 * ???????Activity
 */
public class SetCityActivity extends Activity {
  //?????????????
  private ListView gpsView;
  //?????????????????
  private ExpandableListView provinceList;
  //?????????????
  private TextView filterText;
  
  //????????????SharedPreferences?????
  public static final String CITY_CODE_FILE="city_code";
  
  //??????
  private String[][] cityCodes;
  //???
  private String[] groups;
  //?????
    private String[][] childs;
    
    //????????????
    private MyListAdapter adapter;
    
    //???????widget?ID
    private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.set_city);
        
        gpsView = (ListView)findViewById(R.id.gps_view);
        provinceList= (ExpandableListView)findViewById(R.id.provinceList);
        
        //????????????
        gpsView.setAdapter(new GPSListAdapter(SetCityActivity.this));
        
        //==============================GPS=================================
        //???????????
        gpsView.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> parent, View view,
          int position, long id) {
        TextView localeCity = (TextView)view.findViewById(R.id.locateCityText);
        localeCity.setText("?????...");
        
        final LocateHandler handler = new LocateHandler(localeCity);
        //????????????????
        new Thread(){
          public void run() {
            Map<Integer, String> cityMap= getLocationCityInfo();
            //???????????
            int provinceIndex = -1;
            int cityIndex = -1;
            //?????????????????
            Bundle bundle = new Bundle();
            if(cityMap!=null) {
              //???????
              String country = cityMap.get(LocationXMLParser.COUNTRYNAME);
              //?????????????
              if(country!=null&&country.equals("??")){
                //????
                String province = cityMap.get(LocationXMLParser.ADMINISTRATIVEAREANAME);
                //???
                String city = cityMap.get(LocationXMLParser.LOCALITYNAME);
                //????
                String towns = cityMap.get(LocationXMLParser.DEPENDENTLOCALITYNAME);
                
                Log.i("GPS", "============"+province+"."+city+"."+towns+"==============");
                //?GPS???????????????????????
                StringBuilder matchCity = new StringBuilder(city);
                matchCity.append(".");
                matchCity.append(towns);
                //?????
                for(int i=0; i<groups.length; i++) {
                  if(groups[i].equals(province)) {
                    provinceIndex = i;
                    break;
                  }
                }
                //??????????????
                for(int j=0; j<childs[provinceIndex].length; j++) {
                  if(childs[provinceIndex][j].equals(matchCity.toString())) {
                    cityIndex = j;
                    break;
                  }
                }
                //?????????,???????????
                if(cityIndex == -1) {
                  for(int j=0; j<childs[provinceIndex].length; j++) {
                    if(childs[provinceIndex][j].equals(city)) {
                      cityIndex = j;
                      //????????????
                      break;
                    }
                  }
                }
              }
            }
            //???bundle????????Handler
            bundle.putInt("provinceIndex", provinceIndex);
            bundle.putInt("cityIndex", cityIndex);
            
            Message msg = new Message();
            msg.setData(bundle);
            //?????handler????
            handler.sendMessage(msg);
          }
        }.start();
      }
          
        });
        
        //????????????
        filterText = (TextView) findViewById(R.id.filterField);
        filterText.addTextChangedListener(new TextWatcher() {

      @Override
      public void afterTextChanged(Editable s) {
        CharSequence filterContent = filterText.getText();
        //??????????????
        adapter.getFilter().filter(filterContent);
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
          int after) {
      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before,
          int count) {
      }
          
        });
        
        //??MainActivity?Widget??????intent
        Intent intent =getIntent();
        //????MainActivity??????isFirstRun????????????????
        boolean isFirstRun = intent.getBooleanExtra("isFirstRun", false);
        
        //????Bundle?????Widget????????WidgetId
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, 
                AppWidgetManager.INVALID_APPWIDGET_ID);
            //??WidgetId??
            if(mAppWidgetId!=AppWidgetManager.INVALID_APPWIDGET_ID) {
              //??????????????
              SharedPreferences sp=getSharedPreferences(CITY_CODE_FILE, MODE_PRIVATE);
              if(sp.getString("code", null)==null) {
                //?????????????????????
                isFirstRun = true;
              } else {       
                //????????
                AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(SetCityActivity.this);
            RemoteViews views = new RemoteViews(SetCityActivity.this.getPackageName(),
                R.layout.widget_layout);
            //??????
            String cityCode= sp.getString("code", "");
            if(cityCode!=null&&cityCode.trim().length() > 0) {
              Log.i("widget", "===================update  weather===========================");
              //??widget
              WeatherWidget.updateAppWidget(views, SetCityActivity.this, appWidgetManager, cityCode);
            }
            
            appWidgetManager.updateAppWidget(mAppWidgetId, views);
            //????????
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
            setResult(RESULT_OK, resultValue);
            //????????Activity
            finish();
            return;
              }
            }
        }
        
        //???true?????????
        if(isFirstRun) {
          //????????????
          importInitDatabase();
          
          //?????????????????
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setMessage("????????????????????????????").setPositiveButton("??", null);
          AlertDialog dialog = builder.create();
          dialog.show();
        }
        
        //???????????????????????
        final ProgressDialog dialog = getProgressDialog("", "????????...");
        dialog.show();
        //?????????????
        final MyHandler mHandler = new MyHandler();
        new Thread(new Runnable() {
          public void run() {
            //???????????,??????
                DBHelper dbHelper = new DBHelper(SetCityActivity.this, "db_weather.db");
                groups = dbHelper.getAllProvinces();
                List<String[][]> result = dbHelper.getAllCityAndCode(groups);
                childs = result.get(0);
                cityCodes = result.get(1);
                //??Handler??????
                Message msg = new Message();
                mHandler.sendMessage(msg);
                dialog.cancel();
                dialog.dismiss();
          }
        }).start();
    }

  //?res/raw????????????????????database???
    public void importInitDatabase() {
      //????????
      String dirPath="/data/data/com.imlongluo.weather/databases";
      File dir = new File(dirPath);
      if(!dir.exists()) {
        dir.mkdir();
      }
      //???????
      File dbfile = new File(dir, "db_weather.db");
      try {
        if(!dbfile.exists()) {
          dbfile.createNewFile();
        }
        //???????????
        InputStream is = this.getApplicationContext().getResources().openRawResource(R.raw.db_weather);
        FileOutputStream fos = new FileOutputStream(dbfile);
        byte[] buffere=new byte[is.available()];
        is.read(buffere);
        fos.write(buffere);
        is.close();
        fos.close();

      }catch(FileNotFoundException  e){
        e.printStackTrace();
      }catch(IOException e) {
        e.printStackTrace();
      }
    }
    
    //??????????
    public ProgressDialog getProgressDialog(String title, String content) {
      //????????????ProgressDialog
      ProgressDialog dialog=new ProgressDialog(this);
      
      //??????????
      dialog.setTitle(title);
      dialog.setIndeterminate(true);
      dialog.setMessage(content);
      dialog.setCancelable(true);
      return dialog;
    }
    
    //??GPS????????????????
    public synchronized Map<Integer, String> getLocationCityInfo() {
      LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
      
      //????Criteria??????LocationProvider
      Criteria criteria = new Criteria();
      //?????????????
      criteria.setAltitudeRequired(false);
      //??????????????
      criteria.setBearingRequired(false);
      //?????????
      //criteria.setCostAllowed(false);
      
      //??????????Provider
      String provider = locationManager.getBestProvider(criteria, true);
      //???????????
      Location location = locationManager.getLastKnownLocation(provider);
      if(location!=null) {
        double latitude = location.getLatitude();  //?????
          double longitude = location.getLongitude(); //????
          //?????????????????????
          //????????????
            WebAccessTools webTools = new WebAccessTools(this);
          String addressContext = webTools.getWebContent("http://maps.google.cn/maps/geo?output=xml&q="+latitude+","+longitude);
          //???????????
          SAXParserFactory spf = SAXParserFactory.newInstance();
          try {
          SAXParser parser = spf.newSAXParser();
          XMLReader reader = parser.getXMLReader();
          LocationXMLParser handler = new LocationXMLParser();
          reader.setContentHandler(handler);
          
          StringReader read = new StringReader(addressContext);
          // ????????SAX ??????? InputSource ????????????? XML ??
          InputSource source = new InputSource(read);
          
          //?????
          reader.parse(source);
          //????????????
          if(handler.hasAddress())
            return handler.getDetailAddress();
        } catch (ParserConfigurationException e) {
          e.printStackTrace();
        } catch (SAXException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      
      return null;
    }
    
    public void tempMethod() {
      //==================================for test==========================================
      WebAccessTools webTools = new WebAccessTools(this);
        //?????????
        String webContent=webTools.getWebContent("http://m.weather.com.cn/data5/city.xml");
        
        //???????????????????
        String[][] provinces = WeaterInfoParser.parseCity(webContent);
        String[] groups = new String[provinces.length];
        String[][] childs = new String[provinces.length][];
        String[][] cityCode = new String[provinces.length][];
        for(int i=0; i< provinces.length; i++) {
          groups[i] = provinces[i][1];
          //???????????????
          StringBuffer urlBuilder= new StringBuffer("http://m.weather.com.cn/data5/city");
          urlBuilder.append(provinces[i][0]);
          urlBuilder.append(".xml");
          webContent = webTools.getWebContent(urlBuilder.toString());
          String[][] citys = WeaterInfoParser.parseCity(webContent);
          //????????towns
          String[][][] towns = new String[citys.length][][];
          //???????
          int sum=0;
          for(int j=0; j<citys.length; j++) {
            //??????????????
            urlBuilder= new StringBuffer("http://m.weather.com.cn/data5/city");
            urlBuilder.append(citys[j][0]);
            urlBuilder.append(".xml");
            webContent = webTools.getWebContent(urlBuilder.toString());
            towns[j] = WeaterInfoParser.parseCity(webContent);
            sum = sum + towns[j].length;
          }
          
          childs[i] = new String[sum];
          cityCode[i] = new String[sum];
          
          sum=0;
          for(int j=0; j<citys.length; j++) {
            for(int n=0; n<towns[j].length; n++) {
              if(n==0)
                childs[i][sum] = towns[j][n][1];
              else
                childs[i][sum] = towns[j][0][1] + "." + towns[j][n][1];
              
              urlBuilder= new StringBuffer("http://m.weather.com.cn/data5/city");
              urlBuilder.append(towns[j][n][0]);
              urlBuilder.append(".xml");
              
              webContent = webTools.getWebContent(urlBuilder.toString());
              String[][] code=WeaterInfoParser.parseCity(webContent);
              cityCode[i][sum] = code[0][1];
              sum = sum + 1;
            }
          }
          urlBuilder=null;
        }
        
        BaseExpandableListAdapter adapter=new MyListAdapter(this, provinceList, groups, childs);
        provinceList.setAdapter(adapter);
        
        //============================Create Database================================
        //????????????
        String path="/data"+ Environment.getDataDirectory().getAbsolutePath() + "/com.imlongluo.weather/db_weather.db";
        
        SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase
                                  (path, null);
        //????????
        String sql="create table provinces (_id integer primary key autoincrement, name text)";
        database.execSQL(sql);
        
        //?????
        sql = "create table citys (_id integer primary key autoincrement, province_id integer, name text, city_num text)";
        database.execSQL(sql);
        
        //???????????
        ContentValues cv = null;
        for(int i=0; i<provinces.length; i++) {
          cv = new ContentValues();
          cv.put("name", provinces[i][1]);
          database.insert("provinces", null, cv);
        }
        //??????????
        for(int i=0; i<childs.length; i++) {
          for(int j=0; j<childs[i].length; j++) {
            cv = new ContentValues();
            cv.put("province_id", i);
            cv.put("name", childs[i][j]);
            cv.put("city_num", cityCode[i][j]);
            database.insert("citys", null, cv);
          }
        }
        cv = null;
        database.close();
    }
    
    //???????????????????
    private class MyHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
      
      //???????????????????????
      adapter=new MyListAdapter(SetCityActivity.this, provinceList, groups, childs);
          provinceList.setAdapter(adapter);
          
          //????????????????
          provinceList.setOnChildClickListener(new OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
            int groupPosition, int childPosition, long id) {
          //?????????????MainActivity
          
          //========???????????=======
          //???????
          String cityName = (String)adapter.getChild(groupPosition, childPosition);
          //?????????????
          DBHelper dbHelper = new DBHelper(SetCityActivity.this, "db_weather.db");
          String cityCode = dbHelper.getCityCodeByName(cityName);
          
          Dialog dialog = getProgressDialog("", "??????...");
          dialog.show();
          GoToMainActivity thread = new GoToMainActivity(cityCode, dialog);
          thread.start();
          
          return false;
        }
            
          });
    }
    }
    
    //????????????????
    private class LocateHandler extends Handler {
      //????????????
      private TextView textView;
      
      public LocateHandler(TextView textView) {
        this.textView = textView;
      }
      
    @Override
    public void handleMessage(Message msg) {
      Bundle data = msg.getData();
      int provinceIndex = data.getInt("provinceIndex");
      int cityIndex = data.getInt("cityIndex");
      //???????????????
      if(provinceIndex >=0 && provinceIndex < groups.length && 
          cityIndex >=0 && cityIndex < childs[provinceIndex].length) {
        //????????
        textView.setText(childs[provinceIndex][cityIndex]);
        
        //?????????????MainActivity
        Dialog dialog = getProgressDialog("", "??????...");
        dialog.show();
        GoToMainActivity thread = new GoToMainActivity(cityCodes[provinceIndex][cityIndex], dialog);
        thread.start();
      } else {
        textView.setText("???????");
      }
    }
    }
    
    //??????????????????MainActivity
    private class GoToMainActivity extends Thread {
      
      //???????????
      private String cityCode;
      //??????????????
      private Dialog dialog;
      
      public GoToMainActivity(String cityCode, Dialog dialog) {
        this.cityCode = cityCode;
        this.dialog = dialog;
      }
      
      public void run() {
        //????????SharedPreferences??????
      SharedPreferences.Editor edit = getSharedPreferences(CITY_CODE_FILE, MODE_PRIVATE).edit();
      //????????
      edit.putString("code", cityCode);
      edit.commit();

      //???????widgetId???????????????MainActivity?Widget
      if(mAppWidgetId==AppWidgetManager.INVALID_APPWIDGET_ID) {
        //??????????????Activity
        Intent intent = getIntent();
        //????????????????????????????????????????
        intent.putExtra("updateWeather", true);
        SetCityActivity.this.setResult(0, intent);
      } else {
        //??????widget
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(SetCityActivity.this);
        RemoteViews views = new RemoteViews(SetCityActivity.this.getPackageName(),
            R.layout.widget_layout);
        //??widget
        Log.i("widget", "===================update  weather===========================");
        //??widget
        WeatherWidget.updateAppWidget(views, SetCityActivity.this, appWidgetManager, cityCode);
        
        appWidgetManager.updateAppWidget(mAppWidgetId, views);
        //????????
        Intent resultValue = new Intent();
        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        setResult(RESULT_OK, resultValue);
      }
      SetCityActivity.this.finish();
      dialog.cancel();
      dialog.dismiss();
      }
    }
}




Java Source Code List

.WebAccessTools.java
com.imlongluo.weather.app.MainActivity.java
com.imlongluo.weather.app.SetCityActivity.java
com.imlongluo.weather.app.UpdateWidgetService.java
com.imlongluo.weather.app.WeatherWidget.java
com.imlongluo.weather.db.DBHelper.java
com.imlongluo.weather.location.GPSListAdapter.java
com.imlongluo.weather.location.MyListAdapter.java
com.imlongluo.weather.utils.LocationXMLParser.java
com.imlongluo.weather.utils.WeaterInfoParser.java