仿墨迹天气心得

  闲来无事写了个仿墨迹天气的小软件~

  首先遇见了布局问题,下面的tabwidget里面放得到底是什么

View Code
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/www">
<LinearLayout 
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout 
android:id="@android:id/tabcontent"
android:layout_width="fill_parent" 
android:layout_height="0.0dip" 
android:layout_weight="1.0" 
/>
<TabWidget 
android:id="@android:id/tabs" 
android:visibility="gone" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:layout_weight="0.0" />
<RadioGroup 
android:id="@+id/main_radio"
android:gravity="center_vertical"
android:layout_gravity="bottom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/maintab_toolbar_bg"
android:orientation="horizontal"

>

<RadioButton 
android:id="@+id/radio_button0" 
android:tag="radio_button0" 
android:layout_marginTop="2.0dip" 
android:text="@string/main_home" 
android:drawableTop="@drawable/tab_weather" 
style="@style/main_tab_bottom" />
<RadioButton 
android:id="@+id/radio_button1" 
android:tag="radio_button1" 
android:layout_marginTop="2.0dip" 
android:text="@string/main_message" 
android:drawableTop="@drawable/tab_trend" 
style="@style/main_tab_bottom" />
<RadioButton 
android:id="@+id/radio_button2" 
android:tag="radio_button2" 
android:layout_marginTop="2.0dip" 
android:text="@string/main_ziliao" 
android:drawableTop="@drawable/tab_index" 
style="@style/main_tab_bottom" />
<RadioButton 
android:id="@+id/radio_button3" 
android:tag="radio_button3" 
android:layout_marginTop="2.0dip" 
android:text="@string/main_find" 
android:drawableTop="@drawable/tab_tools" 
style="@style/main_tab_bottom" />
<RadioButton 
android:id="@+id/radio_button4" 
android:tag="radio_button4" 
android:layout_marginTop="2.0dip" 
android:text="@string/more" 
android:drawableTop="@drawable/tab_setting" 
style="@style/main_tab_bottom" />
</RadioGroup>

</LinearLayout>

</TabHost>

 

然后tabactivity中的代码:

