package com.qiyou.mb.android.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.beans.Statistics;
import com.qiyou.mb.android.beans.Track;
import com.qiyou.mb.android.beans.basic.CItem;
import com.qiyou.mb.android.beans.basic.GPItem;
import com.qiyou.mb.android.beans.basic.StatTrack;
import com.qiyou.mb.android.beans.basic.Statics_bean;
import com.qiyou.mb.android.beans.basic.Track_bean;
import com.qiyou.mb.android.beans.basic.TypeStatistics;
import com.qiyou.mb.android.beans.basic.Waypoint;
import com.qiyou.mb.android.beans.basic.Waypoint_bean;
import com.qiyou.mb.android.content_providers.TrackProvider;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.enums.TrackAvStatus;
import com.qiyou.mb.android.utils.enums.TrackStatus;
import com.qiyou.mb.android.utils.enums.TrackType;
import com.qiyou.mb.android.utils.log.QLog;
 

public class TrackDbServiceBackground extends DBservice {
	public static String TAG ="com.qiyou.TrackDbServiceBackground"; 
	
//private final String  WHERE_TRACK_AV_STATUS = " ( ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")!="  +TrackAvStatus.DELETED   +
//		" OR " + TrackProvider.KEY_TRACK_AVSTATUS+" != "+TrackAvStatus.DELETED +")";
//private final String  WHERE_TRACK_AV_STATUS_NOT_DELETED = " ( ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")="  +TrackAvStatus.DELETED   +
//" OR " + TrackProvider.KEY_TRACK_AVSTATUS+" != "+TrackAvStatus.DELETED +")";

private final String  WHERE_TRACK_AV_STATUS =    TrackProvider.KEY_TRACK_AVSTATUS+" != " + TrackAvStatus.DELETED ;
private final String  WHERE_TRACK_AV_STATUS_NOT_DELETED =   TrackProvider.KEY_TRACK_AVSTATUS+" != "+TrackAvStatus.DELETED  ;

private final String  WHERE_TYPE_NO_GPX=" and " +TrackProvider.KEY_TRACK_TYPE +"!="+TrackType.GPX; 
	 
public TrackDbServiceBackground()
	{
	 super(TAG);
	}
	public TrackDbServiceBackground(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}
 
