Obtain data from the Internet and update the UI using sqlite in Android

Source: Internet
Author: User

Obtain data from the Internet and update the UI using sqlite in Android
Obtain data from the Internet and update the UI using sqlite in Android

Here, I mainly want to create
1. First retrieve data from the Internet
2. Store the obtained data locally.
3. The marker within the screen range is displayed on the map.
4. When the MAP status changes, query the local database and update the map.

BaiduMap has a setOnMapStatusChangeListener listener class that monitors the status of BaiduMap. There are three methods: onMapStatusChangeStart (), onMapStatusChangeFinish (), and onMapStatusChange ().

Void onMapStatusChangeStart (MapStatus status) gestures to operate the map, set the MAP status and other operations, resulting in the MAP status changes. Parameter: status-MAP status change starting with the MAP status change void onMapStatusChange (MapStatus status) parameter: status-current map status void onMapStatusChangeFinish (MapStatus status) MAP status change end parameter: status-MAP status after the MAP status changes

If the status of the BaiduMap changes, the corresponding function is called.

In fact, there is a stupid way, that is, every time the map state changes, it gets data from the server and then updates it to the map, but every time it is connected to the Internet, it needs to get data from the server, the sub-thread must be called every time, which consumes a lot of time and memory. Therefore, I want to directly obtain data from the server at one time and then store the data locally, when the MAP status changes, the data is retrieved from the local database and updated to the map. This saves time and memory.

But how do I transmit data obtained from the network in a child thread to the main thread? In fact, there is a method in the asynchronous thread to achieve this well. Let's briefly introduce the usage of asynchronous threads.

AsyncTask defines three generic types: Params, SS, and Result. Input parameters for Params startup task execution, such as the URL of the HTTP request. Percentage of Progress background tasks. Result: The Result returned when the task is executed in the background, such as String. AsyncTask defines several methods. 1. doInBackground (Params ...) The operations in the background can be put here. Note that you cannot directly operate the UI here. This method is executed in the background thread to complete the main work of the task, usually takes a long time. You can call publicProgress (Progress…) during execution ...) To update the task progress. 2. onPostExecute (Result) is equivalent to Handler's way of processing the UI. Here, you can use the Result processing operation UI obtained in doInBackground. This method is executed in the main thread. The task execution result is returned as a parameter of this method. In this example, the key is this method. 3. If necessary, You have to rewrite the following three methods, but not required: onProgressUpdate (Progress ...) You can use the progress bar to increase user experience. This method runs in the main thread to display the progress of the task execution. OnPreExecute () is the interface used by the end user to call Excute. This method is called before the task is executed. The progress dialog box is displayed here. OnCancelled () operations to be performed when a user cancels a call. 4. Use the AsyncTask class. The following guidelines must be followed: the Task instance must be created in the UI thread; the execute method must be called in the UI thread; Do not manually call onPreExecute (), onPostExecute (Result), doInBackground (Params ...), onProgressUpdate (Progress ...) these methods; the task can only be executed once; otherwise, exceptions may occur during multiple calls;

Next, let's take a look at what I want to write:

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. using data; import com. yds. newpowerbike. util. jsonParse; public class HomeFragment extends Fragment {private Activity activity; private MapView mMapView; public region myListener = new MyLocationListener (); private DBManager mgr; BaiduMap listener; LocationClient listener; 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); // database operation -- instantiate 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.exe cute ();} class asyncTask extends AsyncTask
  
   
{@ Override protected DBManager doInBackground (LatLng... params) {// TODO Auto-generated method stub // iml = new ConnectServerIml (); String url = response data. CHARGE_SEARCH; String result = iml. concernByClientGet (url); // ArrayList for json data parsing
   
    
List = JsonParse. search (result); // database operation-insert data mgr. add (list); return mgr;} @ Override protected void onPostExecute (final DBManager mgr) {// TODO Auto-generated method stub super. onPostExecute (mgr); final List
    
     
List = mgr. query (); mBaiduMap. setOnMapStatusChangeListener (new OnMapStatusChangeListener () {// before the map state changes, Marker marker; int length = list. size (); @ Override public void onMapStatusChangeStart (MapStatus status) {// TODO Auto-generated method stub} // After the MAP status changes @ Override public void onMapStatusChangeFinish (MapStatus status) {// TODO Auto-generated method stub LatLng mCenter = status.tar get; // database operation-Data Query For (int I = 0; I <length; I ++) {String pt = list. get (I ). poleFix; double lat = iml. getLat (pt); double lng = iml. getLng (pt); // the latitude and longitude of marker LatLng pt_ll = new LatLng (lat, lng); // obtain the distance between the marker and the circle center. Double distance = DistanceUtil. getDistance (pt_ll, mCenter); // The circle radius is 8000, Which is 7600 for the US. if (distance <7600) {BitmapDescriptor bitmap = BitmapDescriptorFactory is displayed when the distance is less than 7600. 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 onMa when the MAP status changes PStatusChange (MapStatus status) {// TODO Auto-generated method stub LatLng mCenter = status.tar get; mBaiduMap. clear (); // circle 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); // doub Le lng = iml. getLng (pt); // the latitude and longitude of marker // LatLng pt_ll = new LatLng (lat, lng); // obtain the distance between the marker and the circle center. // Double distance = DistanceUtil. getDistance (pt_ll, mCenter); // the radius of the circle is 8000. Here, the circle is 7600. The distance is less than 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; // locate related data MyLocationData locData = new MyLocationData. builder (). accuracy (location. getRadius ()). direction (100 ). latitude (location. getLatitude ()). longpolling (location. getlongpolling ()). build (); mBaiduMap. setMyLocationData (locData); if (isFirstLoc) {isFirstLoc = false; // positioning point coordinate LatLng ll = new LatLng (location. getLatitude (), location. getlongpolling (); // set the map center point and zoom level MapStatusUpdate u = MapStatusUpdateFactory. newLatLngZoom (ll, 12); // animated update map state, animation time 300 MS mBaiduMap. animateMapStatus (u); // circle 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; // close the database 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 ();}}
    
   
  

Here we have a map location, a map circle, a marker in the circle range, and Fragment, which can be seen in my previous blog. I will not go into details here.

DBHelper class:

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 // create the table db.exe cSQL ("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 // update TABLE db.exe cSQL ("alter table polepoint add column other STRING ");}}

DBManager class

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
     
      
List) {db. beginTransaction (); try {for (PolePoint pp: list) {db.exe cSQL ("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
      
       
Query () {ArrayList
       
        
List = new ArrayList
        
         
(); 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);} // close the cursor 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 class

Package com. yds. newpowerbike. bean; import java. io. Serializable;/*** {"PoleId": "consumer", "PoleAdress": "Does the consumer have dependencies? 97 Member Country names "," PoleState ": 0," PoleStyle ": 0," PoleFix ":" 30.884728, 121.01502099999999 "," PoleName ": "How many data items can I splash? "," UserId ":" null "}, * @ author Administrator * @ description parameter number cannot exceed limit (iii) cannot exceed limit? */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 ;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.