View Code
  1 package com.chen.activity;
  2 
  3 import java.io.File;
  4 import java.io.FileNotFoundException;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.io.InputStream;
  8 import java.util.List;
  9 import java.util.Map;
 10 
 11 import com.chen.activity.R;
 12 import com.chen.activity.TianQiActivity;
 13 import com.chen.db.DBHelper;
 14 import com.chen.util.FileUtil;
 15 
 16 import android.app.TabActivity;
 17 import android.content.Intent;
 18 import android.content.res.Resources.NotFoundException;
 19 import android.database.sqlite.SQLiteDatabase;
 20 import android.os.Bundle;
 21 import android.widget.RadioGroup;
 22 import android.widget.RadioGroup.OnCheckedChangeListener;
 23 import android.widget.TabHost;
 24 
 25 public class MainActivity extends TabActivity{
 26 /** Called when the activity is first created. */
 27 private RadioGroup group;
 28 private TabHost tabHost;
 29 public static final String DATABASE_PATH="/data/data/com.chen.activity/databases";
 30 public static final String TAB_HOME="tabHome";
 31 public static final String TAB_ZHISHU="tab_zhishu";
 32 public static final String TAB_QUSHI="tab_qushi";
 33 public static final String TAB_GONGJU="tab_gongJu";
 34 public static final String TAB_CHAZHAO="tab_chazhao";
 35 String databaseFileName = DATABASE_PATH + "/" + DATABASE_FILENAME;
 36 private static final String DATABASE_FILENAME = "weather.db";
 37 public void onCreate(Bundle savedInstanceState) {
 38 super.onCreate(savedInstanceState);
 39 setContentView(R.layout.main);
 40 checkDBExists();
 41 group=(RadioGroup)findViewById(R.id.main_radio);
 42 tabHost=getTabHost();
 43 tabHost.addTab(tabHost.newTabSpec(TAB_HOME)
 44 .setIndicator(TAB_HOME)
 45 .setContent(new Intent(this,TianQiActivity.class)));
 46 tabHost.addTab(tabHost.newTabSpec(TAB_ZHISHU)
 47 .setIndicator(TAB_ZHISHU)
 48 .setContent(new Intent(this,ZhiShuActivity.class)));
 49 tabHost.addTab(tabHost.newTabSpec(TAB_QUSHI)
 50 .setIndicator(TAB_QUSHI)
 51 .setContent(new Intent(this,ZiLiaoActivity.class)));
 52 tabHost.addTab(tabHost.newTabSpec(TAB_QUSHI)
 53 .setIndicator(TAB_CHAZHAO)
 54 .setContent(new Intent(this,ChaZhaoActivty.class)));
 55 group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
 56 
 57 public void onCheckedChanged(RadioGroup group, int checkedId) {
 58 // TODO Auto-generated method stub
 59 switch (checkedId) {
 60 case R.id.radio_button0:
 61 tabHost.setCurrentTabByTag(TAB_HOME);
 62 break;
 63 case R.id.radio_button1:
 64 tabHost.setCurrentTabByTag(TAB_ZHISHU);
 65 break;
 66 case R.id.radio_button2:
 67 tabHost.setCurrentTabByTag(TAB_QUSHI);
 68 break;
 69 case R.id.radio_button3:
 70 tabHost.setCurrentTabByTag(TAB_CHAZHAO);
 71 break;
 72 case R.id.radio_button4:
 73 break;
 74 default:
 75 break;
 76 }
 77 }
 78 });
 79 // 
 80 // FileUtil fileUtil=new FileUtil();
 81 // DBHelper dbHelper=new DBHelper(this);
 82 // db=dbHelper.getWritableDatabase();
 83 // db.beginTransaction();
 84 //     try {
 85 //     InputStream is = getResources().getAssets().open("weathercity.txt");
 86 //     List<Map<String, String>> cities=fileUtil.getCity(is);
 87 //     dbHelper.insertCities(cities);
 88 //     db.setTransactionSuccessful();
 89 //     } catch (IOException e) {
 90 //     e.printStackTrace();
 91 //     }finally{
 92 //     db.endTransaction();
 93 //     }
 94 }
 95 //检查数据文件是否拷贝到databases目录下
 96 private void checkDBExists() {
 97 // 从资源文件中将数据库创建/data/data/com.chen.activity/databases/weather.db
 98 // 1,获得路径
 99 File dir = new File(DATABASE_PATH);
100 if (!dir.exists()) {
101 dir.mkdir();
102 }
103 // 2,获得资源文件
104 if (!(new File(databaseFileName).exists())) {
105 try {
106 // 3,读取资源并创建流
107 InputStream is = getResources().openRawResource(R.raw.weather);
108 FileOutputStream fos = new FileOutputStream(databaseFileName);
109 // 4,复制
110 byte[] buffer = new byte[8192];
111 int count = 0;
112 while ((count = is.read(buffer)) > 0) {
113 fos.write(buffer, 0, count);
114 }
115 // 5,关闭流
116 fos.close();
117 is.close();
118 } catch (NotFoundException e) {
119 e.printStackTrace();
120 } catch (FileNotFoundException e) {
121 e.printStackTrace();
122 } catch (IOException e) {
123 e.printStackTrace();
124 }
125 }
126 }
127 }

 

我所用的数据源是http://m.weather.com.cn/data/101230103.html的数据源,所以必须知道相关城市的编码,在网上搜到了txt的版本,所以没办法只有读取文本文件,将内容一条一条的添加进来数据的格式是这样的101010100=北京,考虑到用户搜索的时候可能会直接拼音搜索,所以又添加一个城市拼音的字段,而将汉字转换为拼音用到了pinyin4j这样一个开源jar包

View Code
public class FileUtil {

public List<Map<String, String>> getCity(InputStream is){
List<Map<String, String>> cities;
Map<String, String> city;
InputStreamReader reader=null;
try {
reader=new InputStreamReader(is, "GBK");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br=new BufferedReader(reader); 
String line;
cities=new ArrayList<Map<String,String>>();
try {
while((line=br.readLine())!=null){
String[] array=line.split("="); 
city=new HashMap<String,String>();
city.put("city_num", array[0]);
city.put("city_name", array[1]);
city.put("city_name_pinyin", cn2Spell(array[1]));
cities.add(city);
}


} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cities;    
}
public String cn2Spell(String chinese) { 
StringBuffer pybf = new StringBuffer(); 
char[] arr = chinese.toCharArray(); 
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); 
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); 
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); 
for (int i = 0; i < arr.length; i++) { 
if (arr[i] > 128) { 
try { 
pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]); 
} catch (BadHanyuPinyinOutputFormatCombination e) { 
e.printStackTrace(); 
} 
} else { 
pybf.append(arr[i]); 
} 
} 
return pybf.toString(); 
}

}

