package com.fuban.user.db
|
|
import android.content.ContentValues
|
import android.content.Context
|
import cn.sinata.xldutils.sysErr
|
import com.amap.api.services.core.LatLonPoint
|
import com.amap.api.services.help.Tip
|
import org.jetbrains.anko.db.*
|
|
/**
|
* 历史记录数据库操作
|
*/
|
object HistoryDBManager {
|
|
private fun hasSameAddress(context: Context, name: String, address: String, table: String = DBHelper.HISTORY_TABLE_NAME): Long {
|
return context.database.use {
|
return@use select(table)
|
.columns("id")
|
.whereSimple("name=? and address=?", name, address)
|
.exec {
|
if (this.moveToFirst()) {
|
this.getLong(0)
|
} else {
|
-1
|
}
|
}
|
}
|
}
|
|
|
fun getAddressList(context: Context,city: String = "", limit: Int = 10, table: String = DBHelper.HISTORY_TABLE_NAME): List<Tip> {
|
return context.database.use {
|
val columns1 = select(table)
|
.columns("name", "lat", "lng", "district", "address", "code", "time")
|
if (city.isNotEmpty()){
|
columns1.whereSimple("city=?",city)
|
}
|
return@use columns1
|
.limit(limit)
|
.orderBy("time", SqlOrderDirection.DESC)
|
.parseList(object : RowParser<Tip> {
|
override fun parseRow(columns: Array<Any?>): Tip {
|
val tip = Tip()
|
tip.name = columns[0].toString()
|
val lat = columns[1].toString().toDoubleOrNull()
|
val lng = columns[2].toString().toDoubleOrNull()
|
sysErr("----->$lat-------->$lng")
|
if (lat != null && lng != null)
|
tip.setPostion(LatLonPoint(lat, lng))
|
tip.district = columns[3].toString()
|
tip.address = columns[4].toString()
|
tip.adcode = columns[5].toString()
|
return tip
|
}
|
})
|
}
|
}
|
|
|
fun saveHistory(context: Context, tip: Tip,city:String, table: String= DBHelper.HISTORY_TABLE_NAME): Long {
|
return context.database.use {
|
//最多存储20条
|
getAllCount(context, table)
|
val values = ContentValues()
|
val id = hasSameAddress(context, tip.name, tip.address, table)
|
//有
|
if (id != -1L) {
|
values.put("time", System.currentTimeMillis())
|
return@use update(table, values, "id=?", arrayOf(id.toString())).toLong()
|
} else {
|
values.put("name", tip.name)
|
values.put("lat", tip.point.latitude)
|
values.put("lng", tip.point.longitude)
|
values.put("district", tip.district)
|
values.put("address", tip.address)
|
values.put("code", tip.adcode)
|
values.put("city", city)
|
values.put("time", System.currentTimeMillis())
|
return@use insert(table, null, values)
|
}
|
}
|
}
|
|
|
fun clearHistory(context: Context, table: String= DBHelper.HISTORY_TABLE_NAME) {
|
context.database.use {
|
delete(table)
|
}
|
}
|
|
private fun getAllCount(context: Context, table: String) {
|
context.database.use {
|
val list = select(table)
|
.columns("time")
|
.orderBy("time", SqlOrderDirection.DESC)
|
.parseList(object : RowParser<Long> {
|
override fun parseRow(columns: Array<Any?>): Long {
|
return columns[0].toString().toLong()
|
}
|
})
|
if (list.size >= 20) {
|
val last = list[18]
|
delete(table, "time<?", arrayOf(last.toString()))
|
}
|
}
|
}
|
|
}
|