	 @Override
	  public void onCreate() {
	    super.onCreate();
	     QLog.getLogger().d(dTAG, TAG+" db service created");
	  }
	 
	
 	String[] newWps =new String[3] ;
	@Override
	protected void onHandleIntent(Intent intent) {
		  QLog.getLogger().d(dTAG, TAG+" start to check intent keys....");
		 Bundle bd= intent.getExtras();
		 for(String key:bd.keySet()){
			 QLog.getLogger().d(dTAG, TAG+" get key of " +key); 
			 
		 } 
		 
		 
//	    }
	// 	
//		@Override
//		protected void onHandleIntent(Intent intent) {		
	 		if(intent==null)return;
			 long bfdbTime = System.currentTimeMillis();
			 
			 
			   Bundle extras = intent.getExtras();
			   String key;
			    //锟斤拷录锟剿讹拷锟届迹
			    key = QiYouConstant.NEW_LOCATION;		   //recording new waypoints
			    if (intent.hasExtra(key) ) {
//			    	StringBuilder wps =new StringBuilder();
			    	
			    	if(app.isRestoreLastTracking &&app.getRecordingTrack().getTrackBean().getTrackId()==0)return;
			    	if ( app.getRecordingTrack().getTrackBean().getStatus() !=TrackStatus.RECORDING)return;
			    	String rdWps  ; 
			    		@SuppressWarnings("unchecked")
						ArrayList<String> locLst =  (ArrayList<String>)extras.get(key) ;
			    	 if(locLst!=null && locLst.size()>0){
			    		 boolean setLastWpSucceed=false;
			    		 int i = 0;		    		 
			    	    StringBuilder wps =new StringBuilder();
//			    		 QLog.getLogger().d(TAG,"---------------New wps insert db...........................");
			    		for(String wp :locLst)
			    		{
			    			//Log.e(TAG ,wp);
			    		//	app.getRecordingTrack().setLastWp(wp);
			    			if(app.getRecordingTrack().setLastWp(wp)){
			    			/*	wps.append(wp);
 			    				wps.append(",");*/
			    				setLastWpSucceed =true; 
//			    				QLog.getLogger().d(TAG,"new wp:" +wp);
			    			}
			    					
//			    			setLastWpSucceed =app.getRecordingTrack().setLastWp(wp)||setLastWpSucceed;//|| app.getRecordingTrack().setLastWp(wp); //add last wp into list of track.track_bean.trkseg.
			    			
			    		}
 
			    		if (!app.canRecord()&& !QiYouConstant.DEVELOPER_MODE) return; 
			    		
			    		rdWps = app.getRecordingTrack().getRdWpsJson().toString();
					    if(setLastWpSucceed){
//					    	newWps = buildWps(wps.toString(),rdWps,app.getRecordingTrack().newMdWpsJson.toString());
					    	newWps = buildWps(wps.toString(),"",app.getRecordingTrack().newMdWpsJson.toString());
//					    	newWps = buildWps(wps.toString(),"','","','");
					    	persistTrack(app.getRecordingTrack() );  
//					    	QLog.getLogger().d(dTAG,TAG+"    wps size: "+ i +" , addNewWayPoints spend time " +String.valueOf((System.currentTimeMillis()-bfdbTime)) );
						    
					    }
					    
					  
	 		            
														     
					}
			     return;
			    }
			    
			    
			    key = QiYouConstant.NEW_GPX_TRACK;   
			    
			    if (intent.hasExtra(key) ) {
			    	
			    	if(app.getImportedGpx().size()==0)return;
			    	
			    	for(Track tr:app.getImportedGpx()){ 
			    		if(tr==null)continue;
			    		if(tr.getTrackBean().getTrackId()>0)continue;
			    		
			    		// QLog.getLogger().d(dTAG,TAG+" "+ " Begin to insert new Gpx to db " );
			    		
//			    		newWps[0] =tr.getJsonWps().toString();
				    	if(tr.getTrackBean().getRoadWps().size()>0){
				    		tr.setBearWps(tr.getTrackBean().getRoadWps());
				    	}
				    	
				    	// QLog.getLogger().d(dTAG,TAG+" "+ " =tr.getRdWpsJson() " +tr.getRdWpsJson() );
				    	
				    	newWps[1] =tr.getRdWpsJson().toString();	
//				    	newWps[2] =tr.newMdWpsJson.toString();
				    	newWps[2] =Utils.getGsonString(tr.getTrackBean().getMdWps());
				    	persistTrack(tr);   
				    	
				    	/* for(Waypoint_bean wb1:tr.getTrackBean().getRoadWps()){
								 
								 QLog.getLogger().d(dTAG,  "4 cust wp  turn flag" + wb1.getTurnFlag().toCHString());
							} */
			    	}
			    	
			        newWps =new String[3];
			    	return;
			    }
			    
			    
			    key = QiYouConstant.INITIAL_GPXS;   
			    
			    if (intent.hasExtra(key) ) {
			    	
			    	ArrayList<Integer> ids =app.getGpxShowingTracks();
			    	for(int i:ids){
			    		if(i>0)
			    			this.getTrack(String.valueOf(i));
			    	}
			    	
			    	return;
			    }
			    
			    key = QiYouConstant.UPDATE_CATE_TRACK;   
			    
			    if (intent.hasExtra(key) ) {
			     
			    	HashMap<Integer,ArrayList<String>> ids =app.getNewCategoryList();
//			    	QLog.getLogger().d(dTAG,  TAG+" begin to add new cates,   app.getNewCategoryList().size()  "+ids.size());
			    	 if(ids.size()>0){
			    		 this.addNewCateTrack(ids);
			    	 }
			    	 
			    	 ids =app.getDelCategoryList(); 
			    	 if(ids.size()>0){
			    		 this.delCateTrack(ids);
			    	 }
			    	
			    	return;
			    }
			    
		       key = QiYouConstant.UPDATE_TRACK_AVSTATUS;   
			    
			    
			    	if (intent.hasExtra(key)) {
//				    	if (!app.canRecord()) return; 
//				    	int id ;//=  extras.getInt(key); 
				    	Object obj = extras.get(key); 
				    	int id =obj==null?0:Integer.parseInt(obj.toString());
//				      if(id ==app.getRecordingTrack().getTrackBean().getTrackId()){	
//				    	  updateTrackAvStatus(app.getRecordingTrack() );
//						  app.getTrackCache().put(app.getRecordingTrack().getTrackBean().getTrackId(), app.getRecordingTrack()); //update the cache
//						  return;  
//				      }
				    	
				    	  
				      if(id ==app.getCurrentTrack().getTrackBean().getTrackId()){	
				    	  updateTrackAvStatus(app.getCurrentTrack());
					      app.getTrackCache().put(app.getCurrentTrack().getTrackBean().getTrackId(), app.getCurrentTrack()); //update the cache
				      }
			    	 
			    	return;
			    }
			    
			    
			    
			    
			    
			    
			    
			    key = QiYouConstant.EXTRA_KEY_FORCE_UPDATE;   
			    if (intent.hasExtra(key)) {
			    	if (!app.canRecord()) return;  
			    	if(app.getRecordingTrack().getTrackBean().getTrackId()>0 && 
			    			app.getRecordingTrack().getTrackBean().getStatus()==TrackStatus.RECORDING) {
				    	app.getRecordingTrack().getTrackBean().setOffTime(app.getRecordingTrack().getTrackBean().getOffTime()+app.offtime);
//				    	app.getRecordingTrack().getTrackBean().setPauseTime(app.getRecordingTrack().getTrackBean().getPauseTime()+app.sumPaused);
//				    	QLog.getLogger().d(dTAG,  TAG+"   MergeTrack: ForceUpdate sportTime:?" +  Utils.getTimeCnt( app.getRecordingTrack().getTrackBean().getPauseTime() ));
//				    	QLog.getLogger().d(dTAG,  TAG+"   MergeTrack: ForceUpdate   offTime:?" +  Utils.getTimeCnt( app.getRecordingTrack().getTrackBean().getOffTime() ));
				    	
				    	/*long endTime =app.getRecordingTrack().getTrackBean().getLastWp().getWb().getTime();
				    	endTime =System.currentTimeMillis() >endTime?System.currentTimeMillis():endTime+app.offtime+app.sumPaused; //in case,the phone's time is reset to 1970...
				    	app.getRecordingTrack().getTrackBean().setEndTime(endTime);
				     	*/
				    	app.getRecordingTrack().getCalBurn();//calculate calories 
				    	
				    	updateTrack(app.getRecordingTrack(),null);
				        app.getTrackCache().put(app.getRecordingTrack().getTrackBean().getTrackId(), app.getRecordingTrack()); //update the cache
				      
 	}
				    	app.offtime =0;
//				    	app.sumPaused=0;
//				    	app.getStatisticsTrack(app.getRecordingTrack().getTrackBean().getType().toInt());
				    	return;
				    } 
			    
			   /* key = QiYouConstant.EXTRA_KEY_FORCE_UPDATE_STAT;   
			    if (intent.hasExtra(key)) {
//			     	if(app.isUIactive)
			     		getStatisticTracks(100,System.currentTimeMillis(),app.getRecordingTrack().getTrackBean().getType().toInt(),true);  //update the statics
			     	return;
			    }*/
			    
//			    key = QiYouConstant.QUERY_TRACKS;  
			    
			    //update the current track, for finishing a record,will include the updated roadbears of maxR wp the lastwp.
			    key = QiYouConstant.UPDATE_TRACK;	    	    
			    if (intent.hasExtra(key)) {
//			    	if (!app.canRecord()) return; 
//			    	int id ;//=  extras.getInt(key); 
			    	Object obj = extras.get(key);
			    	int id =obj==null?0:Integer.parseInt(obj.toString());
			      if(id ==app.getRecordingTrack().getTrackBean().getTrackId()){	
					      updateTrack(app.getRecordingTrack() ,null);
					      app.getTrackCache().put(app.getRecordingTrack().getTrackBean().getTrackId(), app.getRecordingTrack()); //update the cache
					      return;  
			      }

                  Track tr= app.getTrackCache().get(Integer.valueOf(id));
			      if(tr==null)return;
			       updateTrack(tr,tr.getTrackBean().getType()==TrackType.GPX?tr.getRdWpsJson().toString():null);
			       app.getTrackCache().put(id,tr); //update the cache
//			       app.currentTrack= app.getTrackCache().get(Integer.valueOf(app.getCurrentTrack().getTrackBean().getTrackId()));
			       app.setCurrentTrack(app.getTrackCache().get(Integer.valueOf(app.getCurrentTrack().getTrackBean().getTrackId())));
			       // QLog.getLogger().dLog(dTAG,TAG+" updated track, to merge statistics......");
			       app.mStatistics.mergeTrack(tr); 
//			       app.mStatistics.getStatisticsTracks().get(Integer.valueOf(tr.getTrackBean().getType().toInt())).getSbs().put(Integer.valueOf(id), new Statics_bean(tr.getTrackBean()));
			      
			    /*  if(id ==app.getCurrentTrack().getTrackBean().getTrackId()){	
				      updateTrack(app.getCurrentTrack(),null);
				      app.getTrackCache().put(app.getCurrentTrack().getTrackBean().getTrackId(), app.getCurrentTrack()); //update the cache
				      return;
			      }*/
			     
			     
//			      QLog.getLogger().d(dTAG,TAG+" Current Track UPDATE done.");
			      return;
			    } 
			     
			    
			    key = QiYouConstant.EXTR_KEY_FINISH_RECORDING; 
			    if (intent.hasExtra(key)) {
//			    	if (!app.canRecord()) return;  //as it is for finish current recording, to skip the iscnareocord. 
//			    	int id ;//=  extras.getInt(key); 
			    	Object obj = extras.get(key);
			    	int id =obj==null?0:Integer.parseInt(obj.toString());
			      if(id ==app.getCurrentTrack().getTrackBean().getTrackId()){	 
				      updateTrack(app.getCurrentTrack(),app.getCurrentTrack().getRdWpsJson().toString());
				      app.getTrackCache().put(app.getCurrentTrack().getTrackBean().getTrackId(), app.getCurrentTrack()); //update the cache
			      }
//			   	QLog.getLogger().d(dTAG,TAG+" Current Track UPDATE done.");
			      return;
			    } 
			    
			    key = QiYouConstant.UPDATE_RECORDING_TRACK;	    //UDPATE TRACK STATUS	    
			    if (intent.hasExtra(key)) {
			    	if (!app.canRecord()) return; 
//			    	int id =  extras.getInt(key); 
			    	Object obj = extras.get(key);
			    	int id =obj==null?0:Integer.parseInt(obj.toString());
			    	 if(id ==app.getRecordingTrack().getTrackBean().getTrackId()){	
				     	app.getRecordingTrack().getTrackBean().setOffTime(app.getRecordingTrack().getTrackBean().getOffTime()+app.offtime);
				    	app.getRecordingTrack().getTrackBean().setPauseTime(app.getRecordingTrack().getTrackBean().getPauseTime()+app.sumPaused);		    
				    	updateTrack(app.getRecordingTrack(),null);
				    	app.offtime =0;
				    	app.sumPaused=0;
			    	 }
//			      	QLog.getLogger().d(dTAG,TAG+" UPDATE RECORDING TRACK. UPDATE done.");
			      return;
	 		    } 
			 
			    key =QiYouConstant.EXTRA_KEY_TRACK_GEOS;
			    if (intent.hasExtra(key)) {
//			    	HashMap<Integer,String[]> geoWps = (HashMap<Integer, String[]>) intent.getExtras().getSerializable(key);
			    	
			    	// QLog.getLogger().d(dTAG,TAG+" GET KEY EXTRA_KEY_TRACK_GEOS");
			    	if(app.geoWps!=null){
			    		
			    		 for(int trackId :app.geoWps.keySet()){
			    		     // QLog.getLogger().d(dTAG,TAG+" TO UPDATE GEO DATA...");
			    			 updateWpsGEO(trackId,app.geoWps.get(trackId)); 
			    			 // QLog.getLogger().d(dTAG,TAG+"UPDATE GEO DATA... DONE");
			                }
			    		 
			    	}
			    	app.geoWps=null;
			    	QiYouConstant.IS_PROCESSING_GEO_FOOTMARK =false;
//			    	 // QLog.getLogger().d(dTAG, TAG+" app.geoWps.size():"+app.geoWps.size()  );
				    return;
			    }
			     
			    key = QiYouConstant.EXTRA_KEY_GET_CURRENT_TRACK_BY_ID;
		    	
			    //get specified track by id
			    if (intent.hasExtra(key)) {
			    	String id = extras.get(key).toString();// intent.getStringExtra(key);
			    	
//			    	if(QiYouConstant.DEVELOPER_MODE)	bfdbTime = System.currentTimeMillis();
			    	
			    	 getTrack(id); 
			    	 
 			    	 // QLog.getLogger().d(dTAG,TAG+"   fetch track " +  id  + "cost time: "+ String.valueOf((System.currentTimeMillis()-bfdbTime)));
			    	 
			    	/* if(QiYouConstant.DEVELOPER_MODE)
			    	{ 
			        	 Log.e(TAG+"  锟斤拷取track " +  id  + "锟斤拷锟狡猴拷时: ",String.valueOf((System.currentTimeMillis()-bfdbTime)) + "锟斤拷锟斤拷");
				    	// Log.e(TAG + "Current Track GJson String is:",app.getCurrentTrack().toGsonString());
			    	}*/
//			    	 stopSelf(); 
			    }

		 
			    
			    //get statistics Tracks
			    key = QiYouConstant.EXTRA_KEY_GET_STSTICS_TRACKS;
			    if (intent.hasExtra(key)   ) { 
//			    	QLog.getLogger().d(dTAG, TAG+ "--------------- get statistics begin at: "+(System.currentTimeMillis()));

/*			    	if(app.statTrackLoading)return;
			    	app.statTrackLoading=true;*/
			    	long start=100;
			    	long end= System.currentTimeMillis();
//			    	int type =QiYouConstant.TRACK_TYPE_BIKE;
			    	int type =Integer.valueOf(extras.get(key).toString());   
//			    	app.TypeStatistics = getStatisticTracks(start,end,type);
			    	if(app.mStatistics==null ||app.mStatistics.getStatisticsTracks()==null && type>=0){  //to get all type's stat..
			    		type=-100;
			    	}
			    	initialStatistics(start,end,type,false);
			    	/*if(type==-100)
			    		app.mStatistics=new Statistics(); 
			    	
			       	getStatisticTracks(start,end,type,false); 
			       	getTypeUsedList();
			       	getLastStatisticsTrack(QiYouConstant.TRACK_NUMBERS_IN_STATISTICS_CHART+1);
			       	getCateTrackList();
			       	app.statTrackLoading=false;*/
			       	// QLog.getLogger().d(dTAG, TAG+ "--------------- get statistics cost time: "+(System.currentTimeMillis()-end));
			        stopSelf(); 
//			       	return;
			    }
			    
			    
			    
			    key = QiYouConstant.EXTRA_KEY_UPDATE_WAYPOINTS;	    	    
			    if (intent.hasExtra(key)) {
//			    	if (!app.canRecord()) return; 
//			    	int id ;//=  extras.getInt(key); 
			    	Object obj = extras.get(key);
			    	boolean isMd=extras.getBoolean(QiYouConstant.EXTRA_KEY_IS_MD);
			    	int id =obj==null?0:Integer.parseInt(obj.toString());
			    	
			      if(id ==app.getRecordingTrack().getTrackBean().getTrackId()){	
			    	  	  updateWps(app.getRecordingTrack() ,isMd);
//					      app.getTrackCache().put(app.getRecordingTrack().getTrackBean().getTrackId(), app.getRecordingTrack()); //update the cache
					      return;  
			      }
			    	  
			      if(id ==app.getCurrentTrack().getTrackBean().getTrackId()){	
			    	  updateWps(app.getCurrentTrack() ,isMd);
//				      app.getTrackCache().put(app.getCurrentTrack().getTrackBean().getTrackId(), app.getCurrentTrack()); //update the cache
			      }
//			   	QLog.getLogger().d(dTAG,TAG+" wp comments UPDATE done.");
			      return;
			    }
			    
			    key = QiYouConstant.EXTRA_KEY_UPDATE_SVRNOS;	    	    
			    if (intent.hasExtra(key)) {
			    	HashMap<Integer,Integer>ids =  (HashMap<Integer,Integer>) extras.getSerializable(key);			    	
			        updateTrackSvrNo(ids);
			        return;
			    }
			    // to update medias after the upload to web.
			    key = QiYouConstant.EXTRA_KEY_UPDATE_MEDIAS;	    	    
			    if (intent.hasExtra(key)) {
			    	Object obj = extras.get(QiYouConstant.EXTRA_KEY_ID); 
			    	int id =obj==null?0:Integer.parseInt(obj.toString());
			    
			    	String mdstr=extras.getString(QiYouConstant.EXTRA_KEY_UPDATE_MEDIAS); 
			    	// QLog.getLogger().d(dTAG,TAG+" ------------>>>>>>------to update md ------------------" );
			    	// QLog.getLogger().d(dTAG,TAG + "  "+ mdstr);
					ContentValues values = new ContentValues();  
					values.put(TrackProvider.KEY_TRACK_MDWPS,mdstr); 
					updateTable(TrackProvider.TRACKS_URI,values, id,null);	
					return; 
			    }
//				    app.getTrackCache().put(tb.getTrackId(), tr);
			    	
			    	/*QLog.getLogger().d(dTAG,TAG+" begin to get track of " + id);
			    	Track track= getTrack( id ); 
			    	Media tmd =(Media) Utils.getGsonObject(mdstr, Media.class);	 
			    	QLog.getLogger().d(dTAG,TAG+" to update md:" +mdstr);
			    	String  value = track.wps2json(track.getTrackBean().getMdWps());
			    	
			    	QLog.getLogger().d(dTAG,TAG+" ......old value:" +value);
			    	
				   	 for(Waypoint_bean wb:track.getTrackBean().getMdWps()){
						 if(wb==null)continue;
						 for(Media md:wb.getMedias()){
							 if(md!=null && md.getUri().equalsIgnoreCase(tmd.getUri())){
								 md.setComment(tmd.getComment());
								 md.setStatus(tmd.getStatus());
								 md.setSvrUri(tmd.getSvrUri()); 
								 updateWps(track ,true); 
							 }
							 
						 }
					 }
				    value = track.wps2json(track.getTrackBean().getMdWps());
			    	
			    	QLog.getLogger().d(dTAG,TAG+" ......new value:" +value);
			    	return;
			    	}*/
			   
			    
			    
			    
			    
			    
		}
	