对数据文件的操作

//        FileUtil fileUtil=new FileUtil();
//        DBHelper dbHelper=new DBHelper(this);
//        db=dbHelper.getWritableDatabase();
//        db.beginTransaction();
//        try {
//            InputStream is = getResources().getAssets().open("weathercity.txt");
//            List<Map<String, String>> cities=fileUtil.getCity(is);
//            dbHelper.insertCities(cities);
//            db.setTransactionSuccessful();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }finally{
//            db.endTransaction();
//        }
public void insertCities(List<Map<String, String>> cities){
        SQLiteDatabase db=getWritableDatabase();
        ContentValues cv=new ContentValues();
        for (int i = 0; i < cities.size(); i++) {
            city=new HashMap<String, String>();
            city=cities.get(i);
            cv.put("city_num", city.get("city_num"));
            cv.put("city_name", city.get("city_name"));
            cv.put("city_name_pinyin", city.get("city_name_pinyin"));
            db.insert("city", null, cv);
        }
    }

整个将数据添加到数据库后,这时候就该从网络获取数据了

View Code
public class HttpDownloader {
    private URL url = null;


    public String download(String urlStr) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader buffer = null;
        try {
            
            url = new URL(urlStr);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            
            buffer = new BufferedReader(new InputStreamReader(urlConn
                    .getInputStream()));
            while ((line = buffer.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                buffer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

将获取到的json数据进行解析

View Code
package com.chen.util;


import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.chen.bean.WeatherInfo;

public class JsonUtil {
    
    public WeatherInfo parserJson(String jsonData){
        WeatherInfo weatherInfo=new WeatherInfo();
        try {
            JSONObject jsonObject=new JSONObject(jsonData).getJSONObject("weatherinfo");
            String str=jsonObject.getString("city");
            Log.i("Json----->", str);
            
            weatherInfo.setCity(jsonObject.getString("city").toString());
            weatherInfo.setCity_en(jsonObject.getString("city_en").toString());
            weatherInfo.setCityid(jsonObject.getString("cityid"));
            weatherInfo.setDate_y(jsonObject.getString("date_y"));
            weatherInfo.setFchh(jsonObject.getString("fchh"));
            weatherInfo.setFl1(jsonObject.getString("fl1"));
            weatherInfo.setFl2(jsonObject.getString("fl2"));
            weatherInfo.setFl3(jsonObject.getString("fl3"));
            weatherInfo.setFl4(jsonObject.getString("fl4"));
            weatherInfo.setFl5(jsonObject.getString("fl5"));
            weatherInfo.setFl6(jsonObject.getString("fl6"));
            weatherInfo.setFx1(jsonObject.getString("fx1"));
            weatherInfo.setFx2(jsonObject.getString("fx2"));
            weatherInfo.setImg1(jsonObject.getString("img1"));
            weatherInfo.setImg2(jsonObject.getString("img2"));
            weatherInfo.setImg3(jsonObject.getString("img3"));
            weatherInfo.setImg4(jsonObject.getString("img4"));
            weatherInfo.setImg5(jsonObject.getString("img5"));
            weatherInfo.setImg6(jsonObject.getString("img6"));
            weatherInfo.setImg7(jsonObject.getString("img7"));
            weatherInfo.setImg8(jsonObject.getString("img8"));
            weatherInfo.setImg9(jsonObject.getString("img9"));
            weatherInfo.setImg10(jsonObject.getString("img10"));
            weatherInfo.setImg11(jsonObject.getString("img11"));
            weatherInfo.setImg12(jsonObject.getString("img12"));
            weatherInfo.setImg_title1(jsonObject.getString("img_title1"));
            weatherInfo.setImg_title2(jsonObject.getString("img_title2"));
            weatherInfo.setImg_title3(jsonObject.getString("img_title3"));
            weatherInfo.setImg_title4(jsonObject.getString("img_title4"));
            weatherInfo.setImg_title5(jsonObject.getString("img_title5"));
            weatherInfo.setImg_title6(jsonObject.getString("img_title6"));
            weatherInfo.setImg_title7(jsonObject.getString("img_title7"));
            weatherInfo.setImg_title8(jsonObject.getString("img_title8"));
            weatherInfo.setImg_title9(jsonObject.getString("img_title9"));
            weatherInfo.setImg_title10(jsonObject.getString("img_title10"));
            weatherInfo.setImg_title11(jsonObject.getString("img_title11"));
            weatherInfo.setImg_title12(jsonObject.getString("img_title12"));
            weatherInfo.setIndex(jsonObject.getString("index"));
            weatherInfo.setIndex48(jsonObject.getString("index48"));
            weatherInfo.setIndex48_d(jsonObject.getString("index48_d"));
            weatherInfo.setIndex48_uv(jsonObject.getString("index48_uv"));
            weatherInfo.setIndex_ag(jsonObject.getString("index_ag"));
            weatherInfo.setIndex_cl(jsonObject.getString("index_cl"));
            weatherInfo.setIndex_co(jsonObject.getString("index_co"));
            weatherInfo.setIndex_d(jsonObject.getString("index_d"));
            weatherInfo.setIndex_ls(jsonObject.getString("index_ls"));
            weatherInfo.setIndex_uv(jsonObject.getString("index_uv"));
            weatherInfo.setIndex_xc(jsonObject.getString("index_xc"));
            
            weatherInfo.setSt1(jsonObject.getString("st1"));
            weatherInfo.setSt2(jsonObject.getString("st2"));
            weatherInfo.setSt3(jsonObject.getString("st3"));
            weatherInfo.setSt4(jsonObject.getString("st4"));
            weatherInfo.setSt5(jsonObject.getString("st5"));
            weatherInfo.setSt6(jsonObject.getString("st6"));
            weatherInfo.setTemp1(jsonObject.getString("temp1"));
            weatherInfo.setTemp2(jsonObject.getString("temp2"));
            weatherInfo.setTemp3(jsonObject.getString("temp3"));
            weatherInfo.setTemp4(jsonObject.getString("temp4"));
            weatherInfo.setTemp5(jsonObject.getString("temp5"));
            weatherInfo.setTemp6(jsonObject.getString("temp6"));
            weatherInfo.setTempF1(jsonObject.getString("tempF1"));
            weatherInfo.setTempF2(jsonObject.getString("tempF2"));
            weatherInfo.setTempF3(jsonObject.getString("tempF3"));
            weatherInfo.setTempF4(jsonObject.getString("tempF4"));
            weatherInfo.setTempF5(jsonObject.getString("tempF5"));
            weatherInfo.setTempF6(jsonObject.getString("tempF6"));
            
            weatherInfo.setWeather1(jsonObject.getString("weather1"));
            weatherInfo.setWeather2(jsonObject.getString("weather2"));
            weatherInfo.setWeather3(jsonObject.getString("weather3"));
            weatherInfo.setWeather4(jsonObject.getString("weather4"));
            weatherInfo.setWeather5(jsonObject.getString("weather5"));
            weatherInfo.setWeather6(jsonObject.getString("weather6"));
            weatherInfo.setWeek(jsonObject.getString("week"));
            weatherInfo.setWind1(jsonObject.getString("wind1"));
            weatherInfo.setWind2(jsonObject.getString("wind2"));
            weatherInfo.setWind3(jsonObject.getString("wind3"));
            weatherInfo.setWind4(jsonObject.getString("wind4"));
            weatherInfo.setWind5(jsonObject.getString("wind5"));
            weatherInfo.setWind6(jsonObject.getString("wind6"));
            
            
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return weatherInfo;
    }
}

在用户输入城市名称时需要查询数据库进行智能提示,于是就要重写CursorAdapter

View Code
package com.chen.adapter;

import com.chen.db.DBHelper;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class AutoCompleteAdapter extends CursorAdapter {
    private int columnIndex;
    private DBHelper dbHelper;
    private Context context;
    public AutoCompleteAdapter(Context context, Cursor c ,int col) {
        super(context, c);
        this.columnIndex=col;
        this.context=context;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // TODO Auto-generated method stub
        final LayoutInflater inflater=LayoutInflater.from(context);
        final TextView view=(TextView)inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
        view.setText(cursor.getString(columnIndex));
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // TODO Auto-generated method stub
         ((TextView) view).setText(cursor.getString(columnIndex));   
    }

    @Override
    public String convertToString(Cursor cursor) {
        // TODO Auto-generated method stub
        return cursor.getString(columnIndex);
    }

    @Override
    public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
        // TODO Auto-generated method stub
        dbHelper=new DBHelper(context);
        SQLiteDatabase db=dbHelper.getReadableDatabase();
        String selection="";
        if (constraint!=null&&constraint.toString().matches("[\u4e00-\u9fa5]+")) {
            selection = "city_name like \'" + constraint.toString() +"%\'";
        }else{
            selection= "city_name_pinyin like \'" + constraint.toString() +"%\'";
        }
        Cursor cursor=db.query("city", new String[]{"city_name","_id"}, selection, null, null, null, null);
        return cursor;
    }
    

}

而在模糊查询时又要检查用户输入的是拼音还是汉字

public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
        // TODO Auto-generated method stub
        dbHelper=new DBHelper(context);
        SQLiteDatabase db=dbHelper.getReadableDatabase();
        String selection="";
        if (constraint!=null&&constraint.toString().matches("[\u4e00-\u9fa5]+")) {
            selection = "city_name like \'" + constraint.toString() +"%\'";
        }else{
            selection= "city_name_pinyin like \'" + constraint.toString() +"%\'";
        }
        Cursor cursor=db.query("city", new String[]{"city_name","_id"}, selection, null, null, null, null);
        return cursor;
    }

在cityselectactivity中

        actv=(AutoCompleteTextView)findViewById(R.id.actv_city);
        //设置输入触发的最小字符数
        actv.setThreshold(1);
        //设置提示宽度
        actv.setDropDownHeight(350);
        //给AutoCompleteTextView设置适配器
        AutoCompleteAdapter adapter=new AutoCompleteAdapter(this, null, 0);
        actv.setAdapter(adapter);

 

这时候开始遇见更大的问题,因为需要将用户要搜索的城市信息编码、名字、拼音传给前一个tabactivity中的tianqiactivity,显然不可以使用"startActivity()"方法,而要使用"startActivityForResult"方法。这样就必须在前一个activity也就是tianqiactivity中重写

 protected void onActivityResult(int requestCode,int resultCode,Intent data){
  
  switch(requestCode){
  case RESULT_OK:
   /*取得来自SecondActivity页面的数据,并显示到画面*/
   Bundle bundle = data.getExtras();
   
         /*获取Bundle中的数据,注意类型和key*/
         String name = bundle.getString("Name");
         boolean ismale = bundle.getBoolean("Ismale");
  }
 }

不知道为什么我使用的时候传值不成功,于是果断采用广播

View Code
package com.chen.activity;


import com.chen.adapter.AutoCompleteAdapter;
import com.chen.db.DBHelper;
import com.chen.util.JsonUtil;
import com.chen.util.WebUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;

public class CitySelectActivity extends Activity {
    private Button btnSure;
    //private EditText etSearch; 
    private WebUtil webUtil;
    private JsonUtil jsonUtil;
    private AutoCompleteTextView actv;
    private DBHelper dbHelper;
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.city_select);
        //etSearch=(EditText)findViewById(R.id.et_sosuo);
        btnSure=(Button)findViewById(R.id.btn_sure);
        actv=(AutoCompleteTextView)findViewById(R.id.actv_city);
        //设置输入触发的最小字符数
        actv.setThreshold(1);
        //设置提示宽度
        actv.setDropDownHeight(350);
        //给AutoCompleteTextView设置适配器
        AutoCompleteAdapter adapter=new AutoCompleteAdapter(this, null, 0);
        actv.setAdapter(adapter);
        btnSure.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                //String city=etSearch.getText().toString();
                //得到city值设置到bundle中
                dbHelper=new DBHelper(CitySelectActivity.this);
                
                String city=actv.getText().toString();
                int count=dbHelper.isInDataBase(city);
                if(!city.equals("")&&count!=0){
                    Bundle bundle=new Bundle();
                    bundle.putString("city", city);
                    //向外发送广播,广播用WeatherInfoReceiver接收
                    Intent intent=new Intent("com.chen.CitySelectActivity.WeatherInfoReceiver");
                    intent.putExtras(bundle);
                    //发出广播,广播一旦发出 接收器就开始工作
                    sendBroadcast(intent);
                    CitySelectActivity.this.finish();
                }else {
                    AlertDialog.Builder builder=new AlertDialog.Builder(CitySelectActivity.this);
                    LayoutInflater inflater=LayoutInflater.from(CitySelectActivity.this);
                    final View view=inflater.inflate(R.layout.alert_dialog_city_not_found, null);
                    builder.setView(view);
                    builder.setTitle("友情提示");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                }
            }
        });
    }
    
    
    
    
}

