您的位置:首页 > 其它

Fragment中实现自动定位当前城市,点击刷新按钮更新天气信息

2014-09-02 19:02 501 查看
定位用的是百度SDKv4.2接口

城市对应的city_code采用的是查询本地数据库的方式,这一部分并非原创,只是借鉴了别人的一篇帖子,在此非常感这篇博客的主人,细节这篇帖子里说的很详细,我就不重复了,http://blog.csdn.net/eyu8874521/article/details/11574485

获取到city_code之后是通过调用http://www.weather.com.cn/data/cityinfo/ + city_code + .html方式获取天气信息的,字符串拼接方式,当然也可以使用其他的接口获取天气信息

主要代码如下:

package com.fcability.tools;

import android.annotation.SuppressLint;

import android.app.Fragment;

import android.database.Cursor;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import android.view.LayoutInflater;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.ViewGroup;

import android.widget.ImageView;

import android.widget.LinearLayout;

import android.widget.ProgressBar;

import android.widget.TextView;

import android.widget.Toast;

import com.baidu.location.BDLocation;

import com.baidu.location.BDLocationListener;

import com.baidu.location.LocationClient;

import com.baidu.location.LocationClientOption;

import com.example.weatherbycityname.DBHelper;

import com.example.weatherbycityname.DBManager;

import com.fcability.dayoiot.R;

import org.apache.http.HttpResponse;

import org.apache.http.ParseException;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.protocol.HTTP;

import org.apache.http.util.EntityUtils;

import org.json.JSONException;

import org.json.JSONObject;

import java.io.IOException;

public class WeatherReporterFragment extends Fragment{

private LinearLayout changeCity;

private TextView cityText;

private ImageView refresh;

private ProgressBar refreshing;

private LocationClient mLocationClient = null;

private BDLocationListener myListener = new MyLocationListener();

public String city;

private TextView txt_weather_temp, txt_weather_detail, release_time;

private int szr = 1;



@Override

public void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

// 声明LocationClient类,Fragment中是调用getActivity()方法获取关联的Activity

mLocationClient = new LocationClient(getActivity());

// 注册监听函数

mLocationClient.registerLocationListener(myListener);

// 设置定位参数

setLocationOption();

}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

// TODO Auto-generated method stub

View view = inflater.inflate(R.layout.weather, container, false);

txt_weather_temp = (TextView) view.findViewById(R.id.txt_weather_temp);

txt_weather_detail = (TextView) view.findViewById(R.id.txt_weather_detail);

release_time = (TextView) view.findViewById(R.id.ptime);

changeCity = (LinearLayout) view.findViewById(R.id.change_city_layout);

cityText = (TextView) view.findViewById(R.id.city);

refresh = (ImageView) view.findViewById(R.id.refresh);

refreshing = (ProgressBar) view.findViewById(R.id.refreshing);



changeCity.setOnClickListener(new ButtonListener());

refresh.setOnClickListener(new ButtonListener());

Toast.makeText(getActivity(), "正在定位...", Toast.LENGTH_LONG).show();



return view;

}



class ButtonListener implements OnClickListener {

@Override

public void onClick(View v) {

switch (v.getId()) {

case R.id.change_city_layout:

break;

case R.id.refresh:

refreshing(true);

Toast.makeText(getActivity(), "正在更新...", Toast.LENGTH_LONG).show();

SetViewVisi(View.INVISIBLE);

initWaetherData();

break;

default:

break;

}

}

}



