main adapter not submitting paging data android kotlin - android-studio

Main Fragment:
here were initializing the recyclerview and the viewmodel and getting the data to submit to the adapter:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val binding: FragmentMainBinding = FragmentMainBinding.inflate(inflater, container, false)
this.binding = FragmentMainBinding.inflate(layoutInflater)
dataFromViewModel = arrayListOf()
setupViewModel()
setupList()
setupView()
return binding.root;
}
private fun setupView() {
viewLifecycleOwner.lifecycleScope.launchWhenCreated {
viewModel.listData.collectLatest {
Log.e("Output Frg", it.toString())
if (!dataFromViewModel.contains(it)) {
dataFromViewModel.add(it)
mainAdapter.submitData(it)
mainAdapter.notifyDataSetChanged()
Log.e(TAG, "setupView: ${mainAdapter.repos.toString()}", )
}
}
}
}
private fun setupList() {
mainAdapter = MainAdapter()
val gridLayoutManager: GridLayoutManager = GridLayoutManager(context, 2)
binding.recyclerview.apply {
layoutManager = gridLayoutManager
adapter = mainAdapter
}
// mainAdapter.addLoadStateListener { loadState ->
//
// if (loadState.refresh is LoadState.Loading && !flag) {
// binding.progressbar.visibility = View.VISIBLE
// flag = true
// } else {
// binding.progressbar.visibility = View.GONE
// }
// }
}
private fun setupViewModel() {
viewModel =
ViewModelProvider(
this,
ViewModelFactory(RetrofitService.getApiService())
)[MainViewModel::class.java]
}
Main ViewModel:
here were just calling the postdatasource function and adding it to the listData value
class MainViewModel(private val apiService: RetrofitService) : ViewModel() {
val listData = Pager(PagingConfig(pageSize = 6)) {
PostDataSource(apiService)
}.flow.cachedIn(viewModelScope)
}
PostDataSource:
Here, we have extended PostDataSource with PagingSource which will implement a suspend load function which will help us to load the data.
PostDataSource also takes a primary constructor parameter APIService. PostDataSource acts here as a repository and the load function gets the data from the API.
Since the load function is a suspend function, we can call other suspend functions inside it without any issues which we created in APIService.
In the PostDataSource, we take two parameters one of integer type and other of the data type we have to load on the list item. The integer parameter represents the page number here.
Here, we get the page number from params and assign it to nextPage variable using param.key and if it returns null, we set a default value 1.
We also do the API call and get assign the response to the response variable using APIService which we passed as a constructor parameter to PostDataSource class.
After doing all the operations with the successful response, we return the LoadResult.Page object here with the required data and it something went wrong we use LoadResult.Error.
We are also passing null as the next key if there is no corresponding data in that direction.
class PostDataSource(private val apiService: RetrofitService) : PagingSource<Int, repo>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, repo> {
try {
val currentLoadingPageKey = params.key ?: 1
val response = apiService.getListData(currentLoadingPageKey)
val responseData = mutableListOf<repo>()
var repos : List<repo>
val data = response
responseData.addAll(data)
Log.e(TAG, "load: $responseData", )
val prevKey = if (currentLoadingPageKey == 1) null else currentLoadingPageKey - 1
return LoadResult.Page(
data = responseData,
prevKey = prevKey,
nextKey = currentLoadingPageKey.plus(1)
)
} catch (e: Exception) {
return LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<Int, repo>): Int? {
return state.anchorPosition?.let { anchorPosition ->
val anchorPage = state.closestPageToPosition(anchorPosition)
anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
}
}
// fun getAllrepos() = retrofitService.getAllrepos()
}
MainAdapter:
Now, we will update the MainListAdapter. We will extend the MainListAdapter with PagingDataAdapter and the PagingDataAdapter will take the type of data we need to display in the list and the ViewHolder.
It also takes a DiffUtil callback, as a parameter to its primary constructor which helps the PagingDataAdapter to update the items if they are changed or updated. And DiffUtil callback is used because they are more performant.
Now, the MainListAdapter looks like,
class MainAdapter : PagingDataAdapter<repo, MainAdapter.ViewHolder>(DiffCallBack) , Filterable {
private lateinit var Repos : List<repo>
class ViewHolder(view: View, mlistener: onItemClickListener) : RecyclerView.ViewHolder(view)
private lateinit var mlistener: onItemClickListener
interface onItemClickListener {
fun OnItemClick(position: Int)
}
var repos: MutableList<repo> = ArrayList()
private var reposFull: MutableList<repo> = ArrayList()
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.findViewById<TextView>(R.id.title).text = getItem(position)?.name
Log.e(TAG,"name ${holder.itemView.findViewById<TextView>(R.id.title).text}", )
Glide.with(holder.itemView.context)
.load(getItem(position)?.owner?.avatar_url)
.into(holder.itemView.findViewById(R.id.imgCircle))
// val repo = repos[position]
//
//
// val mainViewHolder: ViewHolder = holder as ViewHolder
// mainViewHolder.itemView Title?.text = repo.name
// mainViewHolder.Image?.let {
// Glide.with(holder.itemView.context).load(repo.owner.avatar_url).into(
// it
// )
// }
}
fun submitList(list: PagingData<repo>) {
Repos = list as List<repo>
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater
.from(parent.context)
.inflate(R.layout.repo_layout, parent, false), mlistener
)
}
fun setOnItemClickListener(listener: onItemClickListener) {
mlistener = listener
}
object DiffCallBack : DiffUtil.ItemCallback<repo>() {
override fun areItemsTheSame(oldItem: repo, newItem: repo): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: repo, newItem: repo): Boolean {
return oldItem == newItem
}
}
// class MainViewHolder(itemView: View, listener: onItemClickListener) : RecyclerView.ViewHolder(itemView) {
// var Title: TextView? =
// itemView.findViewById<View>(com.lau.google_rep.R.id.title) as TextView
// var Image: ImageView? =
// itemView.findViewById<View>(com.lau.google_rep.R.id.imgCircle) as ImageView
//
// init {
// itemView.setOnClickListener {
// listener.OnItemClick(adapterPosition)
// }
// }
// }
override fun getFilter(): Filter {
return exampleFilter
}
private val exampleFilter: Filter = object : Filter() {
override fun performFiltering(constraint: CharSequence?): FilterResults? {
val filteredList: MutableList<repo> = ArrayList()
if (constraint == null || constraint.length == 0) {
filteredList.addAll(reposFull)
} else {
val filterPattern = constraint.toString().toLowerCase().trim { it <= ' ' }
for (item in reposFull) {
if (item.name.toLowerCase().contains(filterPattern)) {
filteredList.add(item)
}
}
}
Log.d(TAG, "publishResults: $filteredList")
val results = FilterResults()
results.values = filteredList
return results
}
#SuppressLint("NotifyDataSetChanged")
override fun publishResults(constraint: CharSequence?, results: FilterResults) {
repos.clear()
(results.values as? Collection<repo>)?.let { repos.addAll(it) }
notifyDataSetChanged()
}
}
}
retrofit service:
interface RetrofitService {
// #Headers("Authorization: token ")
#GET("repos")
suspend fun getListData(#Query("page") pageNumber: Int): List<repo>
companion object{
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
fun getApiService() = Retrofit.Builder()
.baseUrl("https://api.github.com/orgs/google/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
.create(RetrofitService::class.java)
}
}

Related

How do I get a function in another thread to start the next function in the main thread after it is done?

Here is, what I'm trying to do:
A Switch is turned on, starting a service in another thread (works fine so far)
When this service is successful, it should then start another function within the main thread
I don't mind whether the function is called directly by the service or the service is returning a "success"-value to the main thread, what then starts the next function from there.
Here is, what the important parts of the code looks like:
Main thread:
class SendNotif : AppCompatActivity() {
val context = this
private lateinit var Switch: Switch
// Start LocationService when the switch is on
Switch.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked) {
Toast.makeText(context, "Starting LocationService", Toast.LENGTH_SHORT).show()
Intent(applicationContext, LocationService::class.java).apply {
action = LocationService.ACTION_START
startService(this)
}
} else {
Toast.makeText(context, "Stopping LocationService", Toast.LENGTH_SHORT).show()
Intent(applicationContext, LocationService::class.java).apply {
action = LocationService.ACTION_STOP
startService(this)
}
}
}
}
fun InitiateMessage() {
// This is the function, that is supposed to start after the LocationService
}
}
This is the LocationService. After being successful, the function InitiateMessage() should start.
class LocationService: Service() {
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private lateinit var locationClient: LocationClient
var lat = 0.0F
var long = 0.0F
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
locationClient = DefaultLocationClient(
applicationContext,
LocationServices.getFusedLocationProviderClient(applicationContext)
)
}
// Start or stop the service
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when(intent?.action) {
ACTION_START -> start()
ACTION_STOP -> stop()
}
return super.onStartCommand(intent, flags, startId)
}
private fun start() {
// Starting notification
val notification = NotificationCompat.Builder(this, "location")
.setContentTitle("Tracking location...")
.setContentText("Location: null")
.setSmallIcon(R.drawable.ic_launcher_background)
// Can't swipe this notification away
.setOngoing(true)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Starting the location updates
locationClient
// Every 10 seconds
.getLocationUpdates(10000L)
.catch { e -> e.printStackTrace() }
.onEach { location ->
lat = location.latitude.toString().toFloat() // .takeLast(3) // taking only the last 3 digits
long = location.longitude.toString().toFloat() // .takeLast(3)
val updatedNotification = notification.setContentText(
"Location: ($lat, $long)"
)
// notificationManager.notify(1, updatedNotification.build())
// Geofence
MyGeofence(lat, long)
}
.launchIn(serviceScope)
// startForeground(1, notification.build())
}
private fun stop() {
// Stopping the notification
stopForeground(true)
// Stopping the location service
stopSelf()
}
override fun onDestroy() {
super.onDestroy()
serviceScope.cancel()
}
companion object {
const val ACTION_START = "ACTION_START"
const val ACTION_STOP = "ACTION_STOP"
}
fun MyGeofence(lat : Float, long : Float){
val context = this
var db = DataBaseHandler(context)
var data = db.readData()
// Setting the accuracy of the geofence
val acc = 2
val safelat : Double = data.get(0).LocLat.toFloat().round(acc)
val safelong = data.get(0).LocLong.toFloat().round(acc) // .take(acc).take(acc)
val h = Handler(context.mainLooper)
if(safelat == lat.toFloat().round(acc) && safelong == long.toFloat().round(acc)){
h.post(Runnable { Toast.makeText(context, "You have reached your safe refuge! " + lat.toFloat().round(acc) + " " + long.toFloat().round(acc), Toast.LENGTH_LONG).show() })
// ToDo: Right hereafter the function InitiateMessage() should start
}
else{
h.post(Runnable { Toast.makeText(context, "You are still in great danger! " + lat.toFloat().round(acc) + " " + long.toFloat().round(acc), Toast.LENGTH_LONG).show() })
}
}
fun Float.round(decimals: Int): Double {
var multiplier = 1.0
repeat(decimals) { multiplier *= 10 }
return round(this * multiplier) / multiplier
}
}
So far, I tried it with a Looper, which did not work.
java.lang.RuntimeException: Can't create handler inside thread Thread[DefaultDispatcher-worker-1,5,main] that has not called Looper.prepare()
But I guess the far easier way would be a returned value by the service. How do I implement this, and how do I start the next function through this returned value?
I solved my problem with an observe-function and a companion object, that is a MutableLiveData.
The companion object is placed inside the main thread:
companion object {
// var iamsafe: Boolean = false
val iamsafe: MutableLiveData<Boolean> by lazy {
MutableLiveData<Boolean>()
}
}
The observe-function is placed within onCreate:
val safeObserver = Observer<Boolean> { newState ->
Toast.makeText(context, "Initiating message to my mate.", Toast.LENGTH_SHORT).show()
InitiateMessage()
}
iamsafe.observe(this, safeObserver)
The companion is changed in the second thread like this:
SendNotif.iamsafe.postValue (true)