然后在tianqiactivty注册广播接受获取来的值

  //实例化过滤器并设置要过滤的广播   
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.chen.CitySelectActivity.WeatherInfoReceiver");
        //注册广播,开始运行WeatherInfoReceiver中得代码
        registerReceiver(new WeatherInfoReceiver(), filter);
View Code
class WeatherInfoReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
//            weatherInfo=(WeatherInfo)intent.getSerializableExtra("weatherInfo");
//            updateWeather(weatherInfo);
            //得到广播中得数据
            String city=intent.getStringExtra("city");
            //将得到的数据存储到SharedPreferences中,方便启动程序的时候直接用
            SharedPreferences preferences=getSharedPreferences("CityName", MODE_PRIVATE);
            SharedPreferences.Editor editor=preferences.edit();
            editor.putString("cityName", city);
            editor.commit();
            //更新tv_city的显示城市
            tv_city.setText(city);
            //给更新按钮设置点击事件
            imgBtn_update.setOnClickListener(new UpdateOnClickListener());
        }
        
    }

然后就是整个应用我觉得最难的部分更新视图,开始的时候我用了AsyncTask,关于它的博文大家可以参考http://www.cnblogs.com/devinzhang/archive/2012/02/13/2350070.html

后来又试了下Handler,看代码