  private void initialStatistics(long start,long end,int type,boolean isForceUpdate){
	    app.statTrackLoading=true;
		/*if(type==-100)
    		app.mStatistics=new Statistics();*/
	 	getStatisticTracks(start,end,type,false); 
       	getTypeUsedList();
       	getGpList();
       	getLastStatisticsTrack(QiYouConstant.TRACK_NUMBERS_IN_STATISTICS_CHART+1);
       	getCateTrackList();
       	app.statTrackLoading=false;
        app.writeStatiscs();
        String tableName ="TRACKS";
         // QLog.getLogger().d(dTAG, TAG+" before update , getCurrentSeq( ) " +getCurrentSeq("TRACKS"));
        // QLog.getLogger().d(dTAG, TAG+" app.mStatistics.getLastTrackId() " +app.mStatistics.getLastTrackId());
        if(getCurrentSeq(tableName)==-1){
        	 insertSeqId(tableName, app.mStatistics.getLastTrackId());
        }else if(getCurrentSeq("TRACKS")<app.mStatistics.getLastTrackId()){
        	updateSeqId("TRACKS",app.mStatistics.getLastTrackId());
        }
        // QLog.getLogger().d(dTAG, TAG+" after update ,getCurrentSeq( ) " +getCurrentSeq("TRACKS"));
  }
	
	String[] buildWps(String newWps,String rdWps,String mdWps){
		String[]  wps = new String[3] ;
		wps[0] =newWps;
    	wps[1] =rdWps;
    	wps[2] =mdWps;
    	if(!TextUtils.isEmpty(rdWps))app.getRecordingTrack().setRdWpsJson(new StringBuffer());//clear rdbears
    	if(!TextUtils.isEmpty(mdWps))app.getRecordingTrack().newMdWpsJson =new StringBuffer();
//    	QLog.getLogger().d(dTAG,TAG +"build wps, mdWps : " +mdWps);
    	return wps;
	}
	
	/*
	 * add/update current track wps to db
	 */	
	protected void persistTrack(Track tr)
	{ 
		Track_bean tb =tr.getTrackBean();
//		  app.saveLocationParameters(false);
//		long bfdbTime = System.currentTimeMillis();
//		QLog.getLogger().d(dTAG,TAG+" "+ "Start to add new wp");		 
		 ContentValues values = new ContentValues();
		 int trackId= tb.getTrackId();		 
		  tb.setLastdbTime(System.currentTimeMillis());																			 
  	 		 values.put(TrackProvider.KEY_ID, trackId); 
  	 		 values.put(TrackProvider.KEY_TRACK_LAST_WP, tr.getLastJsonWp()); 
  	 	     values.put(TrackProvider.KEY_TRACK_DISTANCE, tb.getDistance());
		     values.put(TrackProvider.KEY_TRACK_END_TIME, tb.getEndTime());
		     values.put(TrackProvider.KEY_TRACK_PAUSE_TIME, tb.getPauseTime());
			 values.put(TrackProvider.KEY_TRACK_SPORT_TIME, tb.getSportTime());
			 values.put(TrackProvider.KEY_TRACK_EUP_DIST, tb.geteUpDist());
			 values.put(TrackProvider.KEY_TRACK_EDOWN_DIST, tb.geteDownDist());
			 values.put(TrackProvider.KEY_TRACK_TOPSPEED, tb.getTopSpeed());
			 values.put(TrackProvider.KEY_LAST_UPDATE_TIME, System.currentTimeMillis());
			 values.put(TrackProvider.KEY_TRACK_END_TIME, tb.getEndTime());
			 values.put(TrackProvider.KEY_TRACK_OFFTIME, tb.getOffTime());
			 values.put(TrackProvider.KEY_TRACK_MAXRD_WP, tr.getMaxRdistWpJson());
			 values.put(TrackProvider.KEY_TRACK_MAXRD, tb.getMaxR());
			 values.put(TrackProvider.KEY_TRACK_GEO_STATUS,1);//when new values of road wp,update the geo status to have a value bigger than zeo
			 
      	 	 if(trackId ==0 )  //new track 
      	 	 {
//      	 		QLog.getLogger().d(dTAG,TAG+" "+ " begin to Add  new track with type: " + tb.getType());
//      	 		values.put(TrackProvider.KEY_TRACK_CONTENT, newWps.toString()); //Yeah....Duplicated wps in the db has been fixed! set it to not null when insert, then will be updated with: oldvalue = oldvalue || newvalue;
      	 		 
      	 	    values.put(TrackProvider.KEY_TRACK_CONTENT,newWps[0]);  
      	 	    
      	 		values.put(TrackProvider.KEY_TRACK_ROAD_BEARS, newWps[1]);//",");
      	 		
      	 		values.put(TrackProvider.KEY_TRACK_MDWPS, newWps[2]);//",");
      	 	    values.put(TrackProvider.KEY_TRACK_GPSSPAN, tb.getGpsSpan());
 			    values.put(TrackProvider.KEY_TRACK_NAME, tb.getName());
			    values.put(TrackProvider.KEY_TRACK_COMMENT, tb.getComment());
			    values.put(TrackProvider.KEY_TRACK_DESC, tb.getDescription()); 
	 		    values.put(TrackProvider.KEY_TRACK_START_WP, tr.getStartJsonWp());  
//	 		    values.put(TrackProvider.KEY_TRACK_SPORT_TIME, 0);
	 		    values.put(TrackProvider.KEY_TRACK_OFFTIME, 0);
	 		    values.put(TrackProvider.KEY_TRACK_PAUSE_TIME, 0);
//	 		    Log.e(dTAG,TAG+"addNewWayPoints(), KEY_TRACK_START_WP is" + app.getRecordingTrack().getStartJsonWp());
//	 		    Log.e(dTAG,TAG+"addNewWayPoints(), newWps is" + newWps.toString());
//	 		    Log.e(dTAG,TAG+"addNewWayPoints(), rdWps is" + rdWps );
	 		   
			    values.put(TrackProvider.KEY_TRACK_IS_SETS, tb.getIsCheckedIn()); 
			    values.put(TrackProvider.KEY_TRACK_START_TIME, tb.getStartTime());
			    values.put(TrackProvider.KEY_TRACK_USER_ID, tb.getUserid()); 
//			    values.put(TrackProvider.KEY_TRACK_USER_ID, QiYouConstant.PV_USER_ID); 
			    values.put(TrackProvider.KEY_TRACK_STATUS, tb.getStatus().toInt());  
			    values.put(TrackProvider.KEY_TRACK_TYPE, tb.getType().toString());
			    values.put(TrackProvider.KEY_TRACK_CREATOR, tb.getCreator());
			    values.put(TrackProvider.KEY_TRACK_SRC, tb.getSrc());
			    values.put(TrackProvider.KEY_TRACK_AVSTATUS, tb.getAvStatus().toInt()); 
			    values.put(TrackProvider.KEY_TRACK_CREATE_TIME, tb.getCreatTime());
			    values.put(TrackProvider.KEY_SVR_NUMBER, tb.getSvrNumber());
			   
              /*  for(String key :values.keySet())
                {
                	QLog.getLogger().d(dTAG,TAG+"  "+ key +" : "+ values.getAsString(key));
                }
               */
      	 	 }
//      		 if(tb.getType()!=TrackType.GPX)//it is merging recordingtrack.  // it is in timetick service, on each minute to update.
//      			 app.updateStatistics();
      	 	 
		    // Update or add the new place to the TrackProvider
//		    String where = TrackProvider.KEY_ID + " = '" + trackId + "'";
//		    QLog.getLogger().d(dTAG,TAG+" "+ " where is " + where);
		    Uri uri = Uri.withAppendedPath(TrackProvider.TRACKS_URI, String.valueOf(trackId));
		    try {   
 		    	
//		      if (trackId ==0 ||  contentResolver.update(TrackProvider.CONTENT_URI, values, where, null) == 0) {
//		        if (trackId ==0 ||  contentResolver.update(uri, values, null, new String[]{newWps.toString(),rdWps}) == 0) {
		    	 if (trackId ==0 ||  contentResolver.update(uri, values, null, newWps) == 0) {
		    	   
		    		 if(tb.getType()!=TrackType.GPX && !app.isLastTrackExist() ){
		    			 QLog.getLogger().dLog(dTAG,TAG+" "+ " no available recording track......return.....");
		    			 if(!(app.playBack && QiYouConstant.PLAYBACK_CAN_RECORD)){
		    				 return;
		    			 }
		    		 }
		    			 
		    		 if(values.containsKey(TrackProvider.KEY_ID)) values.remove(TrackProvider.KEY_ID); // new track , leave key_id blank.  
		    	    
		    	    uri =contentResolver.insert(TrackProvider.TRACKS_URI, values);
		    	   
		    	  
		    	  if(uri !=null){ 
		    	  
		    		 try{
		    			 	 
		    			 tb.setTrackId(Integer.valueOf(uri.getPathSegments().get(1))); 
		    			 if(tb.getType()==TrackType.GPX){ 
		    				  if(app.mStatistics!=null && !app.statTrackLoading) {  //gpx won't be calculated in statistics
		    					 app.getTrackCache().put(tb.getTrackId(), tr);
		    					 app.mStatistics.mergeTrack(tr); 
		    					 
		    				 } 
		    			 }else{
		    				 app.setLastRecordingIdStartTime();
		    				 if(QiYouConstant.PV_INT_SPORTS_SPEAK_MODEL<2)
		    						app.speech("卫星定位成功，记录开始",0);
		    			 }
		    			  
//		    			 getStatisticTracks(100,System.currentTimeMillis(),tb.getType().toInt(),true);  //update the statics
//		    			 app.updateStatistics();
		    			  
		    			 // QLog.getLogger().dLog(dTAG," Added new track with ID " + uri.getPathSegments().get(1));
		    		 }catch(Exception e)
		    		 {
		    			 Utils.logStackTrace(e, dTAG);
		    		 }
		    	 } 
		           
		      } 
		    	  tr.saveContent();
		    	  tr.saveBearContent();
		    	 
	    	  
		    }
		    catch (Exception er) {  
		      Utils.logStackTrace(er, dTAG);
		    }
		    
		  																				     
	}
	
