fusedlocationProviderClient가 callback 될때 onLocatioResult() 에서 받은 location에서 위경도를 화면에 출력하려고 했습니다. 잘 안되어서 리스너에 달려서 안되나(?) 라고 의심해 버튼에 달아서 버튼을 누르면 출력되도록 해보니 잘 됩니다. 디버그를 찍어봤을때 문제는 adapter의 list가 계속 새로 갱신되는것 같습니다. size 가 1에서 변함이 없습니다. 흠 .. 어디를 더 수정해야할까요? onlocationresult에선 화면 출력을 못하는 것인가요?
하고싶은 코드
val locationRequest = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 1_000L)
.build()
val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
val new = consoleAdapter.currentList.toMutableList()
locationResult.lastLocation?.let { location ->
// 위치 업데이트 처리
Log.d("Location", "Latitude : ${location.latitude}, Longitude : ${location.longitude} , speed : ${location.speed}")
// logs.add(Item(info=location.latitude.toString()))
new.add(Item(info=location.latitude.toString()))
}
consoleAdapter.update(new)
}
}
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
return
}
flpc.requestLocationUpdates(locationRequest, locationCallback, null)
버튼으로 확인해본 코드
class MainActivity : AppCompatActivity() {
private lateinit var console: RecyclerView
private lateinit var consoleAdapter: PrintAdapter
var logs = mutableListOf<Item>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
console = findViewById<RecyclerView>(R.id.items)
console.layoutManager = LinearLayoutManager(this)
consoleAdapter = PrintAdapter(this, logs)
console.adapter = consoleAdapter
var btn = findViewById<Button>(R.id.btn)
btn.setOnClickListener(View.OnClickListener {
var new = consoleAdapter.currentList.toMutableList()
new.add(Item(info = "1111"))
consoleAdapter.update(new)
})
}
}
class PrintAdapter(
private val context: Context,
val items: MutableList<Item>
) : ListAdapter<Item, PrintAdapter.ViewHolder>(diffUtil) {
companion object {
val diffUtil = object : DiffUtil.ItemCallback<Item>() {
override fun areItemsTheSame(oldItem: Item, newItem: Item): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Item, newItem: Item): Boolean =
oldItem == newItem
}
}
fun update(rooms: List<Item>) {
submitList(rooms)
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val info = itemView.findViewById<TextView>(R.id.item)
fun bind(item: Item) {
info.text = item.info
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.print_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
}