public void initWaetherData() {

new Thread(new Runnable() {

@Override

public void run() {

// TODO Auto-generated method stub

DBHelper helper = new DBHelper(getActivity().getApplicationContext());

DBManager manager = new DBManager(getActivity().getApplicationContext());

manager.copyDatabase();

String cityCode = null;

String sql = "select * from city_table where CITY =" + "'"

+ city + "'" + ";";

try{

Cursor cursor = helper.getReadableDatabase()

.rawQuery(sql, null);

if (cursor != null) {

cursor.moveToFirst();

cityCode = cursor.getString(cursor

.getColumnIndex("WEATHER_ID"));

}

cursor.close();

}catch(Exception e){

e.printStackTrace();

}

helper.close();

String weatherUrl = "http://www.weather.com.cn/data/cityinfo/"

+ cityCode + ".html";

String weatherJson = queryStringForGet(weatherUrl);

try {

JSONObject jsonObject = new JSONObject(weatherJson);

JSONObject weatherObject = jsonObject

.getJSONObject("weatherinfo");

Message message = new Message();

message.obj = weatherObject;

handler.sendMessage(message);

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}).start();

}

@SuppressLint("HandlerLeak")

Handler handler = new Handler() {

@Override

public void handleMessage(Message msg) {

// TODO Auto-generated method stub

super.handleMessage(msg);

JSONObject object = (JSONObject) msg.obj;

try {

Toast.makeText(getActivity(), "更新成功", Toast.LENGTH_LONG).show();

txt_weather_temp.setText(object.getString("temp2") + "/"

+ object.getString("temp1"));

txt_weather_detail.setText(object.getString("weather"));

release_time.setText(object.getString("ptime") + "发布");

SetViewVisi(View.VISIBLE);



refreshing(false);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

};

private void SetViewVisi(int value){

txt_weather_temp.setVisibility(value);

txt_weather_detail.setVisibility(value);

release_time.setVisibility(value);

}



private String queryStringForGet(String url) {

HttpGet request = new HttpGet(url);

String result = null;

try {

HttpResponse response = new DefaultHttpClient().execute(request);

if (response.getStatusLine().getStatusCode() == 200) {

result = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);

return result;

}

} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ParseException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return result;

}



/**

* 刷新时显示进度条

*

* @param isRefreshing

* 是否正在刷新

*/

private void refreshing(boolean isRefreshing) {

if (isRefreshing) {

refresh.setVisibility(View.GONE);

refreshing.setVisibility(View.VISIBLE);

} else {

refresh.setVisibility(View.VISIBLE);

refreshing.setVisibility(View.GONE);

}

}



/**

* 实现BDLocationListener接口

*

*/

class MyLocationListener implements BDLocationListener {

@Override

public void onReceiveLocation(BDLocation location) {

if (location == null)

return;

int code = location.getLocType();

String addr = location.getAddrStr();

if (code == 161 && addr != null) {

// 定位成功

System.out.println(addr);

city = formatCity(addr);

if(szr == 1){

Toast.makeText(getActivity(), "定位成功", Toast.LENGTH_LONG).show();

szr = 0;

}

cityText.setText(city);

} else {

Log.w("WeatherReportFragment", "******************Location Fail*******************");

Log.w("WeatherReportFragment", "******************Location Fail*******************");

return;

}

}

}

/**

* 设置定位参数。 定位模式(单次定位,定时定位),返回坐标类型,是否打开GPS等等。

*/

private void setLocationOption() {

LocationClientOption option = new LocationClientOption();

option.setOpenGps(true);

option.setIsNeedAddress(true);// 返回的定位结果包含地址信息,这个方法和以前的SDK不同

option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02

option.setScanSpan(24 * 60 * 60 * 1000);// 设置发起定位请求的间隔时间

mLocationClient.setLocOption(option);

}

/**

* 将位置信息转换为城市

*

* @param addr 位置

* 北京市朝阳区 会得到 朝阳,**省**市XX县 会得到 县级的名字XX

* @return 城市名称

*/

private String formatCity(String addr) {

String city = null;

if (addr.contains("北京市") && addr.contains("区")) {

city = addr.substring(addr.indexOf("市") + 1, addr.indexOf("区"));

} else if (addr.contains("县")) {

city = addr.substring(addr.indexOf("市") + 1, addr.indexOf("县"));

} else {

int start = addr.indexOf("市");

int end = addr.lastIndexOf("市");

if (start == end) {

if (addr.contains("省")) {

city = addr.substring(addr.indexOf("省") + 1,

addr.indexOf("市"));

} else if (addr.contains("市")) {

city = addr.substring(0, addr.indexOf("市"));

}

} else {

city = addr.substring(addr.indexOf("市") + 1,

addr.lastIndexOf("市"));

}

}

return city;

}

@Override

public void onStart() {

// TODO Auto-generated method stub

if (!mLocationClient.isStarted())

{

mLocationClient.start();

}

super.onStart();

}

@Override

public void onStop() {

// TODO Auto-generated method stub

mLocationClient.stop();

super.onStop();

}

}

对应的weather.xml文件如下:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/weather_bg"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >



<LinearLayout

android:id="@+id/title_bar_layout"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical" >

<RelativeLayout

android:layout_width="match_parent"

android:layout_height="45dp" >

<LinearLayout

android:id="@+id/change_city_layout"

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:layout_centerVertical="true"

android:background="@drawable/title_bar_image_pressed_effect"

android:orientation="horizontal" >

<ImageView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center_vertical"

android:layout_marginLeft="10dp"

android:src="@drawable/locate_indicator" />

<TextView

android:id="@+id/city"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center_vertical"

android:layout_marginLeft="10dp"

android:layout_marginRight="10dp"

android:textColor="@color/white"

android:textSize="20sp" />

</LinearLayout>

<LinearLayout

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:layout_alignParentRight="true"

android:layout_centerVertical="true"

android:orientation="horizontal" >

<RelativeLayout

android:layout_width="45dp"

android:layout_height="match_parent" >

<ImageView

android:id="@+id/refresh"

android:layout_width="45dp"

android:layout_height="match_parent"

android:layout_gravity="center_vertical"

android:background="@drawable/title_bar_image_pressed_effect"

android:paddingLeft="5dp"

android:paddingRight="5dp"

android:scaleType="centerInside"

android:src="@drawable/title_bar_refresh" />

<ProgressBar

android:id="@+id/refreshing"

android:layout_width="22dp"

android:layout_height="22dp"

android:layout_centerInParent="true"

android:visibility="gone" />

</RelativeLayout>

</LinearLayout>

</RelativeLayout>

<TextView

android:id="@+id/update_time"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="right"

android:layout_marginBottom="10dp"

android:layout_marginRight="10dp"

android:textColor="@color/white"

android:textSize="12sp" />

</LinearLayout>



<TextView

android:id="@+id/ptime"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:textColor="@color/white"/>



<TextView

android:id="@+id/txt_weather_temp"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:textColor="@color/white" />



<TextView

android:id="@+id/txt_weather_detail"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:textColor="@color/white" />



</LinearLayout>

还有很多地方可以改进,可以换一个获得天气信息较多的接口,并且对这些信息中有用的项都显示在xml文件中,可以采用ScrollView的方式进行显示,并且在UI上,可以根据不同的天气信息,设置不同的背景图片和天气图标,非常感谢那些前辈们,所以,虽然整个东西不多,分享一下,希望n年后对我的后辈们有所帮助
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