	/*
	 * update  track,no normal wps will be updated, roadwps, mdwps can be updated.
	 */
	protected void updateTrack(Track tr,String roadBears)
	{
//		app.saveLocationParameters(false);
		
//		int trackId= tb.getTrackId();		 
		Track_bean tb =tr.getTrackBean();
		ContentValues values = new ContentValues(); 
		String [] wps=null;
				tb.setLastdbTime(System.currentTimeMillis()) ;
//      	 		values.put(TrackProvider.KEY_ID, trackId); 
      	 	    values.put(TrackProvider.KEY_TRACK_NAME, tb.getName());
			    values.put(TrackProvider.KEY_TRACK_COMMENT, tb.getComment());
			    values.put(TrackProvider.KEY_TRACK_DESC, tb.getDescription());  
			    values.put(TrackProvider.KEY_TRACK_IS_SETS, tb.getIsCheckedIn()); 
			    values.put(TrackProvider.KEY_LAST_UPDATE_TIME, tb.getLastdbTime());
			    values.put(TrackProvider.KEY_TRACK_STATUS, tb.getStatus().toInt()); 
			    values.put(TrackProvider.KEY_TRACK_PAUSE_TIME, tb.getPauseTime());
			    values.put(TrackProvider.KEY_TRACK_OFFTIME, tb.getOffTime());
			    values.put(TrackProvider.KEY_TRACK_END_TIME, tb.getEndTime());
			    values.put(TrackProvider.KEY_TRACK_TYPE, tb.getType().toString());
			    values.put(TrackProvider.KEY_TRACK_CAL_BURNING, tb.getBurn()); 
			    values.put(TrackProvider.KEY_TRACK_SPORT_TIME, tb.getSportTime());
			    values.put(TrackProvider.KEY_TRACK_DISTANCE, tb.getDistance()); 
			    
			    values.put(TrackProvider.KEY_TRACK_GEO_STATUS, 1);			
			    if(tb.getType()==TrackType.GPX){
			    	values.put(TrackProvider.KEY_TRACK_START_WP, tr.getStartJsonWp()); 
			    	values.put(TrackProvider.KEY_TRACK_LAST_WP, tr.getLastJsonWp());
			    	   values.put(TrackProvider.KEY_TRACK_START_TIME, tb.getStartTime());
			    }
			 
			   if(!TextUtils.isEmpty(roadBears)){
//			    values.put(TrackProvider.KEY_TRACK_ROAD_BEARS, roadBears); //TODO: to remove
			    tr.saveBearContent(false);
			   }
			   if(!TextUtils.isEmpty(tr.newMdWpsJson)){
				   wps =  buildWps(null,null,tr.newMdWpsJson.toString());
				   tr.newMdWpsJson=new StringBuffer();
			   }
			    updateTable(TrackProvider.TRACKS_URI,values, tb.getTrackId(),wps);	
//			    QLog.getLogger().d(dTAG, TAG+" updateTrack: "+  tb.getTrackId() +", track status is" +tb.getStatus());
											    
	}
	/*
	 * update  track available status
	 */
	protected void updateTrackAvStatus(Track tr)
	{
//		app.saveLocationParameters(false);
		
//		int trackId= tb.getTrackId();		 
		Track_bean tb =tr.getTrackBean();
		ContentValues values = new ContentValues(); 
		 
		tb.setLastdbTime(System.currentTimeMillis()) ; 
	    values.put(TrackProvider.KEY_TRACK_AVSTATUS, tb.getAvStatus().toInt());
	    values.put(TrackProvider.KEY_LAST_UPDATE_TIME, tb.getLastdbTime());
	    updateTable(TrackProvider.TRACKS_URI,values, tb.getTrackId(),null);	
	    
	    updateCateTrack(tb.getTrackId(),tb.getAvStatus().toInt());//update cates
 
	    initialStatistics(0,System.currentTimeMillis(),tb.getType().toInt(),false);
	   
	    // QLog.getLogger().d(dTAG, TAG+" updateTrack: "+  tb.getTrackId() +", track available status is" +tb.getAvStatus());
											    
	}
	
	
	
	/*
	 * update  track,no normal wps will be updated, roadwps, mdwps can be updated.
	 */
	protected void updateWps(Track tr,boolean isMd)
	{
//		app.saveLocationParameters(false);
		
//		int trackId= tb.getTrackId();		 
		Track_bean tb =tr.getTrackBean();
		ContentValues values = new ContentValues();  
				tb.setLastdbTime(System.currentTimeMillis()) ;
//      	 		values.put(TrackProvider.KEY_ID, trackId); 
      	 	    String value; 
			   if(isMd){
				   value = tr.wps2json(tb.getMdWps());
				   if(!TextUtils.isEmpty(value)) 
					   values.put(TrackProvider.KEY_TRACK_MDWPS,value);  
				    // QLog.getLogger().d(dTAG, TAG+" tr.getMdWps() : "+ value); 
			   }
			   else {
				   value = tr.wps2json(tb.getRoadWps());
				   if(!TextUtils.isEmpty(value)){
//					   values.put(TrackProvider.KEY_TRACK_ROAD_BEARS,value);//TODO: to remove
					   tr.saveBearContent();
				   }
//				   QLog.getLogger().d(dTAG, TAG+" tr.getRoadWps() : "+value); 
			   }
			    updateTable(TrackProvider.TRACKS_URI,values, tb.getTrackId(),null);	
			    app.getTrackCache().put(tb.getTrackId(), tr);
			    
	}
	protected void updateWpsGEO(int trackId,String[]geoWps){
		ContentValues values = new ContentValues(); 
		if(geoWps[0]!=null && geoWps[0].length()>10){//only when the length >10 to update the wps geo info, to provent the wps to be cleared
//			  values.put(TrackProvider.KEY_TRACK_ROAD_BEARS, geoWps[0]);//TODO: to remove
			  Track tr = new Track(  trackId,false,  geoWps[0],null);
			  tr.saveBearContent(false);
			 
		}
		if(geoWps[1]!=null && geoWps[1].length()>10){
			  values.put(TrackProvider.KEY_TRACK_START_WP, geoWps[1]);
		}
		if(geoWps[2]!=null && geoWps[2].length()>10){
			  values.put(TrackProvider.KEY_TRACK_LAST_WP, geoWps[2]);
		}
		if(geoWps[3]!=null && geoWps[3].length()>10){
			  values.put(TrackProvider.KEY_TRACK_MAXRD_WP, geoWps[3]);
		}
		if(geoWps[4]!=null && geoWps[4].length()>0){//network errors cnt
			  values.put(TrackProvider.KEY_TRACK_GEO_STATUS, geoWps[4]); 
		}
		if(values.size()>0){
			values.put(TrackProvider.KEY_LAST_UPDATE_TIME, System.currentTimeMillis()); 
			updateTable(TrackProvider.TRACKS_URI,values,trackId,null);
		}
		
	}

	 
	 
	 
	 
	 
	 
	 protected void getTrack(String trackId)
		{	 
			if(Integer.valueOf(trackId)<=0)return;
			Track track =getTrack( Integer.valueOf(trackId));
			if(track!=null){
				 app.setCurrentTrack(track);
				 app.currentTrackId = Integer.valueOf(trackId);	
			}
			else
				 app.currentTrackId=-1; 
		    // QLog.getLogger().dLog(TAG, " finished get track of "+ trackId  ); 
		      
		}
		 
		
		Track getTrack(int trackId){
			// QLog.getLogger().d(dTAG,TAG+"  begin to get track of :"+trackId);
			 projection = new String[] { 
		         TrackProvider.KEY_TRACK_NAME,TrackProvider. KEY_TRACK_USER_ID,TrackProvider.KEY_TRACK_COMMENT, 
			     TrackProvider.KEY_TRACK_DESC ,TrackProvider.KEY_TRACK_START_WP,TrackProvider.KEY_TRACK_LAST_WP,
			     TrackProvider.KEY_TRACK_START_TIME,TrackProvider.KEY_TRACK_END_TIME,TrackProvider.KEY_TRACK_DISTANCE,	  
			     TrackProvider.KEY_TRACK_EDOWN_DIST,	TrackProvider.KEY_TRACK_EUP_DIST,	TrackProvider.KEY_TRACK_TOPSPEED,	
			     TrackProvider.KEY_TRACK_SPORT_TIME,TrackProvider.KEY_TRACK_PAUSE_TIME,TrackProvider. KEY_TRACK_CONTENT,
			     TrackProvider.KEY_TRACK_IS_SETS,TrackProvider.KEY_SVR_NUMBER, TrackProvider.KEY_LAST_UPDATE_TIME,
			     TrackProvider.KEY_TRACK_STATUS,TrackProvider.KEY_TRACK_OFFTIME    ,TrackProvider.KEY_TRACK_GPSSPAN, 
			     TrackProvider.KEY_TRACK_ROAD_BEARS,TrackProvider.KEY_TRACK_MAXRD_WP,TrackProvider.KEY_TRACK_MAXRD,
			     TrackProvider.KEY_TRACK_MDWPS,TrackProvider.KEY_TRACK_TYPE,TrackProvider.KEY_TRACK_CAL_BURNING,
			     TrackProvider.KEY_TRACK_CREATOR,TrackProvider.KEY_TRACK_SRC,TrackProvider.KEY_TRACK_AVSTATUS,TrackProvider.KEY_TRACK_CREATE_TIME};
			 Track tr = null;
			 Uri uri = Uri.withAppendedPath(TrackProvider.TRACKS_URI, String.valueOf(trackId));
		     Cursor cursor = contentResolver.query(uri, projection, WHERE_TRACK_AV_STATUS_NOT_DELETED, null, null);
		     
		    try {	       
		      if (cursor!=null && cursor.moveToFirst()) {	  
		    	  
//		    	  if( app.getTrackCache().containsKey(Integer.valueOf(trackId))) //check the cache, if exist, then check the timestamp, if timestamp is same,do not read db.
		    	  if( app.getTrackCache().get(Integer.valueOf(trackId))!=null)
		 	     	{
		 	    	if ( app.getTrackCache().get(Integer.valueOf(trackId)).getTrackBean().getLastdbTime() ==  cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_LAST_UPDATE_TIME)))
		 	    	{
//		 	    		app.setCurrentTrack(app.getTrackCache().get(Integer.valueOf(trackId)));
		 	    		//cursor.close();
//		 	    		app.currentTrack =app.getTrackCache().get(Integer.valueOf(trackId));
//		 	    		app.currentTrackId = Integer.valueOf(trackId);	
		 	    	    // QLog.getLogger().dLog(TAG, "get the track from the cache instead of db. "+ trackId  );
		 	    	    cursor.close();
		 	    		return app.getTrackCache().get(Integer.valueOf(trackId));
		 	    	}
		 	     }
		    	  int id =Integer.valueOf(trackId);
		    	  String wpsJson= Utils.isContentExist(Utils.getContentPah(id))?null:cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CONTENT));;
//		    	   String wpsJson =cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CONTENT));
		    	  String rdBearJson = Utils.isContentExist(Utils.getBearContentPah(id))?null:cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_ROAD_BEARS));
//		    	   String rdBearJson =cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_ROAD_BEARS));
		    	   String mdBearJson =  cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MDWPS));
//		    	    Track tr = new Track(null,wpsJson,rdBearJson,mdBearJson);
		    	   // QLog.getLogger().dLog(dTAG, " get trackContent from  "+ (TextUtils.isEmpty(wpsJson)?" txt file":" track db"  ));
		    	   
		    	    tr=TextUtils.isEmpty(wpsJson)? new Track(id,true,rdBearJson,mdBearJson): new Track(id,null,wpsJson,rdBearJson,mdBearJson);
		    	  
