Android中sqlite之从网上获取数据更新UI
在这里,本人主要想做一个
1、首先从网上获取数据
2、将获取的数据存储到本地
3、地图上显示屏幕范围内的marker。
4、当地图状态改变时,要查询本地数据库,并更新地图。
BaiduMap有个setOnMapStatusChangeListener监听类,该类监听BaiduMap的状态,共有三个方法——onMapStatusChangeStart(),onMapStatusChangeFinish(),onMapStatusChange()。
void onMapStatusChangeStart(MapStatus status)
手势操作地图,设置地图状态等操作导致地图状态开始改变。
参数:
status - 地图状态改变开始时的地图状态
void onMapStatusChange(MapStatus status)
地图状态变化中
参数:
status - 当前地图状态
void onMapStatusChangeFinish(MapStatus status)
地图状态改变结束
参数:
status - 地图状态改变结束后的地图状态
若BaiduMap状态改变,就会调用相应的函数。
其实这里有个笨方法,那就是每次地图状态改变,就从服务器获取数据,然后更新到地图上,但这样每次都要联网从服务器端获取数据,而且每次都要调用子线程,非常耗时间和内存,所以,本人想直接一次从服务器端获取数据,然后存在本地,每次地图状态改变时直接从本地获取数据然后更新到地图上,这样就会节约时间与内存。
但,子线程中从网络上获取的数据,怎么传给主线程呢?其实异步线程中有个方法很好实现这点。我们先来简单介绍一下异步线程的用法。
AsyncTask定义了三种泛型类型 Params,Progress和Result。
Params 启动任务执行的输入参数,比如HTTP请求的URL。
Progress 后台任务执行的百分比。
Result 后台执行任务最终返回的结果,比如String。
AsyncTask定义了几个方法
1、doInBackground(Params…) 后台执行,比较耗时的操作都可以放在这里。注意这里不能直接操作UI。此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用publicProgress(Progress…)来更新任务的进度。
2、onPostExecute(Result) 相当于Handler 处理UI的方式,在这里面可以使用在doInBackground 得到的结果处理操作UI。 此方法在主线程执行,任务执行的结果作为此方法的参数返回,本例中关键是这个方法。
3、有必要的话你还得重写以下这三个方法,但不是必须的:
onProgressUpdate(Progress…) 可以使用进度条增加用户体验度。 此方法在主线程执 行,用于显示任务执行的进度。
onPreExecute() 这里是最终用户调用Excute时的接口,当任务执行之前开始调用此方法,可以在这里显示进度对话框。
onCancelled() 用户调用取消时,要做的操作
4、使用AsyncTask类,以下是几条必须遵守的准则:
Task的实例必须在UI thread中创建;
execute方法必须在UI thread中调用;
不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法;
该task只能被执行一次,否则多次调用时将会出现异常;
接下来,我们看看我想写的效果吧:
package com.yds.newpowerbike.fragment;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.os.AsyncTask;
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.ViewGroup;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.yds.newpowerbike.R;
import com.yds.newpowerbike.bean.PolePoint;
import com.yds.newpowerbike.db.DBManager;
import com.yds.newpowerbike.net.ConnectServerIml;
import com.yds.newpowerbike.net.ShareData;
import com.yds.newpowerbike.util.JsonParse;
public class HomeFragment extends Fragment {
private Activity activity;
private MapView mMapView;
public MyLocationListener myListener = new MyLocationListener();
private DBManager mgr;
BaiduMap mBaiduMap;
LocationClient mLocClient;
boolean isFirstLoc = true;
boolean isLocationClientStop = false;
ConnectServerIml iml;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreateView(inflater, container, savedInstanceState);
this.activity = getActivity();
SDKInitializer.initialize(activity.getApplicationContext());
return inflater.inflate(R.layout.fragment_home, container,false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
mMapView = (MapView) activity.findViewById(R.id.mapview);
mBaiduMap = mMapView.getMap();
mBaiduMap.setMyLocationEnabled(true);
//数据库操作——实例化DBManager
mgr = new DBManager(activity);
mLocClient = new LocationClient(activity);
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);
option.setCoorType("bd09ll");//bd09LL
option.setScanSpan(1000);
mLocClient.setLocOption(option);
mLocClient.start();
asyncTask task = new asyncTask();
task.execute();
}
class asyncTask extends AsyncTask<LatLng, Integer, DBManager>{
@Override
protected DBManager doInBackground(LatLng... params) {
// TODO Auto-generated method stub
//充电桩服务器查询
iml = new ConnectServerIml();
String url = ShareData.CHARGE_SEARCH;
String result = iml.ConcernByClientGet(url);
//json数据解析
ArrayList<PolePoint> list = JsonParse.search(result);
//数据库操作——插入数据
mgr.add(list);
return mgr;
}
@Override
protected void onPostExecute(final DBManager mgr) {
// TODO Auto-generated method stub
super.onPostExecute(mgr);
final List<PolePoint>list = mgr.query();
mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {
//地图状态改变前
Marker marker;
int length = list.size();
@Override
public void onMapStatusChangeStart(MapStatus status) {
// TODO Auto-generated method stub
}
//地图状态改变后
@Override
public void onMapStatusChangeFinish(MapStatus status) {
// TODO Auto-generated method stub
LatLng mCenter = status.target;
//数据库操作——数据查询
for (int i = 0; i < length; i++) {
String pt = list.get(i).PoleFix;
double lat = iml.getLat(pt);
double lng = iml.getLng(pt);
//marker的经纬度
LatLng pt_ll = new LatLng(lat, lng);
//获得marker与圆中心点之间的距离。
double distance = DistanceUtil.getDistance(pt_ll, mCenter);
//圆的半径是8000,这里为美观取7600,距离小于7600的显示
if(distance<7600){
BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
OverlayOptions options = new MarkerOptions()
.position(pt_ll)
.icon(bitmap)
.zIndex(14)
.draggable(true);
marker = (Marker) mBaiduMap.addOverlay(options);
}
}
}
//地图状态改变时
@Override
public void onMapStatusChange(MapStatus status) {
// TODO Auto-generated method stub
LatLng mCenter = status.target;
mBaiduMap.clear();
//画圆
OverlayOptions ooCircle = new CircleOptions().fillColor(0x384d73b3)
.center(mCenter).stroke(new Stroke(3, 0x784d73b3))
.radius(8000);
mBaiduMap.addOverlay(ooCircle);
// for (int i = 0; i < length; i++) {
// String pt = list.get(i).PoleFix;
// double lat = iml.getLat(pt);
// double lng = iml.getLng(pt);
// //marker的经纬度
// LatLng pt_ll = new LatLng(lat, lng);
// //获得marker与圆中心点之间的距离。
// double distance = DistanceUtil.getDistance(pt_ll, mCenter);
// //圆的半径是8000,这里为美观取7600,距离小于7600的显示
// if(distance<7600){
// BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
// OverlayOptions options = new MarkerOptions()
// .position(pt_ll)
// .icon(bitmap)
// .zIndex(14)
// .draggable(true);
//
// marker = (Marker) mBaiduMap.addOverlay(options);
//
// }
// }
}
});
}
}
public class MyLocationListener implements BDLocationListener{
@Override
public void onReceiveLocation(BDLocation location) {
// TODO Auto-generated method stub
if(location == null||isLocationClientStop)
return;
//定位相关数据
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
.direction(100)
.latitude(location.getLatitude())
.longitude(location.getLongitude())
.build();
mBaiduMap.setMyLocationData(locData);
if(isFirstLoc){
isFirstLoc = false;
//定位点坐标
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
//设置地图中心点和缩放级别
MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 12);
//以动画方式更新地图状态,动画耗时 300 ms
mBaiduMap.animateMapStatus(u);
//画圆
OverlayOptions ooCircle = new CircleOptions().fillColor(0x384d73b3)
.center(ll).stroke(new Stroke(3, 0x784d73b3))
.radius(8000);
mBaiduMap.addOverlay(ooCircle);
}
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
// mLocClient.stop();
// mBaiduMap.setMyLocationEnabled(false);
// mMapView = null;
//关闭数据库
mgr.closeDB();
mMapView.onDestroy();
super.onDestroy();
}
@Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
mMapView.onPause();
}
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
mMapView.onResume();
}
}
这里有地图定位,地图画圆,显示圆范围内的marker,还有Fragment,这些在我前面的博客中可以看到,这里就不详细讲了。
DBHelper类中:
package com.yds.newpowerbike.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "pole.db";
private static final int DATABASE_VERSION = 1;
public DBHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//创建表
db.execSQL("create table if not exists polepoint"+
"(_id integer primary key autoincrement,poleid varchar,poleaddress varchar,polename varchar,polefix varchar,userid varchar)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
//更新表
db.execSQL("ALTER TABLE polepoint ADD COLUMN other STRING");
}
}
DBManager类中
package com.yds.newpowerbike.db;
import java.util.ArrayList;
import java.util.List;
import com.yds.newpowerbike.bean.PolePoint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DBManager {
private DBHelper helper;
private SQLiteDatabase db;
public DBManager(Context context){
helper = new DBHelper(context);
db = helper.getWritableDatabase();
}
public void add(List<PolePoint> list){
db.beginTransaction();
try {
for (PolePoint pp:list) {
db.execSQL("insert into polepoint values(null,?,?,?,?,?)",new Object[]{pp.PoleId,pp.PoleAdress,pp.PoleName,pp.PoleFix,pp.UserId});
}
db.setTransactionSuccessful();
} catch (Exception e) {
// TODO: handle exception
}finally{
db.endTransaction();
}
}
// public void updatePoleAdress(PolePoint pp){
// ContentValues cv = new ContentValues();
// cv.put("PoleAdress", pp.PoleAdress);
// db.update("polepoint", cv, "polename = ?", new String[]{pp.PoleName});
// }
public List<PolePoint> query(){
ArrayList<PolePoint>list = new ArrayList<PolePoint>();
Cursor c = queryTheCursor();
while (c.moveToNext()) {
PolePoint pp = new PolePoint();
pp.PoleId = c.getString(c.getColumnIndex("poleid"));
pp.PoleAdress = c.getString(c.getColumnIndex("poleaddress"));
pp.PoleName = c.getString(c.getColumnIndex("polename"));
pp.PoleFix = c.getString(c.getColumnIndex("polefix"));
pp.UserId = c.getString(c.getColumnIndex("userid"));
list.add(pp);
}
//关闭游标
c.close();
return list;
}
public Cursor queryTheCursor(){
Cursor c = db.rawQuery("select * from polepoint", null);
return c;
}
public void closeDB(){
db.close();
}
// public void deleteOldPerson(PolePoint pp){
// db.delete("polepoint", "age>=?", new String[]{String.valueOf(person.age)});
//
// }
}
PolePoint类中
package com.yds.newpowerbike.bean;
import java.io.Serializable;
/**
* {
"PoleId": "003f3745-2032-4fa9-afe5-97afde42a89f",
"PoleAdress": "鏋附璺?97闄勮繎",
"PoleState": 0,
"PoleStyle": 0,
"PoleFix": "30.884728,121.01502099999999",
"PoleName": "鐢靛姩姹借溅鍏呯數妗?",
"UserId": "null"
},
* @author Administrator
* @description 鍏呯數妗╅噷闈㈢殑鐐?
*/
public class PolePoint implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public int _id;
public String PoleId;
public String PoleAdress;
public String PoleState;
public String PoleStyle;
public String PoleFix;
public String PoleName;
public String UserId;
public PolePoint(){
}
public PolePoint(String poleId,String poleAddress,String poleName,String poleFix,String userId){
this.PoleId = poleId;
this.PoleAdress = poleAddress;
this.PoleName = poleName;
this.PoleFix = poleFix;
this.UserId = userId;
}
public String getPoleId() {
return PoleId;
}
public void setPoleId(String poleId) {
PoleId = poleId;
}
public String getPoleAdress() {
return PoleAdress;
}
public void setPoleAdress(String poleAdress) {
PoleAdress = poleAdress;
}
public String getPoleState() {
return PoleState;
}
public void setPoleState(String poleState) {
PoleState = poleState;
}
public String getPoleStyle() {
return PoleStyle;
}
public void setPoleStyle(String poleStyle) {
PoleStyle = poleStyle;
}
public String getPoleFix() {
return PoleFix;
}
public void setPoleFix(String poleFix) {
PoleFix = poleFix;
}
public String getPoleName() {
return PoleName;
}
public void setPoleName(String poleName) {
PoleName = poleName;
}
public String getUserId() {
return UserId;
}
public void setUserId(String userId) {
UserId = userId;
}
}
截图:
时间: 2024-10-20 00:14:53