update one particukar item in recyclerview from fragment after success response android kotlin

Fragment Recyclerview code :
private fun initRecyclerView() {
bestSellersAdapter = BestSellerProductsAdapter(frag)
homeBinding.popularproductsRView.apply {
bestSellersAdapter.second(this#HomeFragment)
adapter = bestSellersAdapter
}
}
private fun getSection() {
viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Main) {
roomProductVM.productFlow.collectLatest {
if (it.isEmpty()) {
categoryViewModel.getAllCategories()
} else {
bestSellersAdapter.setMutableArraylist(it)
bestSellersAdapter.notifyDataSetChanged()
}
}
}
}
based on condition i call this function(getSection) in onViewCreated
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initRecyclerView()
getSection()
addcartviewModel.cartTableSuccessorNot.observe(viewLifecycleOwner) {
if(it.toInt() == variant_id) {
Toast.makeText(context,"Product Updated Successfully",Toast.LENGTH_SHORT).show() homeBinding.popularproductsRView.adapter?.notifyItemChanged(productPosition)
} else {
LoadingUtils.hideDialog()
Toast.makeText(context,"Failure in Cart Table", Toast.LENGTH_SHORT).show()
}
}
}
interface function in fragment : ( here i am taking product position from adapter )
override fun updatepro(position: Int, type: String, id: Int, cart_count: Int, is_notify: Boolean, product_id: Int, name: String, measurement: String,
variant_image: String, price: String, qty: String, stock: String, image: String, moq: String, unit: String) {
productPosition = position
variant_id = id
variant_qty = qty.toInt()
addcartviewModel.updateVariantTableinRoom(id,cart_count.toString(),is_notify,product_id)
addcartviewModel.insertVariantListintoCartTable(id,measurement,price,stock,image,moq,name,variant_image,unit,qty)
}
Adapter class :
class BestSellerProductsAdapter(var context: Context) : RecyclerView.Adapter<BestSellerProductsAdapter.BestSellerViewHolder>() {
var mutableList = mutableListOf<ProductWithVariants>()
fun setMutableArraylist(datas: MutableList<ProductWithVariants>) {
mutableList.clear()
mutableList.addAll(datas)
}
override fun onBindViewHolder(holder: BestSellerViewHolder, position: Int) {
var cart_count = mutableList[position].variantsList[0].cart_count
if(stock?.toInt()==0) {
holder.notify.visibility = View.VISIBLE
holder.addtocart.visibility = View.GONE
holder.pll_cart.visibility = View.GONE
} else if(cart_count == 0) {
holder.addtocart.visibility = View.VISIBLE
holder.pll_cart.visibility = View.GONE
holder.notify.visibility = View.GONE
} else {
holder.notify.visibility = View.GONE
holder.addtocart.visibility = View.GONE
holder.pll_cart.visibility = View.VISIBLE
holder.tv_cart.text = cart_count.toString()
}
holder.addtocart.setOnClickListener {
cart_count = ((cart_count ?: 0) + 1)
selectpro?.updatepro(position,"AddCart",mutableList[position].variantsList[0].id,mutableList[position].variantsList[0].cart_count!!.toInt(),false,mutableList[position].products.id,
mutableList[position].products.name.toString(),
mutableList[position].variantsList[0].measurement.toString() + mutableList[position].variantsList[0].measurement_unit_name.toString(),
mutableList[position].variantsList[0].image.toString(),
mutableList[position].variantsList[0].discounted_price.toString(),
cart_count.toString(),
stock.toString(),
mutableList[position].variantsList[0].image.toString(),
moq.toString(),
mutableList[position].variantsList[0].measurement_unit_name.toString()
)
}
var selectpro: selectproduct?=null
fun second(selectproduct: selectproduct) {
selectpro = selectproduct
}
interface selectproduct {
fun updatepro(position:Int,type:String,id:Int, cart_count:Int,is_notify:Boolean,product_id:Int,
name:String,measurement:String,variant_image:String,price:String,qty:String,
stock:String,image:String,moq:String,unit:String)
fun selectProduct(product: ProductWithVariants,position:Int)
}
Now i want to update the particular item of recycler view after Toast ( Product Updated Successfully ) in fragment .. how to do that
1 After response first find out the item position you want to update
in adapter
2 Also you have to update the list in adapter with new list of data
you get from the response.
then use below code to update particular item in adapter using
position.
adapter.notifyItemChanged(position)

MapBox not focusing camera on location right after allowing location permission

I have an Android app with a map in MapBox where I'm asking for the user's location. It pops up the permission request correctly, but on clicking "Allow" the camera shows a region of Africa, instead of the proper coordinates. It's taking the correct coordinates, it's just the camera that doesn't focus.
This is my LocationPermissionHelper
class LocationPermissionHelper(val activity: WeakReference<Activity>) {
private lateinit var permissionsManager: PermissionsManager
fun checkPermissions(onMapReady: () -> Unit) {
if (PermissionsManager.areLocationPermissionsGranted(activity.get())) {
Log.e("permission", "I'm already granted")
onMapReady()
} else {
Log.e("permission", "They are not granted")
permissionsManager = PermissionsManager(object : PermissionsListener {
override fun onExplanationNeeded(permissionsToExplain: List<String>) {
Log.e("permission", "Inside onExplanation needed")
Toast.makeText(
activity.get(), "You need to accept location permissions.",
Toast.LENGTH_SHORT
).show()
}
override fun onPermissionResult(granted: Boolean) {
Log.e("permission", "Inside onPermissionResult needed before if statement")
if (granted) {
Log.e("permission", "I just got granted")
onMapReady()
} else {
Log.e("permission", "Inside onPermissionResult needed NOT GRANTED")
activity.get()?.finish()
}
}
})
permissionsManager.requestLocationPermissions(activity.get())
}
}
fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
And fragment:
class AddMapFragment : Fragment(R.layout.fragment_add_map) {
private lateinit var locationPermissionHelper: LocationPermissionHelper
private lateinit var binding: FragmentAddMapBinding
private lateinit var mapView: MapView
private lateinit var fusedLocationClient: FusedLocationProviderClient
private var userLat: Double = 41.409428
private var userLong: Double = 2.111255
private var boarLat: Double = 41.409428
private var boarLong: Double = 2.111255
#SuppressLint("MissingPermission")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentAddMapBinding.bind(view)
fusedLocationClient =
LocationServices.getFusedLocationProviderClient(activity as MainActivity)
mapView = binding.mapAdd
// Check location permissions
locationPermissionHelper = LocationPermissionHelper(WeakReference(activity))
locationPermissionHelper.checkPermissions {
// configure map
onMapReady()
// store user location coordinates
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
userLat = location?.latitude ?: 41.409428
userLong = location?.longitude ?: 2.111255
}
}
// Button listener
with(binding) {
fabAddMap.setOnClickListener {
findNavController().navigate(R.id.action_addMapFragment_to_addFormFragment,
Bundle().apply {
putDouble("lat", boarLat)
putDouble("long", boarLong)
}
)
}
}
}
// get map and set camera
fun onMapReady() {
mapView.getMapboxMap().setCamera(
CameraOptions.Builder()
.center(Point.fromLngLat(userLong, userLat))
.pitch(45.0)
.zoom(14.0)
.bearing(-17.6)
.build()
)
mapView.getMapboxMap().loadStyleUri(
Style.MAPBOX_STREETS
) {
initLocationComponent()
setupGesturesListener()
addAnnotationToMap()
}
}
private fun initLocationComponent() {
val locationComponentPlugin = mapView.location
locationComponentPlugin.updateSettings {
this.enabled = true
this.pulsingEnabled = true
this.locationPuck = LocationPuck2D(
bearingImage = AppCompatResources.getDrawable(
requireContext(),
com.mapbox.maps.plugin.locationcomponent.R.drawable.mapbox_user_icon,
),
shadowImage = AppCompatResources.getDrawable(
requireContext(),
com.mapbox.maps.plugin.locationcomponent.R.drawable.mapbox_user_icon_shadow,
),
scaleExpression = interpolate {
linear()
zoom()
stop {
literal(0.0)
literal(0.6)
}
stop {
literal(20.0)
literal(1.0)
}
}.toJson()
)
}
// Pass the user's location to camera
locationComponentPlugin.addOnIndicatorPositionChangedListener(
onIndicatorPositionChangedListener
)
}
#SuppressLint("MissingPermission")
private fun addAnnotationToMap() {
// Create an instance of the Annotation API and get the PointAnnotationManager.
bitmapFromDrawableRes(
requireContext(),
R.drawable.boar
)?.let {
val annotationApi = mapView.annotations
val pointAnnotationManager = annotationApi.createPointAnnotationManager()
// Set options for the resulting symbol layer.
val pointAnnotationOptions: PointAnnotationOptions = PointAnnotationOptions()
// Define a geographic coordinate.
.withPoint(Point.fromLngLat(userLong, userLat))
// Point.fromLngLat(2.111255, 41.409428)
// Specify the bitmap you assigned to the point annotation
.withIconImage(it)
// make marker draggable
.withDraggable(true)
// Add the resulting pointAnnotation to the map.
pointAnnotationManager.addDragListener(dragListener)
pointAnnotationManager.create(pointAnnotationOptions)
}
}
private val dragListener = object : OnPointAnnotationDragListener {
override fun onAnnotationDrag(annotation: Annotation<*>) {}
override fun onAnnotationDragStarted(annotation: Annotation<*>) {}
override fun onAnnotationDragFinished(annotation: Annotation<*>) {
boarLat = (annotation as PointAnnotation).point.latitude()
boarLong = annotation.point.longitude()
/*
Toast.makeText(
requireContext(),
"Lat: $latitude, Long: $longitude, Time: $time",
Toast.LENGTH_SHORT
).show()
*/
}
}
private fun setupGesturesListener() {
mapView.gestures.addOnMoveListener(onMoveListener)
mapView.gestures.addOnMapClickListener { point ->
mapView.location
.isLocatedAt(point) { isPuckLocatedAtPoint ->
if (isPuckLocatedAtPoint) {
Toast.makeText(
requireContext(),
"Clicked on location puck ${mapView.location}",
Toast.LENGTH_SHORT
).show()
}
}
true
}
mapView.gestures.addOnMapLongClickListener { point ->
mapView.location
.isLocatedAt(point) { isPuckLocatedAtPoint ->
if (isPuckLocatedAtPoint) {
Toast.makeText(
requireContext(),
"Long-clicked on location puck ${mapView.location}",
Toast.LENGTH_SHORT
).show()
}
}
true
}
}
// CAMERA TRACKING
private val onIndicatorBearingChangedListener = OnIndicatorBearingChangedListener {
mapView.getMapboxMap().setCamera(CameraOptions.Builder().bearing(it).build())
}
private val onIndicatorPositionChangedListener = OnIndicatorPositionChangedListener {
// Jump to the current indicator position
mapView.getMapboxMap().setCamera(CameraOptions.Builder().center(it).build())
// Set the gestures plugin's focal point to the current indicator location.
mapView.gestures.focalPoint = mapView.getMapboxMap().pixelForCoordinate(it)
}
private val onMoveListener = object : OnMoveListener {
override fun onMoveBegin(detector: MoveGestureDetector) {
onCameraTrackingDismissed()
}
override fun onMove(detector: MoveGestureDetector): Boolean {
return false
}
override fun onMoveEnd(detector: MoveGestureDetector) {}
}
private fun onCameraTrackingDismissed() {
Toast.makeText(requireContext(), "onCameraTrackingDismissed", Toast.LENGTH_SHORT).show()
mapView.location
.removeOnIndicatorPositionChangedListener(onIndicatorPositionChangedListener)
mapView.gestures.removeOnMoveListener(onMoveListener)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
locationPermissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onDestroyView() {
super.onDestroyView()
mapView.location
.removeOnIndicatorBearingChangedListener(onIndicatorBearingChangedListener)
mapView.location
.removeOnIndicatorPositionChangedListener(onIndicatorPositionChangedListener)
mapView.gestures.removeOnMoveListener(onMoveListener)
}
}
IMAGES:

CameraX When I press Take Photo button, cant enter OnImageSavedCallback

I tried to check issue with breakpoints but at this: "object : OnImageSavedCallback{
" line, debugger can't go further and just exits the function without any error. I hope someone can show me the part that I'm missing.
I also already added the permission requests to AndroidManifest.xml for writing and reading media on storage.
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var imageCapture:ImageCapture? = null
private lateinit var outputDirectory: File
private lateinit var cameraExecutor:ExecutorService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
outputDirectory = getOutputDirectory()
cameraExecutor = Executors.newSingleThreadExecutor()
if(allPermissionGranted()){
Toast.makeText(this, "Camera Permissions are Granted", Toast.LENGTH_SHORT).show()
startCamera()
}
else
{
ActivityCompat.requestPermissions(
this, Constants.REQUIRED_PERMISSIONS,
Constants.REQUEST_CODE_PERMISSIONS
)
}
binding.btnTakePhoto.setOnClickListener {
takePhoto()
}
}
private fun getOutputDirectory(): File{
val mediaDir = externalMediaDirs.firstOrNull()?.let { mFile ->
File(mFile, resources.getString(R.string.app_name)).apply {
mkdirs()
}
}
return if(mediaDir != null && mediaDir.exists())
mediaDir else filesDir
}
private fun takePhoto(){
val imageCapture = imageCapture?: return
val photoFile = File(
outputDirectory,
SimpleDateFormat(Constants.FILE_NAME_FORMAT,
Locale.getDefault()).format(System.currentTimeMillis()) + ".jpg")
val outputOption = ImageCapture.OutputFileOptions.Builder(photoFile).build()
imageCapture.takePicture(
outputOption, ContextCompat.getMainExecutor(this),
object : OnImageSavedCallback{
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
val savedUri = Uri.fromFile(photoFile)
val msg = "Photo Saved"
Toast.makeText(
this#MainActivity,
"$msg $savedUri",
Toast.LENGTH_LONG
).show()
}
override fun onError(exception: ImageCaptureException) {
Log.e(Constants.TAG, "onError: ${exception.message}",exception)
}
}
)
}
private fun startCamera(){
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener({
val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder().build().also {
mPreview->
mPreview.setSurfaceProvider(
binding.viewFinder.surfaceProvider
)
}
imageCapture = ImageCapture.Builder().build()
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
try{
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(
this, cameraSelector, preview, imageCapture
)
}
catch (e: Exception){
Log.d(Constants.TAG, "startCamera Fail:", e)
}
}, ContextCompat.getMainExecutor(this))
}
#SuppressLint("MissingSuperCall")
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if(requestCode == Constants.REQUEST_CODE_PERMISSIONS){
if(allPermissionGranted()){
startCamera()
}
else
{
Toast.makeText(this, "Permissions Not Granted by User", Toast.LENGTH_SHORT).show()
finish()
}
}
}
private fun allPermissionGranted() =
Constants.REQUIRED_PERMISSIONS.all{
ContextCompat.checkSelfPermission(
baseContext, it
) == PackageManager.PERMISSION_GRANTED
}
override fun onDestroy() {
super.onDestroy()
cameraExecutor.shutdown()
}
}
Emirhan.
I believe the error is in "outputOption".
Switch to this code and try to run the application and click the button.
Another thing, when trying to run the program and your app closes you can use the "Debug" to see which line of code is giving problem.
I hope it worked out, hug.
...
val outputFilesOption = ImageCapture.OutputFileOptions.Builder(photoFile).build()
imageCapture.takePicture(
outputFilesOption,getMainExecutor(this),
object : ImageCapture.OnImageSavedCallback {
...

Loading indicator does not hide if api failed to retrieve data although it hides if api succeed to retrieve data in Android Paging library

I have a remote server from where I want to fetch 20 items(Job) per api call and show them in RecyclerView using paging library.
For that, I want to show a loading indicator at the beginning of the first api call when list of items is being fetched from the server. Everything is okay if data is fetched successfully. That means the loading indicator got invisible if data loaded successfully. The code is given bellow.
JobService.KT
#GET(Constants.API_JOB_LIST)
fun getJobPost(
#Query("page") pageNumber: Int
): Observable<Response<JobResponse>>
JobResponse.kt
data class JobResponse(
#SerializedName("status") val status: Int? = null,
#SerializedName("message") val message: Any? = null,
#SerializedName("data") val jobData: JobData? = null
)
JobData.kt
data class JobData(
#SerializedName("jobs") val jobs: List<Job?>? = null,
#SerializedName("total") val totalJob: Int? = null,
#SerializedName("page") val currentPage: Int? = null,
#SerializedName("showing") val currentlyShowing: Int? = null,
#SerializedName("has_more") val hasMore: Boolean? = null
)
NetworkState.kt
sealed class NetworkState {
data class Progress(val isLoading: Boolean) : NetworkState()
data class Failure(val errorMessage: String?) : NetworkState()
companion object {
fun loading(isLoading: Boolean): NetworkState = Progress(isLoading)
fun failure(errorMessage: String?): NetworkState = Failure(errorMessage)
}
}
Event.kt
open class Event<out T>(private val content: T) {
private var hasBeenHandled = false
fun getContentIfNotHandled() = if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
fun peekContent() = content
}
JobDataSource.kt
class JobDataSource(
private val jobService: JobService,
private val compositeDisposable: CompositeDisposable
) : PageKeyedDataSource<Int, Job>() {
val paginationState: MutableLiveData<Event<NetworkState>> = MutableLiveData()
val initialLoadingState: MutableLiveData<Event<NetworkState>> = MutableLiveData()
val totalJob: MutableLiveData<Event<Int>> = MutableLiveData()
companion object {
private const val FIRST_PAGE = 1
}
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Job>) {
compositeDisposable += jobService.getJobPost(FIRST_PAGE)
.performOnBackgroundOutputOnMain()
.doOnSubscribe { initialLoadingState.postValue(Event(loading(true))) }
.doOnTerminate { initialLoadingState.postValue(Event(loading(false))) }
.subscribe({
if (it.isSuccessful) {
val jobData = it.body()?.jobData
totalJob.postValue(Event(jobData?.totalJob!!))
jobData.jobs?.let { jobs -> callback.onResult(jobs, null, FIRST_PAGE+1) }
} else {
val error = Gson().fromJson(it.errorBody()?.charStream(), ApiError::class.java)
when (it.code()) {
CUSTOM_STATUS_CODE -> initialLoadingState.postValue(Event(failure(error.message!!)))
else -> initialLoadingState.postValue(Event(failure("Something went wrong")))
}
}
}, {
if (it is IOException) {
initialLoadingState.postValue(Event(failure("Check Internet Connectivity")))
} else {
initialLoadingState.postValue(Event(failure("Json Parsing error")))
}
})
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Job>) {
compositeDisposable += jobService.getJobPost(params.key)
.performOnBackgroundOutputOnMain()
.doOnSubscribe { if (params.key != 2) paginationState.postValue(Event(loading(true))) }
.doOnTerminate { paginationState.postValue(Event(loading(false))) }
.subscribe({
if (it.isSuccessful) {
val jobData = it.body()?.jobData
totalJob.postValue(Event(jobData?.totalJob!!))
jobData.jobs?.let { jobs -> callback.onResult(jobs, if (jobData.hasMore!!) params.key+1 else null) }
} else {
val error = Gson().fromJson(it.errorBody()?.charStream(), ApiError::class.java)
when (it.code()) {
CUSTOM_STATUS_CODE -> initialLoadingState.postValue(Event(failure(error.message!!)))
else -> initialLoadingState.postValue(Event(failure("Something went wrong")))
}
}
}, {
if (it is IOException) {
paginationState.postValue(Event(failure("Check Internet Connectivity")))
} else {
paginationState.postValue(Event(failure("Json Parsing error")))
}
})
}
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Job>) {}
}
JobDataSourceFactory.kt
class JobDataSourceFactory(
private val jobService: JobService,
private val compositeDisposable: CompositeDisposable
): DataSource.Factory<Int, Job>() {
val jobDataSourceLiveData = MutableLiveData<JobDataSource>()
override fun create(): DataSource<Int, Job> {
val jobDataSource = JobDataSource(jobService, compositeDisposable)
jobDataSourceLiveData.postValue(jobDataSource)
return jobDataSource
}
}
JobBoardViewModel.kt
class JobBoardViewModel(
private val jobService: JobService
) : BaseViewModel() {
companion object {
private const val PAGE_SIZE = 20
private const val PREFETCH_DISTANCE = 20
}
private val jobDataSourceFactory: JobDataSourceFactory = JobDataSourceFactory(jobService, compositeDisposable)
var jobList: LiveData<PagedList<Job>>
init {
val config = PagedList.Config.Builder()
.setPageSize(PAGE_SIZE)
.setInitialLoadSizeHint(PAGE_SIZE)
.setPrefetchDistance(PREFETCH_DISTANCE)
.setEnablePlaceholders(false)
.build()
jobList = LivePagedListBuilder(jobDataSourceFactory, config).build()
}
fun getPaginationState(): LiveData<Event<NetworkState>> = Transformations.switchMap<JobDataSource, Event<NetworkState>>(
jobDataSourceFactory.jobDataSourceLiveData,
JobDataSource::paginationState
)
fun getInitialLoadingState(): LiveData<Event<NetworkState>> = Transformations.switchMap<JobDataSource, Event<NetworkState>>(
jobDataSourceFactory.jobDataSourceLiveData,
JobDataSource::initialLoadingState
)
fun getTotalJob(): LiveData<Event<Int>> = Transformations.switchMap<JobDataSource, Event<Int>>(
jobDataSourceFactory.jobDataSourceLiveData,
JobDataSource::totalJob
)
}
JobBoardFragment.kt
class JobBoardFragment : BaseFragment() {
private val viewModel: JobBoardViewModel by lazy {
getViewModel { JobBoardViewModel(ApiFactory.jobListApi) }
}
private val jobAdapter by lazy {
JobAdapter {
val bundle = Bundle()
bundle.putInt(CLICKED_JOB_ID, it.jobId!!)
navigateTo(R.id.jobBoard_to_jobView, R.id.home_navigation_fragment, bundle)
}
}
override fun getLayoutResId() = R.layout.fragment_job_board
override fun initWidget() {
job_list_recycler_view.adapter = jobAdapter
back_to_main_image_view.setOnClickListener { onBackPressed() }
}
override fun observeLiveData() {
with(viewModel) {
jobList.observe(this#JobBoardFragment, Observer {
jobAdapter.submitList(it)
})
getInitialLoadingState().observe(this#JobBoardFragment, Observer {
it.getContentIfNotHandled()?.let { state ->
when (state) {
is Progress -> {
if (state == loading(true)) {
network_loading_indicator.visible()
} else {
network_loading_indicator.visibilityGone()
}
}
is Failure -> context?.showToast(state.errorMessage.toString())
}
}
})
getPaginationState().observe(this#JobBoardFragment, Observer {
it.getContentIfNotHandled()?.let { state ->
when (state) {
is Progress -> {
if (state == loading(true)) {
pagination_loading_indicator.visible()
} else {
pagination_loading_indicator.visibilityGone()
}
}
is Failure -> context?.showToast(state.errorMessage.toString())
}
}
})
getTotalJob().observe(this#JobBoardFragment, Observer {
it.getContentIfNotHandled()?.let { state ->
job_board_text_view.visible()
with(profile_completed_image_view) {
visible()
text = state.toString()
}
}
})
}
}
}
But the problem is if data fetching failed due to internet connectivity or any other server related problem loading indicator does not invisible that means it still loading though I make the loadingStatus false and error message is shown. it means .doOnTerminate { initialLoadingState.postValue(Event(loading(false))) } is not called if error occured. This is the first problem. Another problem is loadInitial() and loadAfter() is being called simultaneously at the first call. But I just want the loadInitial() method is called at the beginning. after scrolling loadAfter() method will be called.
Try replacing all your LiveData's postValue() methods by setValue() or simply .value =.
The problem is that the postValue() method is for updating the value from a background thread to observers in the main thread. In this case you are always changing the values from the main thread itself, so you should use .value =.
Hope it's not too late.

Resources