//		    	    tr.getTrackBean().setTrackId(Integer.valueOf(trackId));
		    	    /*int idx = cursor.getColumnIndex(TrackProvider.KEY_TRACK_NAME);
		    	    String nm = cursor.getString(idx);	    	    
		    	    cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_NAME));*/
			       tr.getTrackBean().setName(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_NAME)));
			       tr.getTrackBean().setUserid(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_USER_ID)));
			       tr.getTrackBean().setDescription(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DESC)));
			       tr.getTrackBean().setComment(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_COMMENT)));				
			       tr.getTrackBean().setStartTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME)));
			       // tb.setStartWp( )(cursor.getString((cursor.getColumnIndex(TrackProvider.KEY_TRACK_DESC))));
			       tr.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_WP)));
			       tr.loadLastWp(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_LAST_WP)));
			       
			       tr.setMaxRdistWpJson(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD_WP)));
			       tr.getTrackBean().setMaxR(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD)));
			       
			       tr.getTrackBean().setEndTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME))); 
			       tr.getTrackBean().setCreatTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CREATE_TIME)));
			       tr.getTrackBean().setDistance(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE)));
			       tr.getTrackBean().seteDownDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST)));
			       tr.getTrackBean().seteUpDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST)));
			       tr.getTrackBean().setTopSpeed(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED)));		       
			       tr.getTrackBean().setPauseTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME)));
			       tr.getTrackBean().setSvrNumber(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_SVR_NUMBER)));	        
			       tr.getTrackBean().setIsCheckedIn(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_IS_SETS)));
			       tr.getTrackBean().setLastdbTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_LAST_UPDATE_TIME)));
			       tr.getTrackBean().setStatus(TrackStatus.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_STATUS)))); 
			       tr.getTrackBean().setOffTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME))); 
			       tr.getTrackBean().setGpsSpan(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_GPSSPAN)));	 
			       tr.getTrackBean().setType( TrackType.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE))));	
			       tr.getTrackBean().setSportTime( cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME)));
			       tr.getTrackBean().setBurn(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CAL_BURNING)));
			       tr.getTrackBean().setCreator(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CREATOR)));
			       tr.getTrackBean().setSrc(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SRC))); 
			       tr.getTrackBean().setAvStatus(TrackAvStatus.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_AVSTATUS))));
			       app.getTrackCache().put(trackId,tr);
		      }
			        
		      }catch(Exception er){ 
		    	  Utils.logStackTrace(er, dTAG);
		      }
		      finally {
		    	if(cursor!=null && !cursor.isClosed())
		    	 cursor.close();
		      }
		      return tr;
			
		}
		protected void getLastStatisticsTrack(int lastNumber){

			TypeStatistics lastStack    =app.mStatistics.getLastStrack();// new TypeStatistics()  ; 
			// QLog.getLogger().d(dTAG,TAG+"  begin to get getStatisticsTracks  ");
			 projection = new String[] { TrackProvider.KEY_ID,
		         TrackProvider.KEY_TRACK_NAME,       TrackProvider. KEY_TRACK_USER_ID, 
			     TrackProvider.KEY_TRACK_START_TIME, TrackProvider.KEY_TRACK_END_TIME,
			     TrackProvider.KEY_TRACK_DISTANCE,   TrackProvider.KEY_TRACK_EDOWN_DIST, 
			     TrackProvider.KEY_TRACK_EUP_DIST,	 TrackProvider.KEY_TRACK_TOPSPEED,	
			     TrackProvider.KEY_TRACK_SPORT_TIME, TrackProvider.KEY_TRACK_PAUSE_TIME,  
			     TrackProvider.KEY_TRACK_STATUS,     TrackProvider.KEY_TRACK_OFFTIME,
			     TrackProvider.KEY_TRACK_MAXRD  ,    TrackProvider.KEY_TRACK_TYPE,
			     TrackProvider.KEY_LAST_UPDATE_TIME,TrackProvider.KEY_TRACK_CAL_BURNING
			     ,TrackProvider.KEY_TRACK_AVSTATUS,TrackProvider.KEY_SVR_NUMBER
			    };
			
			 Uri uri = TrackProvider.TRACKS_URI; 
			 
			 
			 String where = WHERE_TRACK_AV_STATUS + // "ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")=="+TrackAvStatus.ACTIVE +
			 		" and " +TrackProvider.KEY_TRACK_TYPE +"!="+TrackType.COPY; 
			 where += WHERE_TYPE_NO_GPX;//" and " +TrackProvider.KEY_TRACK_TYPE +"!="+TrackType.GPX; 
			 if(lastStack!=null)
				 where +=" and " + TrackProvider.KEY_TRACK_START_TIME + " > "+  lastStack.getEnd();
			 
			 String orderBy= TrackProvider.KEY_TRACK_START_TIME +" DESC " ;
			 String limit =" LIMIT "+lastNumber; 
		     Cursor cursor = contentResolver .query(uri, projection, where, null, orderBy+limit);
		    
		    
		     if(cursor==null  ){
		    	 
		    	 return;
		     }
		     if(cursor.getCount()==0){
		    	 if(cursor!=null && !cursor.isClosed())
			    	 cursor.close();
		    	 return;
		     }
		     if(cursor.getCount()>5){
		    	 lastStack =  new TypeStatistics()  ; 
		     }
		    
		   /*  long earlistTime=System.currentTimeMillis();
		     long latestTime=0;
		     long statStart=System.currentTimeMillis();
		     long statEnd=0;
		     int LastType=type;
		     int currentType = 0;
		     int lastTrackId=0;
		     int trackId=0;
		     StatTrack maxAvTrack; */
		    try {	     
		    	  // QLog.getLogger().d(dTAG, " Tracks got: " +cursor.getCount());  
//			    	  while(cursor.moveToNext()){
		    	  	for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) {
			    		 
//			    		  trackId =Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID)));
			    		 float topSpd =cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED));
			    		  Statics_bean stb = new Statics_bean(); 
			    		  	stb .setTrackid(Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID)))); 
			    		  	stb .setSvrNo(Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_SVR_NUMBER)))); 
			    		  	stb .setName(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_NAME)));
			    		  	stb .setUserid(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_USER_ID)));
			    		  	stb .setStartTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME)));
			    		  	stb .setMaxR(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD))); 
			    		   	stb .setEndTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME))); 
					        stb .setDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE)));
					        stb .seteDownDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST)));
					        stb. seteUpDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST)));
					        stb. setTopSpeed(topSpd);		       
					        stb. setPause(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME))); 
					        stb. setStatus(TrackStatus.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_STATUS)))); 
					        stb. setOffTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME))); 
					        stb.setSportTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME))); 
					        stb.setLastdbTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_LAST_UPDATE_TIME)));
					        stb.setBurn(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CAL_BURNING)));	
					       stb. setType(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE)));  
//					        stb. setType(currentType);  
//					       float avSp = stb.getSportTime()>0? 3600*stb.getDistance()/stb.getSportTime():0; 
					        stb.setAvs(stb.getSportTime()>0? 3600*stb.getDist()/stb.getSportTime():0);  
//					       strack.getSbs().put(stb .getTrackid(), stb) ;
					       
//					     strack.getStaticsTrackBeans().add(stb); 
//					        QLog.getLogger().d(dTAG, TAG+" ddddddddddddddBACKGROUND   stb.getTrackid(): " +stb.getTrackid());
//					        QLog.getLogger().d(dTAG, TAG+" ddddddddddddddBACKGROUND stb.GetOffTime(): " +stb.getOffTime());
//					        QLog.getLogger().d(dTAG, TAG+" ddddddddddddddBACKGROUND stb.GetPause(): " +stb.getPause());
					       lastStack.getSbs().put(stb.getTrackid(), stb);
//					     strack.getTrackIds().put(trackId, lastTrackId);
//					     lastTrackId =trackId;
//					     long totalTime= cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME)) 
//		    				  		-cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME))  ;
				/*	     long totalTime = cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME)) +
					    		   cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME)) +
					    		   cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME));*/
					     
					     long totalTime = stb.getTotalTime();
					     
					     
					     
		    		   if(totalTime>0) { 
		    		 
//					     strack.getStatTrack().seteDownDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST)));
//					     strack.getStatTrack().seteUpDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST))+cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST)));
		    			   lastStack.getStatTrack().setUpDistE(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST)));

		    			   lastStack.getStatTrack().setTopSpeed(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED)));		       
		    			   lastStack.getStatTrack().setPause(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME)));
		    			   lastStack.getStatTrack().setOffTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME))); 
		    			   lastStack.getStatTrack().setDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE)));	 
			    		  lastStack.getStatTrack().setMaxR(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD)));
			    		  lastStack.getStatTrack().setSportTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME)));
			    		  lastStack.getStatTrack().setBurn(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CAL_BURNING)));		       

			    		  float avSp =  cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME)) >0?
			    		   			3600*cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE))
			    		   			/cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME))
			    		   			:0;
			    		   			avSp =	avSp>topSpd?0:avSp;	
//			    		 QLog.getLogger().d(dTAG, TAG+" dddddddddddddd  ID: " +cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID)));
//			    		 QLog.getLogger().d(dTAG, TAG+" dddddddddddddd  avSp: " +avSp);
			    		   			lastStack.getStatTrack().setAvSpeed(avSp);
			    		 float tavSp =  3600*cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE)) /totalTime ;	    		   		 
			    		 tavSp =	tavSp>topSpd?0:tavSp;	
			    		 lastStack.getStatTrack().setTavSpeed(tavSp);
					     
			    		 lastStack.getStatTrack().setTotalTime(totalTime);
			    		 lastStack.setEnd(stb.getEndTime()); 
		    		   }
			      } 
		    	  	
		    	   
//			       maxAvTrack = getMaxTrack(statStart,statEnd,currentType);
			     
			       app.mStatistics.setLastStrack(lastStack);
			       
			      // QLog.getLogger().d(dTAG,TAG+" "+ "finished get statitics tracks" );
		        
		      
		      }catch(Exception er)
		      {
		    	  Utils.logStackTrace(er, dTAG);
		      }
		      finally {
		    		if(cursor!=null && !cursor.isClosed())
				    	 cursor.close();
		        
		      } 
		}
		
		protected void getStatisticTracks(long start,long end,int type,boolean isForceUpdate)
		{	  
			  if(app.mStatistics==null ){
				  app.initialStatistics(); 
			     }
			  
//			 if(QiYouConstant.DEVELOPER_MODE)  
//				 return;  
			 
			 
			  start =app.mStatistics.getLastTime()+100;
			  
			TypeStatistics strack    = new TypeStatistics()  ; 
			// QLog.getLogger().d(dTAG,TAG+"  begin to get getStatisticsTracks  ,start time is "+ start);
			 projection = new String[] { TrackProvider.KEY_ID,
		         TrackProvider.KEY_TRACK_NAME,       TrackProvider. KEY_TRACK_USER_ID, 
			     TrackProvider.KEY_TRACK_START_TIME, TrackProvider.KEY_TRACK_END_TIME,
			     TrackProvider.KEY_TRACK_DISTANCE,   TrackProvider.KEY_TRACK_EDOWN_DIST, 
			     TrackProvider.KEY_TRACK_EUP_DIST,	 TrackProvider.KEY_TRACK_TOPSPEED,	
			     TrackProvider.KEY_TRACK_SPORT_TIME, TrackProvider.KEY_TRACK_PAUSE_TIME,  
			     TrackProvider.KEY_TRACK_STATUS,     TrackProvider.KEY_TRACK_OFFTIME,
			     TrackProvider.KEY_TRACK_MAXRD  ,    TrackProvider.KEY_TRACK_TYPE,
			     TrackProvider.KEY_LAST_UPDATE_TIME ,TrackProvider.KEY_TRACK_CAL_BURNING,
			     TrackProvider.KEY_TRACK_CREATOR,    TrackProvider.KEY_TRACK_SRC
			     ,TrackProvider.KEY_TRACK_AVSTATUS,TrackProvider.KEY_SVR_NUMBER
			     ,TrackProvider.KEY_TRACK_LAST_WP
			    };
			
			 Uri uri = TrackProvider.TRACKS_URI;
			
			 String whereType =type>=0?" and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",1)" + " = " + type:"";
			 String where = WHERE_TRACK_AV_STATUS  + " and " //"ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")==" +TrackAvStatus.ACTIVE   + " and "
					     + TrackProvider.KEY_TRACK_START_TIME + " > "+ start + " and " 
					    + TrackProvider.KEY_TRACK_START_TIME + " < "+ end 
				 		+ whereType;
//			 		where += WHERE_TYPE_NO_GPX;
			 
			 
//			 String where = TrackProvider.KEY_TRACK_START_TIME + " >=? and " 
//					    + TrackProvider.KEY_TRACK_START_TIME + " <=? "  
//				 		+ " and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",1)" + " =? ";

			 String orderBy=TrackProvider.KEY_TRACK_TYPE+","+ TrackProvider.KEY_TRACK_START_TIME  ;