Handler handler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
            case TianQiActivity.RESULT_OK:
                updateWeather((WeatherInfo)msg.obj);
                imgBtn_update.setVisibility(View.VISIBLE);
                proBar.setVisibility(View.INVISIBLE);
                break;
            default:
                break;
            }
            super.handleMessage(msg);
        }
        
    };
class UpdateOnClickListener implements OnClickListener{

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (!note_Internet(TianQiActivity.this)) {
                 Toast.makeText(TianQiActivity.this, "亲!不联网就想用啊 ?", Toast.LENGTH_SHORT).show();
            }else{
                imgBtn_update.setVisibility(View.INVISIBLE);
                proBar.setVisibility(View.VISIBLE);
                //开辟新线程进行网络访问这种耗时的操作
                WeatherInfoRunnable runnable=new WeatherInfoRunnable();
                mThread=new Thread(runnable);
                mThread.start();
            }
        }
        
    }
    
    class WeatherInfoRunnable implements Runnable{

        @Override
        public void run() {
            // TODO Auto-generated method stub
            String city=tv_city.getText().toString();
            dbHelper=new DBHelper(TianQiActivity.this);
            String cityNum=dbHelper.selectNumByName(city);
            dbHelper.close();
            webUtil=new WebUtil();
            String weather=webUtil.getWeatherMsg(cityNum);
            jsonUtil=new JsonUtil();
            weatherInfo=jsonUtil.parserJson(weather);
            //handler.post(new WeatherInfoRunnable());
            handler.obtainMessage(TianQiActivity.RESULT_OK, weatherInfo).sendToTarget();
        }
        
    }

还有推算星期几的一个小方法

public String afterNDay(int n){
        String today=weatherInfo.getWeek().substring(2, 3);
        String[] week={"日","一","二","三","四","五","六"};
        if (today.equals("日")) {
            return week[n%7];
        }else if(today.equals("一")){
            return week[(1+n%7)%7];
        }else if(today.equals("二")){
            return week[(2+n%7)%7];
        }else if(today.equals("三")){
            return week[(3+n%7)%7];
        }else if(today.equals("四")){
            return week[(4+n%7)%7];
        }else if(today.equals("五")){
            return week[(5+n%7)%7];
        }else if(today.equals("六")){
            return week[(6+n%7)%7];
        }
        return null;
    }

 

 

posted @ 2012-08-27 10:09  愤怒的coder  Views(399)  Comments(0)    收藏  举报