//			 String[] parameters = new String[3]; 
//			 parameters[0] =String.valueOf(start);
//			 parameters[1] =String.valueOf(end) ;
//			 parameters[2] =String.valueOf(type) ;
//			 
		     // QLog.getLogger().dLog(dTAG, TAG+" where clause is: " +where);
		     // QLog.getLogger().d(dTAG, TAG+String.format("  where parameters are, start is %s,end is %s,type is %s",start,end,type));
//		     Cursor cursor = contentResolver.query(uri, projection, where,  parameters, orderBy);
//		     Cursor cursor = contentResolver.query(uri, projection, where,  new String[]{ String.valueOf(start), String.valueOf(end), String.valueOf(type) }, orderBy);
		     Cursor cursor = contentResolver.query(uri, projection, where, null, orderBy);
		     
 		    /* if(cursor!=null ){
 		    	 QLog.getLogger().dLog(dTAG, TAG+" get statistics from db cursor.getCount() " + cursor.getCount());
 		     }*/
		     
		     if(cursor==null){
		    	 
		    	 return;
		     }
		     if(cursor.getCount()==0){ 
		    	 if(cursor!=null && !cursor.isClosed())
			    	 cursor.close();
		    	 return;
		     } 
		     
		     long earlistTime=System.currentTimeMillis();
		     long latestTime=0;
		     long statStart=System.currentTimeMillis();
		     long statEnd=0;
		     int LastType=type;
		     int currentType = 0;
		     int lastTrackId=0;
		     int trackId=0;
		     StatTrack maxAvTrack; 
		    try {	     
		    	  // QLog.getLogger().d(dTAG, " Tracks got: " +cursor.getCount());  
//			    	  while(cursor.moveToNext()){
		    	  	for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) {
			    		  currentType=  cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE));
			    		 
//			    		  // QLog.getLogger().d(dTAG, TAG+" LastType: " +LastType);
			    		  trackId =Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID)));
			    		  if(cursor.getPosition()==0){
			    			  LastType=currentType; 
			    			   strack   =   app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType));
			    			  /* QLog.getLogger().dLog(dTAG, TAG+" 0 app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType)) is null? " + 
			    					   	(app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType))==null) +",currentType:"+currentType
			    					   	);*/
					    	   strack   =  strack==null?new TypeStatistics():strack; 
					    	   
					    	   // QLog.getLogger().d(dTAG, " 0 strack.getSbs().size(): " +strack.getSbs().size()); 
			    		  }else
			    		      if(  LastType!=currentType ){		    		    	  	
							       strack.setStart(statStart);
							       strack.setEnd(statEnd); 
							       strack.setType(LastType);
//							       maxAvTrack = getMaxTrack(statStart,statEnd,LastType);
//							       StatTrack statTrack=strack.getStatTrack();  
							    		  
							       maxAvTrack = getMaxTrack(strack.getStatTrack(),strack.getStatTrack().getEnd(),System.currentTimeMillis(),LastType);
						    	   strack.setStatTrack(maxAvTrack);   
						    	   app.mStatistics.setMaxAvStat(maxAvTrack); 
						    	   app.mStatistics.getStatisticsTracks().put(LastType, strack); 
						    	   strack   =   app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType));
						    	 /*  QLog.getLogger().dLog(dTAG, TAG+" 1 app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType)) is null? " + 
				    					   	(app.mStatistics.getStatisticsTracks().get(Integer.valueOf(currentType))==null) +",currentType:"+currentType
				    					   	);*/
						    	  
						    	   
						    	   strack   =  strack==null?new TypeStatistics():strack; 
						    	   // QLog.getLogger().d(dTAG, " 1 strack.getSbs().size(): " +strack.getSbs().size()); 
						    	   LastType=currentType ; 
						    	   statEnd=0;
							       statStart=System.currentTimeMillis();
						       }
			    		  
 			    		 
			    		  Track_bean  tb = new Track_bean();
			    		  	 tb .setTrackId(Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID)))); 
			    		  	 tb .setSvrNumber(Integer.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_SVR_NUMBER)))); 
			    		  	 tb .setName(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_NAME)));
			    		  	 tb .setUserid(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_USER_ID)));
			    		  	 tb .setStartTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME)));
			    		  	 tb .setMaxR(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD))); 
			    		   	 tb .setEndTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME))); 
					         tb .setDistance(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE)));
					         tb .seteDownDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST)));
					         tb. seteUpDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST)));
					         tb. setTopSpeed(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED)));		       
					         tb. setPauseTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME))); 
					         tb. setStatus(TrackStatus.valueOf(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_STATUS)))); 
					         tb. setOffTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME))); 
					         tb.setSportTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME))); 
					         tb.setLastdbTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_LAST_UPDATE_TIME)));
					         tb.setBurn(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CAL_BURNING)));
					         tb.setCreator(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CREATOR)));
					         tb.setSrc(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SRC)));
					         tb. setType(TrackType.valueOf(currentType));
					         Waypoint wpobj = new Waypoint(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_LAST_WP)));
					         tb.setLastWp(wpobj);  
					         Statics_bean stb = new Statics_bean(tb);  
//					       stb. setType(cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE)));  
					        
					       
//					       float avSp = stb.getSportTime()>0? 3600*stb.getDistance()/stb.getSportTime():0; 
//					        stb.setAVS(stb.getSportTime()>0? 3600*stb.getDistance()/stb.getSportTime():0);  
//					       strack.getSbs().put(stb .getTrackid(), stb) ;
					        earlistTime=earlistTime>stb.getStartTime()?stb.getStartTime():earlistTime;
					        latestTime=latestTime<stb.getStartTime()?stb.getStartTime():latestTime;
					        statStart=statStart>stb.getStartTime()?stb.getStartTime():statStart ;
					        statEnd=statEnd<stb.getStartTime()?stb.getStartTime():statEnd;
//					     strack.getStaticsTrackBeans().add(stb); 
//					        QLog.getLogger().d(dTAG, TAG+" ddddddddddddddBACKGROUND   stb.getTrackid(): " +stb.getTrackid());
//					        QLog.getLogger().d(dTAG, TAG+" ddddddddddddddBACKGROUND stb.GetOffTime(): " +stb.getOffTime());
//					        QLog.getLogger().d(dTAG, TAG+" ddddddddddddddBACKGROUND stb.GetPause(): " +stb.getPause());
					     
					        if( strack.getSbs().containsKey( Integer.valueOf(stb.getTrackid()))){
					        	
					        	 // QLog.getLogger().d(dTAG, " to merge the db track to statistics sbs of " +stb.getTrackid() ); 
					        	app.mStatistics.mergeTrack(new Track(tb));
					        }else{
					        	 // QLog.getLogger().d(dTAG, " to add the db track to statistics sbs of " +stb.getTrackid() ); 
					        	 strack.getSbs().put(stb.getTrackid(), stb); 
							     strack.getTrackIds().put(trackId, lastTrackId);
							     lastTrackId =trackId;
							     app.mStatistics.setLastTrackId(trackId);
							     if(tb.getSvrNumber()>0)
							    	 app.mStatistics.getExistedSvrNos().add(Integer.valueOf(tb.getSvrNumber()));
					        }
					        
					     
					     
			      } 
		    	  	
		    	    maxAvTrack = getMaxTrack(strack.getStatTrack(),strack.getStatTrack().getEnd(),System.currentTimeMillis(),currentType);
		    	  	strack.setStart(statStart);
				    strack.setEnd(statEnd); 
			       strack.setType(currentType);
//			       maxAvTrack = getMaxTrack(statStart,statEnd,currentType);
//			       maxAvTrack = getMaxTrack(strack.getStatTrack(),strack.getStatTrack().getEnd(),System.currentTimeMillis(),LastType);
			       strack.setStatTrack(maxAvTrack);
//			       QLog.getLogger().d(dTAG, TAG+" ddddddddddddddBACKGROUND maxAvTrack.getSumTotalTime(): " +maxAvTrack.getSumTotalTime());   
			       app.mStatistics.setFirstTime(earlistTime);
			       app.mStatistics.setLastTime(latestTime); 
			       if(type<0){
			    	   //show all type's tracks.
//			    	   app.mStatistics.setCnt(cursor.getCount());
			    	   app.mStatistics.setCnt(app.mStatistics.getCnt()+cursor.getCount()); 
			       }
			    	  
			       if(!isForceUpdate){
			    	   app.mStatistics.setMaxAvStat(maxAvTrack);			       
//				         
			       }else{
//			    	      CItem citem =new CItem (String.valueOf(type),TrackType.valueOf(type).toCHString());
//			    		  citem.setCnt(1);
			    		 /* boolean isExist = false;
			    		  for(CItem ci:app.mStatistics.getTypeUsedLst()){
			    			  if(Integer.valueOf(ci.GetID())==type){
			    				  isExist=true;
			    				  break;
			    			  }
			    		  }
			    		  */
			    	   if(!app.mStatistics.typeExitsInTypeUsedLst(type)){
			    		      CItem citem =new CItem (String.valueOf(type),TrackType.valueOf(type).toCHString());
				    		  citem.setCnt(1); 
			    			  app.mStatistics.getTypeUsedLst().add(citem);
			    	   }
			       }
			       if(strack.getSbs().size()>0)
			        app.mStatistics.getStatisticsTracks().put(currentType, strack); //put the last one of types
			      
			       
			      // QLog.getLogger().d(dTAG,TAG+" "+ "finished get statitics tracks" );
		        
		      
		      }catch(Exception er)
		      {
		    	  Utils.logStackTrace(er, dTAG);
		      }
		      finally {
		    		if(cursor!=null && !cursor.isClosed())
				    	 cursor.close();
		        
		      } 
//		    return strack;
		   
		}
		

		protected StatTrack getMaxTrack(StatTrack statTrack ,long start,long end,int type){
			 
//			QLog.getLogger().d(dTAG,TAG+"  begin to get max value track");
			 projection = new String[] {  
					 TrackProvider.KEY_ID,
				      TrackProvider.KEY_TRACK_DISTANCE,	  
				     TrackProvider.KEY_TRACK_EDOWN_DIST,	TrackProvider.KEY_TRACK_EUP_DIST,	
				     TrackProvider.KEY_TRACK_TOPSPEED,	
				     TrackProvider.KEY_TRACK_SPORT_TIME,TrackProvider.KEY_TRACK_PAUSE_TIME,  
				     TrackProvider.KEY_TRACK_OFFTIME  ,  
				     TrackProvider.KEY_TRACK_MAXRD,TrackProvider.KEY_TRACK_CAL_BURNING
				     ,TrackProvider.KEY_TRACK_START_TIME,TrackProvider.KEY_TRACK_END_TIME
				     ,TrackProvider.KEY_TRACK_AVSTATUS,TrackProvider.KEY_TRACK_LAST_WP
			   					};
			
//			 Uri uri = Uri.withAppendedPath(TrackProvider.TRACKS_URI, null);
//			 String where = TrackProvider.KEY_TRACK_START_TIME + " > 0 and " 
//					 		+ "ifnull(" + TrackProvider.KEY_TRACK_TYPE +",1)" + "!=" + QiYouConstant.TRACK_TYPE_COPY;
			 
			 String where =  WHERE_TRACK_AV_STATUS //"ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")==" +TrackAvStatus.ACTIVE   
					 	+ " and "
			            + TrackProvider.KEY_TRACK_START_TIME + " >= "+ start + " and " 
					    + TrackProvider.KEY_TRACK_START_TIME + " <= "+ end 
//				 		+ " and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",0)" + " != " + QiYouConstant.TRACK_TYPE_COPY
					    + " and ifnull(" + TrackProvider.KEY_TRACK_TYPE +",0)" + " = " + type
//				 		+ " and _id=70"
				 		;
			 		where += WHERE_TYPE_NO_GPX;
			 		
//			  QLog.getLogger().d(dTAG, TAG+" where clause is: " +where);
		     Cursor cursor = contentResolver.query(TrackProvider.TRACKS_URI, projection, where, null, null);
//		     StatTrack statTrack= new StatTrack();
		     statTrack.setType(type);
		    try {	       
		      if (cursor!=null ) {
//		    	  QLog.getLogger().d(dTAG, TAG+" Max Average Tracks got: " +cursor.getCount());
//		    	  int processedCnt=0; 
//		    	  while(processedCnt<cursor.getCount()){
		    	  for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) {
//		    	  while(cursor.moveToNext()){
//		    		  QLog.getLogger().d(dTAG, "KEY_ID: " + cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID)));
		    		  long totalTime = cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME)) +
				    		   cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME)) +
				    		   cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME));
		    		  
		    		  long totalTime1 = cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME)) -
				    		   cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME)) ;
		    		  
		    		  totalTime =totalTime>totalTime1?totalTime1:totalTime;
		    		  
//		    		  long totalTime= cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME)) 
//		    				  		-cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME))  ;
		    		  float topSpd =cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED));
		    		  if(totalTime>0) {
//		    			  statTrack.seteDownDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST)));
//			    		  statTrack.seteUpDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST))+cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EDOWN_DIST)));
			    		  statTrack.setUpDistE(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_EUP_DIST)));
			    		  statTrack.setTopSpeed(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_TOPSPEED)));		       
			    		  statTrack.setPause(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_PAUSE_TIME)));
			    		  statTrack.setOffTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_OFFTIME))); 
			    		  statTrack.setDist(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE)));	 
			    		  statTrack.setMaxR(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_MAXRD)));
			    		  statTrack.setSportTime(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME)));
			    		  statTrack.setBurn(cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_CAL_BURNING)));		       
			    		  statTrack.setStart(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_START_TIME)) );
			    		  statTrack.setEnd(cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_END_TIME)) );
			    		  Waypoint wpobj = new Waypoint(cursor.getString(cursor.getColumnIndex(TrackProvider.KEY_TRACK_LAST_WP)));
			    		  statTrack.setMaxEle(wpobj.getWb().getMaxEle());
			    		  statTrack.setMinEle(wpobj.getWb().getMinEle());
			    		  statTrack.setUpDist(wpobj.getWb().getUpDist());
			    		  statTrack.setDownDist(wpobj.getWb().getDownDist());
//			    		  QLog.getLogger().d(dTAG, "id,KEY_TRACK_SPORT_TIME: " 	    		  
//			    				  				+ cursor.getInt(cursor.getColumnIndex(TrackProvider.KEY_ID))+","
//			    				  				+ cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME)));
			    		  long sptime=cursor.getLong(cursor.getColumnIndex(TrackProvider.KEY_TRACK_SPORT_TIME));
			    		  float distance=cursor.getFloat(cursor.getColumnIndex(TrackProvider.KEY_TRACK_DISTANCE));
				       float avSp =  sptime >0?
				    		   			3600*distance/sptime
				    		   			:0;
    		   		   avSp =	avSp>topSpd?0:avSp;	
				       statTrack.setAvSpeed(avSp); 
				       
				       float tavSp =  3600*distance /totalTime ;
		    		   		 
				       tavSp =	tavSp>topSpd?0:tavSp;	
				       statTrack.setTavSpeed(tavSp);
				     
				       statTrack.setTotalTime(totalTime);
				       
				       if(sptime>0 
				    		   &&distance>100){
					       statTrack.setMinTimeKm((long) (sptime*1000/distance)); 
				       }
				       
				      
		    		  } 
//			           processedCnt++;
//	   			   cursor.moveToNext();
//	   			  QLog.getLogger().d(dTAG, "processedCnt: " + processedCnt);
	   			
	   			   
		    	  } 
		    	 
		      }
		    } catch(Exception er)
		      {
		    	  Utils.logStackTrace(er, dTAG);
		      }
		      finally {
		    		if(cursor!=null && !cursor.isClosed())
				    	 cursor.close();
		      }
		   
		    // QLog.getLogger().d(dTAG, "Initialized statTrack...of type "+TrackType.valueOf(type).toCHString());
		    return statTrack;
		 
		}
		
		/*
		 * get the ordered used track type list
		 */
		void getTypeUsedList(){ 
			
			  String TYPES_COUNT="tpes_cnt";
			  projection = new String[] {
					  		TrackProvider.KEY_TRACK_TYPE,
					  		"COUNT(*) AS " + TYPES_COUNT
			  			 };
			  String selection = "0==0) GROUP BY ("+
					  TrackProvider.KEY_TRACK_TYPE;
//			  String orderBy=TrackProvider.KEY_TRACK_TYPE + " DESC ";
			  
//			  "ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")
			  String where =WHERE_TRACK_AV_STATUS //"ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")==" +TrackAvStatus.ACTIVE   
					  + " and " +selection
//					  + " and " +TrackProvider.KEY_TRACK_TYPE +"!=" + TrackType.GPX;
					  ;
			  
			  
			  String orderBy=TYPES_COUNT + " DESC ";
			  Cursor cursor = contentResolver.query(TrackProvider.TRACKS_URI, projection, where, null, orderBy);
			  try {	       
			      if (cursor!=null) {
//			    	  QLog.getLogger().d(dTAG, TAG+" Used track type got: " +cursor.getCount());
//			    	  int processedCnt=0;
			    	  CItem citem;
			    	  boolean exist;
			    	  if( app.mStatistics ==null){
//		    			  app.mStatistics =new Statistics();
			    		  app.initialStatistics();
		    		  }
//			    	  app.mStatistics.getTypeUsedLst().clear();
			    	  
//			    	  ArrayList<CItem> typeUsedLst = new ArrayList<CItem>();//new SparseArray<Integer>();
//			    	  while(cursor.moveToNext() ){
			    	  for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) {
//			    		  QLog.getLogger().d(dTAG, TAG+"xxxxxxxxxxxx cursor.getString(0): " +cursor.getString(0));
//			    		  QLog.getLogger().d(dTAG, TAG+"xxxxxxxxxxxx TrackType.valueOf(cursor.getInt(0)).toCHString(): " +TrackType.valueOf(cursor.getInt(0)).toCHString());
			    		 
			    		  if(cursor.getInt(0)==TrackType.GPX.toInt())continue;
			    		  
			    		  citem =new CItem (cursor.getString(0),TrackType.valueOf(cursor.getInt(0)).toCHString());
			    		
			    		  exist=false;
			    		  for(CItem i:app.mStatistics.getTypeUsedLst()){
			    			 if(Integer.valueOf(i.getId()) == Integer.valueOf(citem.getId())){			    				 
			    				 exist=true;
			    				 break;
			    			 }
			    		  }
			    		  if(exist)continue;
			    		  citem.setCnt(cursor.getInt(1)); 
			    		  app.mStatistics.getTypeUsedLst().add(citem); 
			    		
//			    		   processedCnt++;
//			   			   cursor.moveToNext();
			    		  
//			    		  QLog.getLogger().d(dTAG, TAG+ "%%%%%%% track Type:" +cursor.getColumnIndex(TrackProvider.KEY_TRACK_TYPE) +", count:"+cursor.getColumnIndex(TYPES_COUNT) );
				    	  } 
//			    	  app.typeUsedLst =  typeUsedLst ;
				      }
				    } catch(Exception er)
				      {
				    	  Utils.logStackTrace(er, dTAG);
				      }
				      finally {
				    		if(cursor!=null && !cursor.isClosed())
						    	 cursor.close();
				      }
				   
		}
		 
		
		
		void getGpList(){
			  String GEO_COUNT="geo_cnt";
			  projection = new String[] {
					  		TrackProvider.KEY_GEO_LAT,
					  		TrackProvider.KEY_GEO_LON,
					  		TrackProvider.KEY_LAST_UPDATE_TIME,
					  		" (select count(*) from track_geos where "+  TrackProvider.KEY_TRACK_GEO_GID +" =geos._id) " + GEO_COUNT
			  			 };
//			  String selection = "0==0) GROUP BY ("+
//					  TrackProvider.KEY_TRACK_TYPE;
//			  String orderBy=TrackProvider.KEY_TRACK_TYPE + " DESC ";
			  
//			  "ifnull(" + TrackProvider.KEY_TRACK_AVSTATUS +","+TrackAvStatus.ACTIVE +")
			  String where =TrackProvider.KEY_GEO_TYPE +" = " + QiYouConstant.GEO_STREETNO; 
			  where +=" and " +TrackProvider.KEY_LAST_UPDATE_TIME +" > " + app.mStatistics.getLastGeo(); 
//			  int i=0;
			  int i =app.mStatistics.getGpList().size();
			  long lastGeoDate = 0;
			  Cursor cursor = contentResolver.query(TrackProvider.GEOS_URI, projection, where, null, null);
			  try {	       
			      if (cursor!=null) {
//			    	 
//			    	  app.mStatistics.getGpList().clear();
//			    	  ArrayList<CItem> typeUsedLst = new ArrayList<CItem>();//new SparseArray<Integer>();
//			    	  while(cursor.moveToNext() ){
			    	  
			    	  for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) {
//			    		  QLog.getLogger().d(dTAG, TAG+"xxxxxxxxxxxx cursor.getString(0): " +cursor.getString(0));
//			    		  QLog.getLogger().d(dTAG, TAG+"xxxxxxxxxxxx TrackType.valueOf(cursor.getInt(0)).toCHString(): " +TrackType.valueOf(cursor.getInt(0)).toCHString());
			    		 if( cursor.getDouble(0)>0 && cursor.getDouble(1)>0){
			    			 lastGeoDate =cursor.getLong(2)>lastGeoDate?cursor.getLong(2):lastGeoDate;
			    			 
//			    			 app.mStatistics.getGpList().put(i++, new GPItem(cursor.getInt(3),Utils.getGeoPoint(cursor.getDouble(0), cursor.getDouble(1)),-1));
			    			 app.mStatistics.getGpList().put(i++, new GPItem(cursor.getInt(3), cursor.getDouble(0) , cursor.getDouble(1) ,-1));
			    			 	
			    		 }
			    		  
//			    		  QLog.getLogger().d(dTAG, TAG+ "%%%%%%% geo Cnt: " +cursor.getInt(2)+", geo: "+cursor.getDouble(0)+","+ cursor.getDouble(1) );
				    	  }
			    	   app.mStatistics.setLastGeo(lastGeoDate);
//			    	  app.typeUsedLst =  typeUsedLst ;
			    	   
			    	  
				      }
			      
				        String bearString = Utils.readSDFile(QiYouConstant.BEAR_TEXT);	
				        if(TextUtils.isEmpty(bearString)){
				        	return;
				        }
					    String[] gps = bearString.split(";");
				        String[] latlon; 
				        GPItem gp = null;
				        for(String bear:gps){
				        	latlon=bear.split(",");
				        	if(latlon.length==0||TextUtils.isEmpty(latlon[0])||TextUtils.isEmpty(latlon[1]))continue;
				        	gp = null;
				        	try{
	//			        		gp= new GPItem(1,new GeoPoint(Double.valueOf(latlon[0]),Double.valueOf(latlon[1])));
//				        		gp= new GPItem(1,Utils.getGeoPoint(Double.valueOf(latlon[0]),Double.valueOf(latlon[1])),5);
				        		gp = new GPItem(1, Double.valueOf(latlon[0]) ,Double.valueOf(latlon[1]) ,5);

				        		if(gp!=null)
				        			app.mStatistics.getGpList().put(i++, gp);
				        	}catch(NumberFormatException e) {
				        		Utils.logStackTrace(e, TAG);
				        	}
				        	 
				        } 
				        Utils.writeSDFile(QiYouConstant.BEAR_TEXT,"");//update bear text to null on each mStatistics reading.
			        
				    } catch(Exception er)
				      {
				    	  Utils.logStackTrace(er, dTAG);
				      }
				      finally {
				    		if(cursor!=null && !cursor.isClosed())
						    	 cursor.close();
				      }
			  
			   
		        
		        
		}
		
		void getCateTrackList(){  
			
//			private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";
//
//			TrackProvider.getTracksDB().rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});
//			
			  projection = new String[] {TrackProvider.KEY_CATE_NAME,TrackProvider.KEY_TRACK_ID };
			 
//			  String orderBy=TrackProvider.KEY_TRACK_TYPE + " DESC ";
			  
//			  String where = "ifnull(" + TrackProvider.KEY_CATE_TRACK_STATUS +","+TrackAvStatus.ACTIVE +")=="  +TrackAvStatus.ACTIVE  ;
			  String where =  "( ifnull(" + TrackProvider.KEY_CATE_TRACK_STATUS +","+TrackAvStatus.ACTIVE +")=="  +TrackAvStatus.ACTIVE   +
				" OR " + TrackProvider.KEY_CATE_TRACK_STATUS+" = "+TrackAvStatus.ACTIVE +")";
			  String orderBy= TrackProvider.KEY_CATE_NAME  ;
			  
			  Cursor cursor = contentResolver.query(TrackProvider.CATE_TRACK_URI, projection, where, null, orderBy);
			  try {	       
			      if (cursor!=null) {
//			    	  QLog.getLogger().d(dTAG, TAG+" Category track get cnt: " +cursor.getCount());
//			    	  int processedCnt=0; 
			    	  if( app.mStatistics ==null){
		    			  app.mStatistics =new Statistics();			    			  
		    		  }
			    	 
//			    	  ArrayList<CItem> typeUsedLst = new ArrayList<CItem>();//new SparseArray<Integer>();
//			    	  while(cursor.moveToNext() ){
			    	  String lastCate="";
			    	  String cate="";
			    	  ArrayList<Integer> trackIds=new ArrayList<Integer>();
			    	  HashMap<String,ArrayList<Integer>> mCategoryList= new HashMap<String,ArrayList<Integer>> ();
			    	  for (cursor.moveToFirst(); !cursor.isAfterLast();cursor.moveToNext()) { 
			    		  cate =cursor.getString(0);
			    		  if(!TextUtils.isEmpty(lastCate) && !lastCate.equalsIgnoreCase(cate)) { 
//			    			  QLog.getLogger().d(dTAG, TAG+"got category: " +lastCate);
			    			  mCategoryList.put(lastCate, trackIds);
			    			  trackIds= new ArrayList<Integer>();
			    		  }
			    		  trackIds.add(cursor.getInt(1)); 
			    		  lastCate=cate;
			    		  if(cursor.isLast()){
			    			  mCategoryList.put(lastCate, trackIds);
			    		  }
				      }
			    	  app.mStatistics.setCategoryList(mCategoryList);
			    	  app.initialCates();//check and insert default Cates  
			      }
			  }catch(Exception er)
				      {
				    	  Utils.logStackTrace(er, dTAG);
				      }
				      finally {
				    		if(cursor!=null && !cursor.isClosed())
						    	 cursor.close();
				      }
				   
		}
		 
		 void addNewCateTrack(HashMap<Integer,ArrayList<String>> mCategoryList){ 
			 if(mCategoryList==null)return;
			  ContentValues[] values = new ContentValues[mCategoryList.size()];
			  List<ContentValues> valueList = new  ArrayList<ContentValues>();
			  ContentValues value;
			  int i=0;
			  for(int id :mCategoryList.keySet()){
				 if(mCategoryList.get(id)==null)continue;
				  for(String key:mCategoryList.get(id)){ 
					  value = new ContentValues();
					  value.put(TrackProvider.KEY_CATE_NAME, key); 
					  value.put(TrackProvider.KEY_TRACK_ID, id);
//				    	QLog.getLogger().d(dTAG,  TAG+" adding new cate is  "+key);
					  valueList.add(value);
				  }
				
              } 
			    try {   
	 	 		      contentResolver.bulkInsert(TrackProvider.CATE_TRACK_URI, valueList.toArray(values)); 
	 	 		      app.getNewCategoryList().clear();
			    }
			    catch (Exception er) { 
			      Utils.logStackTrace(er, dTAG);
			    }
			    
		 }
		 
		 void delCateTrack(HashMap<Integer,ArrayList<String>> mCategoryList){  
			 if(mCategoryList==null)return;
			 String where="";
			 String[] args=new String[2]; 
			 int errCnt=0;
			  for( int id:mCategoryList.keySet()){
				  if(mCategoryList.get(id)==null)continue;
				  for(String key:mCategoryList.get(id)){		
					  
					  where = TrackProvider.KEY_CATE_NAME +"=? and "+ TrackProvider.KEY_TRACK_ID +"=?";
					  args[0]=key;
					  args[1]=String.valueOf(id); 
				      try {   
			 	 		      contentResolver.delete(TrackProvider.CATE_TRACK_URI, where, args);
			 	 		      
					     }
					   catch (Exception er) {  
					      Utils.logStackTrace(er, dTAG);
					      errCnt++;
					    } 
				  }
				
             } 
			 if(errCnt==0)
				 app.getDelCategoryList().clear();   
		 }
		 
		 
		 /*
			 * update  track,no normal wps will be updated, roadwps, mdwps can be updated.
			 */
			protected void updateCateTrack(int trackId,int status)
			{
//				app.saveLocationParameters(false);
				
//				int trackId= tb.getTrackId();		 
				 
				ContentValues values = new ContentValues();  
					 
			    values.put(TrackProvider.KEY_CATE_TRACK_STATUS,status);
			    
			   String where =  TrackProvider.KEY_TRACK_ID + "==" + trackId;
			    if (contentResolver.update(TrackProvider.CATE_TRACK_URI, values, where, null) == 0) {
			    	  //没有找到记录,新增track.
			    	  Log.e(dTAG,TAG+" "+"没有可匹配更新。");
//					    	   
			      }  
			    
//			    updateTable(TrackProvider.CATE_TRACK_URI,values, trackId,null);	
//			    QLog.getLogger().d(dTAG, TAG+" updateTrack: "+  trackId +", track status is" + status);
													    
			}
		 
			/*
			 * update  track server Number
			 */
/*			protected void updateTrackSvrNo(Track_bean tb)
			{
//				app.saveLocationParameters(false);
				
//				int trackId= tb.getTrackId();		 
//				Track_bean tb =tr.getTrackBean();
				ContentValues values = new ContentValues(); 
				 
				tb.setLastdbTime(System.currentTimeMillis()) ; 
			    values.put(TrackProvider.KEY_SVR_NUMBER, tb.getNumber());
			    values.put(TrackProvider.KEY_LAST_UPDATE_TIME, tb.getLastdbTime());
			    updateTable(TrackProvider.TRACKS_URI,values, tb.getTrackId(),null);	 
			    QLog.getLogger().d(dTAG, TAG+" updateTrack: "+  tb.getTrackId() +", track available status is" +tb.getAvStatus());
													    
			}*/
			
			/*
			 * update  track server Number
			 */
			protected void updateTrackSvrNo(Map<Integer,Integer> ids)
			{
				 if(ids==null)return;
				  
				  ContentValues values =  new ContentValues(); ;
				  int svrNo=0;
				  Track tr;
				  for(int id :ids.keySet()){
//					 if(mCategoryList.get(id)==null)continue;
					  svrNo=ids.get(Integer.valueOf(id));
					  // QLog.getLogger().d(dTAG, TAG+" get track id: "+id+", svrnumber"+svrNo);
					  svrNo=ids.get(Integer.valueOf(id));
					  if(svrNo<=0)continue;
					  	values.put(TrackProvider.KEY_SVR_NUMBER,svrNo );
					  	values.put(TrackProvider.KEY_LAST_UPDATE_TIME, System.currentTimeMillis());
					    updateTable(TrackProvider.TRACKS_URI,values, id,null);	 
					   
					    tr =app.getTrackCache().get(Integer.valueOf(id));
					    if(tr!=null)
					    	tr.getTrackBean().setSvrNumber(svrNo);
					    
					    // QLog.getLogger().d(dTAG, TAG+" srvnumber updated: " +svrNo);
	              } 
//				    try {   
//		 	 		      contentResolver。(TrackProvider.CATE_TRACK_URI, valueList.toArray(values)); 
//		 	 		      app.getNewCategoryList().clear();
//				    }
//				    catch (Exception er) { 
//				      Utils.logStackTrace(er, dTAG);
//				    }
				    								    
			}
			
			int getCurrentSeq(String tableName){
				String sql ="select seq from sqlite_sequence where name=?";
				  // QLog.getLogger().d(dTAG, TAG+" sequence query sql: " +sql);
				 Cursor cursor = TrackProvider.getTracksDB().rawQuery(sql,  new String[]{tableName });
				
				 try{
					  if(cursor!=null && cursor.moveToFirst() ){
						  // QLog.getLogger().d(dTAG, TAG+" sequence query cursor.getCount() : " +cursor.getCount());
						 return cursor.getInt(cursor.getColumnIndex("seq"));
					 }
				  }catch(Exception er){ 
			    	  Utils.logStackTrace(er, dTAG);
			      }
			      finally {
			    	if(cursor!=null && !cursor.isClosed())
			    	 cursor.close();
			      }
				 
				 return -1;
			}
			void updateSeqId(String tableName,int seq){
				String sql ="update sqlite_sequence set seq="+ seq +" where name="+"'" + tableName + "'";
				sql ="update sqlite_sequence set seq=? where name=?";
				
				  // QLog.getLogger().d(dTAG, TAG+" sequence updated: ------------- " +sql);
//				TrackProvider.getTracksDB().beginTransaction();
				TrackProvider.getTracksDB().execSQL(sql,new Object[]{seq,tableName});
//				TrackProvider.getTracksDB().endTransaction();
			}
			
			void insertSeqId(String tableName,int seq){
				String   sql ="insert into sqlite_sequence(name,seq) values(?,?)";
				
				  // QLog.getLogger().d(dTAG, TAG+" sequence insert sql: ------------- " +sql);
//				TrackProvider.getTracksDB().beginTransaction();
				TrackProvider.getTracksDB().execSQL(sql,new Object[]{tableName,seq});
//				TrackProvider.getTracksDB().endTransaction();
			}
		 
		 @Override
		public void onDestroy() {
	  
	     //  isStop=true;//锟斤拷使service锟斤拷锟斤拷锟竭筹拷也锟斤拷锟斤拷停止锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷通锟斤拷锟斤拷锟斤拷isStop锟斤拷停止锟竭筹拷
			  // QLog.getLogger().d(dTAG, TAG+" db service destory");
	       super.onDestroy(); 
//	       app.saveLocationParameters(false);

	}

}
