<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Burak on Medium]]></title>
        <description><![CDATA[Stories by Burak on Medium]]></description>
        <link>https://medium.com/@burakdev?source=rss-a99dac39edcb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ONKOzf1vbb6QVf6GsDQ8ag.jpeg</url>
            <title>Stories by Burak on Medium</title>
            <link>https://medium.com/@burakdev?source=rss-a99dac39edcb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:33:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@burakdev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Video and Image Capture with CameraX in Android]]></title>
            <link>https://itnext.io/video-and-image-capture-with-camerax-in-android-797f497c0487?source=rss-a99dac39edcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/797f497c0487</guid>
            <category><![CDATA[camerax]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-camera]]></category>
            <dc:creator><![CDATA[Burak]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 17:22:13 GMT</pubDate>
            <atom:updated>2023-01-30T19:20:58.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhbiaEHoOGci_gIGGFZTyg.png" /></figure><h3>Table of Contents</h3><ul><li>Permissions</li><li>Image Capture<br>- Save Photo<br>- Capture Photo</li><li>Video Capture</li></ul><h3>Getting Started</h3><p>App level build.gradle file,</p><pre>def camerax_version = &quot;1.3.0-alpha02&quot;<br>implementation &quot;androidx.camera:camera-core:${camerax_version}&quot;<br>implementation &quot;androidx.camera:camera-camera2:${camerax_version}&quot;<br>implementation &quot;androidx.camera:camera-lifecycle:${camerax_version}&quot;<br>implementation &quot;androidx.camera:camera-video:${camerax_version}&quot;<br><br>implementation &quot;androidx.camera:camera-view:${camerax_version}&quot;<br>implementation &quot;androidx.camera:camera-extensions:${camerax_version}&quot;</pre><p>AndroidManifest.xml for permissions,</p><pre>&lt;uses-feature android:name=&quot;android.hardware.camera.any&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.RECORD_AUDIO&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; android:maxSdkVersion=&quot;28&quot; /&gt;</pre><p>Adding android.hardware.camera.any makes sure that the device has a camera. Specifying .any means that it can be a front camera or a back camera.</p><h3>Permissions</h3><pre>class MainActivity : AppCompatActivity() {<br>    companion object {<br>        private const val REQUEST_CODE_PERMISSIONS = 10<br>        private val REQUIRED_PERMISSIONS =<br>            mutableListOf (<br>                Manifest.permission.CAMERA,<br>                Manifest.permission.RECORD_AUDIO,<br>            ).apply {<br>                if (Build.VERSION.SDK_INT &lt;= Build.VERSION_CODES.P) {<br>                    add(Manifest.permission.WRITE_EXTERNAL_STORAGE)<br>                }<br>            }.toTypedArray()<br>    }<br><br>    private lateinit var viewModel: SharedViewModel<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        viewModel = ViewModelProvider(this).get(SharedViewModel::class.java)<br><br>        if (!allPermissionsGranted()) {<br>            ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)<br>        } else {<br>            viewModel.setPermission(allPermissionsGranted())<br>        }<br><br>        //...<br>    }<br><br>    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array&lt;out String&gt;, grantResults: IntArray) {<br>        super.onRequestPermissionsResult(requestCode, permissions, grantResults)<br>        if (requestCode == REQUEST_CODE_PERMISSIONS) {<br>            viewModel.setPermission(allPermissionsGranted())<br>        }<br>    }<br><br>    private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {<br>        ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED<br>    }<br>}</pre><p>We’ll ask for necessary permissions on app launch but it’s not ideal for production.</p><p><strong><em>Recommended Implementation:</em></strong><em> Generally, you should display a UI explaining to the user the features that will be enabled if they grant permissions for the app to post notifications. This UI should provide the user options to agree or deny, such as </em><strong><em>OK</em></strong><em> and </em><strong><em>No thanks</em></strong><em> buttons. If the user selects </em><strong><em>OK</em></strong><em>, directly request the permission. If the user selects </em><strong><em>No thanks</em></strong><em>, allow the user to continue without notifications.</em></p><h3>Image Capture</h3><pre>class MainFragment : Fragment() {<br>    //...<br><br>    private var imageCapture: ImageCapture? = null<br><br>    private lateinit var cameraExecutor: ExecutorService<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br>        sharedViewModel.isPermissionGranted.observe(viewLifecycleOwner) {<br>            if (it) startCamera()<br>        }<br><br>        _binding.imageCaptureButton.setOnClickListener { capturePhoto() }<br>        _binding.imageSaveButton.setOnClickListener { savePhoto() }<br><br>        cameraExecutor = Executors.newSingleThreadExecutor()<br>    }<br><br>    private fun capturePhoto() {<br>        //...<br>    }<br><br>    private fun savePhoto() {<br>        //...<br>    }<br><br>    private fun startCamera() {<br>        val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())<br><br>        cameraProviderFuture.addListener({<br>            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()<br><br>            val preview = Preview.Builder()<br>                .build()<br>                .also {<br>                    it.setSurfaceProvider(_binding.viewFinder.surfaceProvider)<br>                }<br><br>            imageCapture = ImageCapture.Builder()<br>                .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)<br>                .build()<br><br>            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA<br><br>            try {<br>                // Unbind use cases before rebinding<br>                cameraProvider.unbindAll()<br>                cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)<br>            } catch(exc: Exception) {<br>                Log.e(TAG, &quot;Use case binding failed&quot;, exc)<br>            }<br>        }, ContextCompat.getMainExecutor(requireContext()))<br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        cameraExecutor.shutdown()<br>    }<br>}</pre><p><em>We’ll implement </em><em>savePhoto and </em><em>capturePhoto later.</em></p><blockquote><a href="https://developer.android.com/reference/androidx/camera/lifecycle/ProcessCameraProvider">ProcessCameraProvider</a>, a singleton which can be used to bind the lifecycle of cameras to any <a href="https://developer.android.com/reference/androidx/lifecycle/LifecycleOwner">LifecycleOwner</a> within an application&#39;s process.</blockquote><blockquote>Only a single process camera provider can exist within a process, and it can be retrieved with <a href="https://developer.android.com/reference/androidx/camera/lifecycle/ProcessCameraProvider#getInstance(android.content.Context)">getInstance</a>.</blockquote><p>setCaptureMode, is to configure the capture mode when taking a photo,</p><ul><li>CAPTURE_MODE_MINIMIZE_LATENCY optimize image capture for latency.</li><li>CAPTURE_MODE_MAXIMIZE_QUALITY optimize image capture for image quality.</li></ul><p>The capture mode defaults to CAPTURE_MODE_MINIMIZE_LATENCY.</p><p>Now, we’ll implement savePhoto and capturePhoto. Difference is, savePhoto saves the image to the provided file location but capturePhoto provides in-memory buffer of the captured image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*JgL7aRbMvpNacn94izVOFQ.png" /></figure><h4>Save Photo</h4><pre>private fun savePhoto() {<br>    // If the use case is null, exit out of the function.<br>    // This will be null If we tap the photo button before image capture is set up.<br>    // Without the return statement, the app would crash if it was null.<br>    val imageCapture = imageCapture ?: return<br><br>    val name = SimpleDateFormat(FILENAME_FORMAT, Locale.US)<br>        .format(System.currentTimeMillis())<br>    val contentValues = ContentValues().apply {<br>        put(MediaStore.MediaColumns.DISPLAY_NAME, name)<br>        put(MediaStore.MediaColumns.MIME_TYPE, &quot;image/jpeg&quot;)<br>        if(Build.VERSION.SDK_INT &gt; Build.VERSION_CODES.P) {<br>            put(MediaStore.Images.Media.RELATIVE_PATH, &quot;Pictures/PATH&quot;)<br>        }<br>    }<br><br>    val outputOptions = ImageCapture.OutputFileOptions<br>        .Builder(requireActivity().contentResolver,<br>            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,<br>            contentValues)<br>        .build()<br><br>    imageCapture.takePicture(<br>        outputOptions,<br>        ContextCompat.getMainExecutor(requireContext()),<br>        object : ImageCapture.OnImageSavedCallback {<br>            override fun onError(exc: ImageCaptureException) {<br>                Log.e(TAG, &quot;Photo capture failed: ${exc.message}&quot;, exc)<br>            }<br><br>            override fun onImageSaved(output: ImageCapture.OutputFileResults){<br>                val msg = &quot;Photo capture succeeded: ${output.savedUri}&quot;<br>                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()<br>                Log.d(TAG, msg)<br>            }<br>        }<br>    )<br>}</pre><p>contentValues, creates a MediaStore content value to hold the image. We use a timestamp so the display name in MediaStore will be unique.</p><p>outputOptions, creates output options object which contains file and metadata.</p><p>takePicture(OutputFileOptions, Executor, OnImageSavedCallback), this method saves the captured image to the provided file location.</p><h4>Capture Photo</h4><pre>private fun capturePhoto() {<br>    val imageCapture = imageCapture ?: return<br><br>    imageCapture.takePicture(<br>        ContextCompat.getMainExecutor(requireContext()),<br>        object : ImageCapture.OnImageCapturedCallback() {<br>            override fun onCaptureSuccess(image: ImageProxy) {<br>                super.onCaptureSuccess(image)<br>                parentFragmentManager.beginTransaction()<br>                    .replace(R.id.container, ImageViewFragment.newInstance(image))<br>                    .addToBackStack(null)<br>                    .commit()<br>            }<br>        }<br>    )<br>}</pre><p>takePicture(Executor, OnImageCapturedCallback), this method provides an in-memory buffer of the captured image.</p><p>That’s it. We pass image: ImageProxy to ImageViewFragment and display it to the user.</p><p><em>Note: To display </em><em>ImageProxy as Image, we need to convert it to bitmap.</em></p><pre>fun Image.toBitmap(): Bitmap {<br>    val buffer = planes[0].buffer<br>    buffer.rewind()<br>    val bytes = ByteArray(buffer.capacity())<br>    buffer.get(bytes)<br>    return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)<br>}</pre><h3>Video Capture</h3><pre>class VideoFragment : Fragment() {<br>    //...<br><br>    private var videoCapture: VideoCapture&lt;Recorder&gt;? = null<br>    private var recording: Recording? = null<br><br>    private lateinit var cameraExecutor: ExecutorService<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br>        sharedViewModel.isPermissionGranted.observe(viewLifecycleOwner) {<br>            if (it) startCamera()<br>        }<br><br>        _binding.videoCaptureButton.setOnClickListener { captureVideo() }<br><br>        cameraExecutor = Executors.newSingleThreadExecutor()<br>    }<br><br>    private fun captureVideo() {<br>        //...<br>    }<br><br>    private fun startCamera() {<br>        //...<br><br>        // Video<br>        val recorder = Recorder.Builder()<br>            .setQualitySelector(<br>                QualitySelector.from(<br>                    Quality.HIGHEST,<br>                    FallbackStrategy.higherQualityOrLowerThan(Quality.SD)<br>                )<br>            )<br>            .build()<br>        videoCapture = VideoCapture.withOutput(recorder)<br>        <br>        //...<br>        cameraProvider.bindToLifecycle(this, cameraSelector, preview, videoCapture)<br>    }<br><br>    override fun onDestroy() {<br>        super.onDestroy()<br>        cameraExecutor.shutdown()<br>    }<br>}</pre><p><em>We’ll implement </em><em>captureVideo later.</em></p><p>startCamera is same as what we did in <strong>Image Capture</strong> part. Only difference is, we need to remove imageCapture and add recorder and videoCapture variables.</p><pre>private fun captureVideo() {<br>    val videoCapture = this.videoCapture ?: return<br><br>    _binding.videoCaptureButton.isEnabled = false<br><br>    val curRecording = recording<br>    if (curRecording != null) {<br>        curRecording.stop()<br>        recording = null<br>        return<br>    }<br><br>    val name = SimpleDateFormat(FILENAME_FORMAT, Locale.US)<br>        .format(System.currentTimeMillis())<br>    val contentValues = ContentValues().apply {<br>        put(MediaStore.MediaColumns.DISPLAY_NAME, name)<br>        put(MediaStore.MediaColumns.MIME_TYPE, &quot;video/mp4&quot;)<br>        if (Build.VERSION.SDK_INT &gt; Build.VERSION_CODES.P) {<br>            put(MediaStore.Video.Media.RELATIVE_PATH, &quot;Movies/CameraX-Video&quot;)<br>        }<br>    }<br><br>    val mediaStoreOutputOptions = MediaStoreOutputOptions<br>        .Builder(requireActivity().contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI)<br>        .setContentValues(contentValues)<br>        .build()<br><br>    recording = videoCapture.output<br>        .prepareRecording(requireContext(), mediaStoreOutputOptions)<br>        .apply {<br>            // Enable Audio for recording<br>            if (<br>                PermissionChecker.checkSelfPermission(requireContext(), Manifest.permission.RECORD_AUDIO) ==<br>                PermissionChecker.PERMISSION_GRANTED<br>            ) {<br>                withAudioEnabled()<br>            }<br>        }<br>        .start(ContextCompat.getMainExecutor(requireContext())) { recordEvent -&gt;<br>            when(recordEvent) {<br>                is VideoRecordEvent.Start -&gt; {<br>                    _binding.videoCaptureButton.apply {<br>                        text = getString(R.string.stop_capture)<br>                        isEnabled = true<br>                    }<br>                }<br>                is VideoRecordEvent.Finalize -&gt; {<br>                    if (!recordEvent.hasError()) {<br>                        val msg = &quot;Video capture succeeded: ${recordEvent.outputResults.outputUri}&quot;<br>                        parentFragmentManager.beginTransaction()<br>                            .replace(R.id.container, VideoViewFragment.newInstance(recordEvent.outputResults.outputUri))<br>                            .addToBackStack(null)<br>                            .commit()<br>                        Log.d(TAG, msg)<br>                    } else {<br>                        recording?.close()<br>                        recording = null<br>                        Log.e(TAG, &quot;Video capture ends with error: ${recordEvent.error}&quot;)<br>                    }<br>                    _binding.videoCaptureButton.apply {<br>                        text = getString(R.string.start_capture)<br>                        isEnabled = true<br>                    }<br>                }<br>            }<br>        }<br>}</pre><p>curRecording, if there is an active recording in progress, we stop it and release the current recording. We notify when the captured video file is ready to be used by application.</p><p>To start recording, we create a new recording session. First, we create intended MediaStore video object with system timestamp as the display name.</p><p>.start starts the recording, making it an active recording. Only a single recording can be active at a time.</p><ul><li>Upon successful start, VideoRecordEvent.Start event will be triggered.</li><li>Upon successful recording, VideoRecordEvent.Finalize will be triggered. Also, if error occurs while starting the recording, VideoRecordEvent.Finalize event will be the first event to be triggered. We can access the error with .getError method.</li></ul><p>When we successfully record a video, we can get the saved video’s uri with .outputResults.outputUri.</p><h3>Full Code</h3><p><a href="https://github.com/MrNtlu/Camera-Guide">MrNtlu/Camera-Guide (github.com)</a></p><h3>Sources:</h3><ul><li><a href="https://developer.android.com/training/camerax">CameraX overview | Android Developers</a></li><li><a href="https://developer.android.com/codelabs/camerax-getting-started">https://developer.android.com/codelabs/camerax-getting-started</a></li><li><a href="https://developer.android.com/training/camerax/take-photo">Image capture | Android Developers</a></li><li><a href="https://developer.android.com/training/camerax/video-capture">CameraX video capturing architecture | Android Developers</a></li><li><a href="https://developer.android.com/training/data-storage/shared/photopicker">Photo picker | Android Developers</a></li></ul><p>You can contact me on,</p><ul><li><a href="https://www.linkedin.com/in/burak-fidan/">LinkedIn</a></li><li><a href="https://github.com/MrNtlu">Github</a></li><li><a href="https://twitter.com/BurakFNtlu">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=797f497c0487" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/video-and-image-capture-with-camerax-in-android-797f497c0487">Video and Image Capture with CameraX in Android</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebSockets in Android with OkHttp and ViewModel]]></title>
            <link>https://itnext.io/websockets-in-android-with-okhttp-and-viewmodel-776a9eed67b5?source=rss-a99dac39edcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/776a9eed67b5</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[okhttp]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[androidviewmodel]]></category>
            <dc:creator><![CDATA[Burak]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 09:31:56 GMT</pubDate>
            <atom:updated>2023-01-25T08:05:59.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YdAyUypTpRoLgX8z2zxyeQ.png" /></figure><h4>Table of Contents</h4><ul><li>What is WebSocket?</li><li>PieSocket Setup</li><li>Getting Started</li><li>OkHttp WebSocket Lifecycle</li><li>WebSocket with ViewModel</li></ul><h3>What is WebSocket?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lwkkKGoVhdYpZhMfOo6hAA.png" /></figure><p>WebSocket is bidirectional. It is a stateful protocol, which means the connection between client and server remains alive until it’s terminated by either client or server. WebSocket endpoints starts with ws:// or wss://.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ori9BopVCAUTXhX_JBsV7Q.png" /><figcaption><a href="https://www.wallarm.com/what/a-simple-explanation-of-what-a-websocket-is">Source</a></figcaption></figure><p><strong>Example WebSocket use cases,</strong></p><ul><li><strong>Real-time application:</strong> In WebSocket, data is continuously pushed/transmitted into the same connection which is already open. <br>For e.g. in a trading website or bitcoin trading, for displaying the price fluctuation and movement data is continuously pushed by the backend server to the client end by using a WebSocket channel.</li><li><strong>Gaming application:</strong> In a Gaming application, data is continuously received by the server, and without refreshing the UI, it will take effect on the screen, UI gets automatically refreshed without even establishing the new connection.</li><li><strong>Chat application:</strong> Chat applications use WebSockets to establish the connection only once for exchange, publishing, and broadcasting the message among the subscribers. It reuses the same WebSocket connection, for sending and receiving the message and for one-to-one message transfer.</li></ul><p><a href="https://www.geeksforgeeks.org/what-is-web-socket-and-how-it-is-different-from-the-http/">Read More…</a></p><h3>Getting Started</h3><p>App level build.gradle file,</p><pre>implementation(&quot;com.squareup.okhttp3:okhttp:4.10.0&quot;)</pre><p>Don’t forget to add Internet permission in AndroidManifest.xml,</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><p>We’ll use <a href="https://www.piesocket.com/">PieSocket</a> for testing. You can register and create channel easily. You’ll need Cluseter ID and API Key. <em>You can also click </em><em>Test Online button for sending and receiving messages.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQUA-0TChfkBmJlRADx40g.png" /></figure><h3>OkHttp WebSocket Lifecycle</h3><p>Upon normal operation each web socket progresses through a sequence of states:</p><ul><li><strong>Connecting:</strong> the initial state of each web socket. Messages may be enqueued but they won’t be transmitted until the web socket is open.</li><li><strong>Open:</strong> the web socket has been accepted by the remote peer and is fully operational. Messages in either direction are enqueued for immediate transmission.</li><li><strong>Closing:</strong> one of the peers on the web socket has initiated a graceful shutdown. The web socket will continue to transmit already-enqueued messages but will refuse to enqueue new ones.</li><li><strong>Closed:</strong> the web socket has transmitted all of its messages and has received all messages from the peer.</li></ul><p>Web sockets may fail due to HTTP upgrade problems, connectivity problems, or if either peer chooses to short-circuit the graceful shutdown process:</p><ul><li><strong>Canceled:</strong> the web socket connection failed. Messages that were successfully enqueued by either peer may not have been transmitted to the other.</li></ul><h3>WebSocket with ViewModel</h3><p>First, we’ll create WebSocketListener,</p><pre>class WebSocketListener(<br>    private val viewModel: MainViewModel<br>): WebSocketListener() {<br><br>    private val TAG = &quot;Test&quot;<br><br>    override fun onOpen(webSocket: WebSocket, response: Response) {<br>        super.onOpen(webSocket, response)<br>        viewModel.setStatus(true)<br>        webSocket.send(&quot;Android Device Connected&quot;)<br>        Log.d(TAG, &quot;onOpen:&quot;)<br>    }<br><br>    override fun onMessage(webSocket: WebSocket, text: String) {<br>        super.onMessage(webSocket, text)<br>        viewModel.addMessage(Pair(false, text))<br>        Log.d(TAG, &quot;onMessage: $text&quot;)<br>    }<br><br>    override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {<br>        super.onClosing(webSocket, code, reason)<br>        Log.d(TAG, &quot;onClosing: $code $reason&quot;)<br>    }<br><br>    override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {<br>        super.onClosed(webSocket, code, reason)<br>        viewModel.setStatus(false)<br>        Log.d(TAG, &quot;onClosed: $code $reason&quot;)<br>    }<br><br>    override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {<br>        Log.d(TAG, &quot;onFailure: ${t.message} $response&quot;)<br>        super.onFailure(webSocket, t, response)<br>    }<br>}</pre><p>Since we’ve already checked lifecycle in the previous part, we can implement MainFragment and MainViewModel.</p><pre>class MainViewModel : ViewModel() {<br><br>    private val _socketStatus = MutableLiveData(false)<br>    val socketStatus: LiveData&lt;Boolean&gt; = _socketStatus<br><br>    private val _messages = MutableLiveData&lt;Pair&lt;Boolean, String&gt;&gt;()<br>    val messages: LiveData&lt;Pair&lt;Boolean, String&gt;&gt; = _messages<br><br>    fun addMessage(message: Pair&lt;Boolean, String&gt;) = viewModelScope.launch(Dispatchers.Main) {<br>        if (_socketStatus.value == true) {<br>            _messages.value = message<br>        }<br>    }<br><br>    fun setStatus(status: Boolean) = viewModelScope.launch(Dispatchers.Main) {<br>        _socketStatus.value = status<br>    }<br>}</pre><p>ViewModel is very simple, there is nothing special. We set LiveData values in main thread with Dispatchers.Main and that’s it. _messages is Pair&lt;Boolean, String&gt; because this way we can check if we are the receiver or sender of the message.</p><pre>class MainFragment : Fragment() {<br>    //...<br><br>    private lateinit var webSocketListener: WebSocketListener<br>    private val okHttpClient = OkHttpClient()<br>    private var webSocket: WebSocket? = null<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)<br>        webSocketListener = WebSocketListener(viewModel)<br>    }<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br>        //...<br><br>        viewModel.socketStatus.observe(viewLifecycleOwner) {<br>            statusTV.text = if (it) &quot;Connected&quot; else &quot;Disconnected&quot;<br>        }<br><br>        var text = &quot;&quot;<br>        viewModel.messages.observe(viewLifecycleOwner) {<br>            text += &quot;${if (it.first) &quot;You: &quot; else &quot;Other: &quot;} ${it.second}\n&quot;<br><br>            messageTV.text = text<br>        }<br><br>        connectButton.setOnClickListener {<br>            webSocket = okHttpClient.newWebSocket(createRequest(), webSocketListener)<br>        }<br><br>        disconnectButton.setOnClickListener {<br>            webSocket?.close(1000, &quot;Canceled manually.&quot;)<br>        }<br><br>        sendMessageButton.setOnClickListener {<br>            webSocket?.send(messageET.text.toString())<br>            viewModel.addMessage(Pair(true, messageET.text.toString()))<br>        }<br>    }<br><br>    private fun createRequest(): Request {<br>        val websocketURL = &quot;wss://${Constants.CLUSTER_ID}.piesocket.com/v3/1?api_key=${Constants.API_KEY}&quot;<br><br>        return Request.Builder()<br>            .url(https://medium.com/websocketURL)<br>            .build()<br>    }<br><br>    override fun onDestroyView() {<br>        super.onDestroyView()<br>        okHttpClient.dispatcher.executorService.shutdown()<br>    }<br>}</pre><p>viewModel.socketStatus is to determine if we are connected to socket or not and update statusTV.</p><p><em>I was too lazy to create RecyclerView to show messages</em>, so we’ll just concatenate incoming texts into String and set it into messageTV.</p><p>connectButton creates new socket and connection.</p><p>disconnectButton closes the connection.</p><ul><li>.close Attempts to initiate a graceful shutdown of this web socket. Any already-enqueued messages will be transmitted before the close message is sent but subsequent calls to send will return false and their messages will not be enqueued.</li><li>.cancel Immediately and violently release resources held by this web socket, discarding any enqueued messages. This does nothing if the web socket has already been closed or canceled.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*GLmqHsRmLZrLWEfR5e4QqQ.png" /><figcaption>MainFragment UI</figcaption></figure><p>That’s it! I hope it was useful. 👋👋</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*GCxATdpkcGicSkHw" /></figure><h3>Full Code</h3><p><a href="https://github.com/MrNtlu/WebSocket-Guide">MrNtlu/WebSocket-Guide (github.com)</a></p><h3>Sources:</h3><ul><li><a href="https://www.youtube.com/watch?v=YnvUZ68MZIg&amp;ab_channel=burakselcuk">WEBSOCKET STRUCTURE ANDROID KOTLIN — YouTube</a></li><li><a href="https://square.github.io/okhttp/4.x/okhttp/okhttp3/-web-socket/">WebSocket — OkHttp — OkHttp (square.github.io)</a></li><li><a href="https://www.geeksforgeeks.org/what-is-web-socket-and-how-it-is-different-from-the-http/">What is web socket and how it is different from the HTTP? — GeeksforGeeks</a></li></ul><p>You can contact me on,</p><ul><li><a href="https://www.linkedin.com/in/burak-fidan/">LinkedIn</a></li><li><a href="https://github.com/MrNtlu">Github</a></li><li><a href="https://twitter.com/BurakFNtlu">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=776a9eed67b5" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/websockets-in-android-with-okhttp-and-viewmodel-776a9eed67b5">WebSockets in Android with OkHttp and ViewModel</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FCM Push Notification & Local Notification]]></title>
            <link>https://itnext.io/fcm-push-notification-local-notification-13117f447255?source=rss-a99dac39edcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/13117f447255</guid>
            <category><![CDATA[android-push-notification]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-fcm]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-notification]]></category>
            <dc:creator><![CDATA[Burak]]></dc:creator>
            <pubDate>Wed, 18 Jan 2023 11:18:21 GMT</pubDate>
            <atom:updated>2023-01-24T11:46:21.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C1cCEfAcI51P9H_h4I0iEQ.png" /></figure><p>In this article, we’ll implement Firebase Cloud Messaging (FCM) for push notification and local notification.</p><h4>Table of Contents</h4><ul><li><a href="#8ef4">Getting Started</a></li><li><a href="#c161">Firebase Cloud Messaging (FCM) Setup</a><br>- <a href="#42e6">Permissions and FCM Token</a></li><li><a href="#c2a5">FCM Notification</a></li><li><a href="#e2d4">Local Notification</a><br>- <a href="#8d4d">Local Notification w/Big Text</a><br>- <a href="#da38">Local Notification w/Action &amp; Broadcast Receiver</a></li></ul><h3>Getting Started</h3><p>Top level build.gradle file,</p><pre>buildscript {<br>    dependencies {<br>        classpath &#39;com.google.gms:google-services:4.3.14&#39;<br>    }<br>}<br><br>plugins {<br>    id &#39;com.android.application&#39; version &#39;7.3.1&#39; apply false<br>    id &#39;com.android.library&#39; version &#39;7.3.1&#39; apply false<br>    id &#39;org.jetbrains.kotlin.android&#39; version &#39;1.7.20&#39; apply false<br>}</pre><p>App level build.gradle file,</p><pre>implementation platform(&#39;com.google.firebase:firebase-bom:31.1.1&#39;)<br>implementation &#39;com.google.firebase:firebase-analytics-ktx&#39;<br>implementation &#39;com.google.firebase:firebase-messaging-ktx&#39;</pre><p>Finally, we’ll create extension functions that we’ll use later.</p><pre>fun Context.setNotification(<br>    channelId: String,<br>    title: String?,<br>    body: String?,<br>    soundUri: Uri?,<br>    groupId: String?,<br>    pendingIntent: PendingIntent,<br>): NotificationCompat.Builder {<br>    val notification = NotificationCompat.Builder(this, channelId)<br>        .setSmallIcon(R.drawable.ic_stat_test)<br>        .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.ic_stat_test))<br>        .setColor(ContextCompat.getColor(applicationContext, R.color.notification))<br>        .setContentTitle(title)<br>        .setContentText(body)<br>        .setAutoCancel(true)<br>        .setSound(soundUri)<br>        .setGroupSummary(false)<br><br>    if (groupId != null)<br>        notification.setGroup(groupId)<br><br>    notification.setContentIntent(pendingIntent)<br><br>    return notification<br>}<br><br>fun Context.setGroupNotification(<br>    channelId: String,<br>    groupId: String,<br>    groupSummary: Boolean,<br>    lineText: String,<br>    bigContentTitle: String,<br>    summaryText: String,<br>): Notification = NotificationCompat.Builder(this, channelId)<br>    .setSmallIcon(R.drawable.ic_stat_test)<br>    .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.ic_stat_test))<br>    .setColor(ContextCompat.getColor(applicationContext, R.color.notification))<br>    .setStyle(<br>        NotificationCompat.InboxStyle()<br>            .addLine(lineText)<br>            .setBigContentTitle(bigContentTitle)<br>            .setSummaryText(summaryText)<br>    )<br>    .setGroup(groupId)<br>    .setGroupSummary(groupSummary)<br>    .setAutoCancel(true)<br>    .build()</pre><p>setNotification,</p><ul><li><a href="https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setSmallIcon(int)">setSmallIcon()</a> this is the only user-visible content that&#39;s required.</li><li><a href="https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setAutoCancel(boolean)">setAutoCancel()</a> should notification automatically be canceled when user clicks.</li><li><a href="https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setGroup(java.lang.String)">setGroup()</a> sets this notification to be part of a group of notifications sharing the same key.</li><li><a href="https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setGroupSummary(boolean)">setGroupSummary()</a> whether this notification should be a group summary.<em> You can </em><a href="https://developer.android.com/develop/ui/views/notifications/group#group-summary"><em>read more</em></a><em> about it.</em></li></ul><p>setGroupNotification is to help notification grouping. In case of multiple related notifications being stacked, we’ll group them with this function.</p><h3>Firebase Cloud Messaging (FCM) Setup</h3><p><em>Before we start, create Firebase project for your app and add the </em><em>google-services.json file if you haven’t already. </em><a href="https://firebase.google.com/docs/android/setup"><em>Firebase setup link</em></a></p><p>AndroidManifest.xml,</p><pre>&lt;uses-permission android:name=&quot;android.permission.POST_NOTIFICATIONS&quot;/&gt;<br><br>&lt;application<br>        //... &gt;<br>        &lt;activity<br>            android:name=&quot;.MainActivity&quot;<br>            android:exported=&quot;true&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br><br>                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>            &lt;/intent-filter&gt;<br><br>            &lt;meta-data<br>                android:name=&quot;android.app.lib_name&quot;<br>                android:value=&quot;&quot; /&gt;<br>        &lt;/activity&gt;<br><br>        &lt;!-- [START fcm_default_icon] --&gt;<br>        &lt;meta-data<br>            android:name=&quot;com.google.firebase.messaging.default_notification_icon&quot;<br>            android:resource=&quot;@drawable/ic_stat_test&quot; /&gt;<br>        &lt;meta-data<br>            android:name=&quot;com.google.firebase.messaging.default_notification_color&quot;<br>            android:resource=&quot;@color/notification&quot; /&gt;<br>        &lt;!-- [END fcm_default_icon] --&gt;<br><br>        &lt;!-- [START fcm_default_channel] --&gt;<br>        &lt;meta-data<br>            android:name=&quot;com.google.firebase.messaging.default_notification_channel_id&quot;<br>            android:value=&quot;@string/notification_channel_id&quot; /&gt;<br>        &lt;!-- [END fcm_default_channel] --&gt;<br><br>        &lt;!-- [START firebase_service] --&gt;<br>        &lt;service<br>            android:name=&quot;.service.FirebaseMessagingService&quot;<br>            android:exported=&quot;false&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;com.google.firebase.MESSAGING_EVENT&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/service&gt;<br>        &lt;!-- [END firebase_service] --&gt;<br><br>        &lt;!-- [START broadcast_receiver] --&gt;<br>        &lt;receiver android:name=&quot;.service.NotificationActionBroadcastReceiver&quot;/&gt;<br>    &lt;/application&gt;</pre><p>fcm_default_icon, you can set the notification icon and icon background color in here. <em>You can use </em><a href="https://romannurik.github.io/AndroidAssetStudio/icons-notification.html"><em>this link</em></a><em> to generate notification icon.</em></p><blockquote>Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. <a href="https://developer.android.com/develop/ui/views/notifications#ManageChannels">Reference</a></blockquote><p>fcm_default_channel, we set the notification channel id.</p><p>We’ll implement and explain firebase_service and broadcast_receiver later.</p><h4>Permissions and FCM Token</h4><p><em>FCM Token is necessary if you want to target single device.</em></p><p>Now, we need to ask for notification permission from the user and retrieve the FCM token. We’ll ask permission as soon as user launches the application but it’s not the recommended way.</p><p><strong><em>Recommended Implementation:</em></strong><em> Generally, you should display a UI explaining to the user the features that will be enabled if they grant permissions for the app to post notifications. This UI should provide the user options to agree or deny, such as </em><strong><em>OK</em></strong><em> and </em><strong><em>No thanks</em></strong><em> buttons. If the user selects </em><strong><em>OK</em></strong><em>, directly request the permission. If the user selects </em><strong><em>No thanks</em></strong><em>, allow the user to continue without notifications.</em></p><p>Now we can start the implementation. We’ll ask for permission and retrieve token in MainActivity.kt,</p><pre>private val requestPermissionLauncher = registerForActivityResult(<br>    ActivityResultContracts.RequestPermission()<br>) { isGranted: Boolean -&gt;<br>    if (isGranted) {<br>        // FCM SDK (and your app) can post notifications.<br>        Log.d(TAG, &quot;Granted&quot;)<br>    } else {<br>        // TODO: Inform user that that your app will not show notifications.<br>        Log.d(TAG, &quot;Failed&quot;)<br>    }<br>}<br><br>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    //...<br><br>    getFCMToken()<br>    askNotificationPermission()<br>}<br><br>private fun getFCMToken() {<br>    FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task -&gt;<br>        if (!task.isSuccessful) {<br>            Log.d(TAG, &quot;Fetching FCM registration token failed&quot;, task.exception)<br>            return@OnCompleteListener<br>        }<br><br>        // Get new FCM registration token<br>        val token = task.result<br><br>        Log.d(TAG, &quot;Token is $token&quot;)<br>    })<br>}<br><br>private fun askNotificationPermission() {<br>    // This is only necessary for API level &gt;= 33 (TIRAMISU)<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>        if (ContextCompat.checkSelfPermission(this, POST_NOTIFICATIONS) ==<br>            PackageManager.PERMISSION_GRANTED<br>        ) {<br>            // FCM SDK (and your app) can post notifications.<br>        } else if (shouldShowRequestPermissionRationale(POST_NOTIFICATIONS)) {<br>            // TODO: Display UI Here<br>        } else {<br>            // Directly ask for the permission<br>            requestPermissionLauncher.launch(POST_NOTIFICATIONS)<br>        }<br>    }<br>}</pre><h3>FCM Notification</h3><blockquote>Firebase notifications behave differently depending on the foreground/background state of the receiving app. If you want foregrounded apps to receive notification messages or data messages, you’ll need to use a service that extends <a href="https://firebase.google.com/docs/reference/android/com/google/firebase/messaging/FirebaseMessagingService">FirebaseMessagingService</a>.</blockquote><p>Now, we’ll create FirebaseMessagingService,</p><pre>class FirebaseMessagingService: FirebaseMessagingService() {<br><br>    companion object {<br>        const val CHANNEL_NAME = &quot;Test Notification&quot;<br>        const val GROUP_NAME = &quot;Test Group Notification&quot;<br>        const val GROUP_ID = &quot;test.notification&quot;<br><br>        const val PATH_EXTRA = &quot;path&quot;<br>        const val DATA_EXTRA = &quot;data&quot;<br>    }<br><br>    override fun onNewToken(token: String) {<br>        super.onNewToken(token)<br><br>        handleNewToken(token)<br>    }<br><br>    private fun handleNewToken(token: String) {<br>        Log.d(TAG, &quot;handleNewToken: $token&quot;)<br>    }<br><br>    override fun onMessageReceived(remoteMessage: RemoteMessage) {<br>        // Check if message contains a data payload.<br>        if (remoteMessage.data.isNotEmpty()) {<br>            Log.d(TAG, &quot;Message data payload: ${remoteMessage.data}&quot;)<br>        }<br><br>        // Check if message contains a notification payload.<br>        remoteMessage.notification?.let {<br>            Log.d(TAG, &quot;Message Notification Body: ${it.body}&quot;)<br>            sendNotification(it.title, it.body, remoteMessage.data)<br>        }<br>    }<br><br>    private fun sendNotification(<br>        title: String?,<br>        messageBody: String?,<br>        data: Map&lt;String, String&gt;<br>    ) {<br>        val intent = Intent(this, MainActivity::class.java)<br>        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP<br><br>        for (i in 0 until data.size) {<br>            val key = data.keys.toList()[i]<br>            val value = data.values.toList()[i]<br>            intent.putExtra(key, value)<br>        }<br><br>        val pendingIntent = PendingIntent.getActivity(<br>            this, 0, intent,<br>            PendingIntent.FLAG_IMMUTABLE<br>        )<br><br>        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)<br><br>        val channelId = getString(R.string.notification_channel_id)<br>        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager<br><br>        val notification = setNotification(<br>            channelId,<br>            title,<br>            messageBody,<br>            defaultSoundUri,<br>            GROUP_ID,<br>            pendingIntent<br>        )<br><br>        val groupNotification = setGroupNotification(<br>            channelId,<br>            GROUP_ID,<br>            true,<br>            &quot;$title $messageBody&quot;,<br>            &quot;New Notifications&quot;,<br>            &quot;Notifications Grouped&quot;<br>        )<br><br>        //ID of notification<br>        notificationManager.notify(System.currentTimeMillis().toInt(), notification.build())<br>        notificationManager.notify(0, groupNotification)<br>    }<br>}</pre><p>onNewToken is called if the FCM token is updated. <em>Also note that this is called when the FCM registration token is initially generated so this is where you would retrieve the token.</em></p><p>handleNewToken, after obtaining the token, in an ideal scenario we can send FCM Token to backend and store it.</p><p><a href="https://firebase.google.com/docs/reference/android/com/google/firebase/messaging/FirebaseMessagingService#onMessageReceived(com.google.firebase.messaging.RemoteMessage)">onMessageReceived</a> is called when a notification message is received while the app is in the foreground.</p><blockquote>When your app is in the background, <a href="https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages">notification messages</a> are displayed in the system tray, and onMessageReceived is not called. For notification messages with a data payload, the notification message is displayed in the system tray, and the data that was included with the notification message can be retrieved from the intent launched when the user taps on the notification.</blockquote><p>sendNotification, creates and shows a simple notification containing the received FCM message.</p><ul><li>pendingIntent is for tap action. Every notification should respond to a tap, usually to open an activity in your app that corresponds to the notification.</li><li>With the help of extension functions that we’ve created earlier, we set notification and notify the notificationManager.</li><li>notificationManager.notify(ID, notification), ID is very important. If notification ids are the same, it overwrites the previous notification. Since we don’t have any unique id for notification or we don’t pass id with notification data, we’ll use System.currentTimeMillis.</li><li>Finally, we put incoming data to intent via .putExtra(key, value).</li></ul><p>Let’s retrieve the data in MainActivity,</p><pre>class MainActivity : AppCompatActivity() {<br>    //...<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        //...<br><br>        handleIntentData(intent?.extras)<br><br>        getFCMToken()<br>        askNotificationPermission()<br>    }<br><br>    override fun onNewIntent(intent: Intent?) {<br>        super.onNewIntent(intent)<br><br>        handleIntentData(intent?.extras)<br>    }<br><br>    private fun handleIntentData(extras: Bundle?) {<br>        if (extras != null) {<br>            val data = extras.getString(DATA_EXTRA)<br><br>            when(extras.getString(PATH_EXTRA)) {<br>                &quot;dashboard&quot; -&gt; {<br>                    navController.navigate(R.id.action_global_navigation_dashboard, bundleOf(<br>                        DATA_EXTRA to data<br>                    ))<br>                }<br>            }<br>        }<br>    }<br><br>    //...<br>}</pre><blockquote><a href="https://developer.android.com/reference/android/app/Activity#onNewIntent(android.content.Intent)">onNewIntent</a>, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.</blockquote><p>handleIntentData will retrieve the data that notification has. In our case, we are expecting two data, DATA_EXTRA and PATH_EXTRA.</p><ul><li>PATH_EXTRA will be used for navigation. If data is set to &quot;dashboard&quot; we’ll navigate to DashboardFragment.</li><li>DATA_EXTRA is any other data that we can pass for DashboardFragment. In our case, it’s string. We’ll pass it while navigating with bundleOf. To retrieve the DATA_EXTRA in DashboardFragment,</li></ul><pre>class DashboardFragment : Fragment() {<br>    //...<br><br>    private var data: String? = null<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        arguments?.let {<br>            data = it.getString(DATA_EXTRA)<br>        }<br>    }<br><br>    //...<br>}</pre><p>It’s that simple.</p><h3>Local Notification</h3><h4>Local Notification w/Big Text</h4><pre>class NotificationsFragment : Fragment() {<br>    //...<br><br>    private val notificationManager by lazy { context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager }<br><br>    private val redirectChannelId = 1<br>    private val actionChannelID = 2<br><br>    private fun sendLocalTestNotificationWithRedirect() {<br>        val intent = Intent(context, MainActivity::class.java)<br>        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP<br><br>        intent.putExtra(PATH_EXTRA, &quot;dashboard&quot;)<br><br>        val pendingIntent = PendingIntent.getActivity(<br>            context, 0, intent,<br>            if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else PendingIntent.FLAG_UPDATE_CURRENT<br>        )<br><br>        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)<br>        val notification = context?.setNotification(<br>            getString(R.string.notification_channel_id),<br>            &quot;Local Notification Ch 1&quot;,<br>            getString(R.string.short_text),<br>            defaultSoundUri,<br>            null,<br>            pendingIntent<br>        )<br><br>        notification?.apply {<br>            setStyle(<br>                NotificationCompat.BigTextStyle()<br>                    .bigText(getString(R.string.long_text))<br>            )<br>        }<br><br>        notificationManager.notify(redirectChannelId, notification?.build())<br>    }<br>}</pre><p>This notification is very simple, it’s similar to what we’ve already done.</p><ul><li><a href="https://developer.android.com/reference/android/content/Intent#FLAG_ACTIVITY_NEW_TASK">FLAG_ACTIVITY_NEW_TASK</a>, this activity will become the start of a new task on this history stack.</li><li><a href="https://developer.android.com/reference/android/content/Intent#FLAG_ACTIVITY_SINGLE_TOP">FLAG_ACTIVITY_SINGLE_TOP</a>, the activity will not be launched if it is already running at the top of the history stack.</li><li>We’ll use putExtra to add tap action.</li><li><a href="https://developer.android.com/reference/android/app/PendingIntent#FLAG_MUTABLE">FLAG_MUTABLE</a>, flag indicating that the created PendingIntent should be mutable.</li><li><a href="https://developer.android.com/reference/android/app/PendingIntent#FLAG_UPDATE_CURRENT">FLAG_UPDATE_CURRENT</a>, flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.</li><li>.bigText will add expandable big text like the image below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*GizsuWAesMv6PeHfjke8fA.png" /></figure><h4>Local Notification w/Action &amp; Broadcast Receiver</h4><p>Before we set notification, let’s implement Broadcast Receiver,</p><blockquote>Android apps can send or receive broadcast messages from the Android system and other Android apps, similar to the <a href="https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern">publish-subscribe</a> design pattern. These broadcasts are sent when an event of interest occurs.</blockquote><pre>class NotificationActionBroadcastReceiver: BroadcastReceiver() {<br>    companion object {<br>        const val CHANNEL_ID_EXTRA = &quot;channel_id&quot;<br><br>        const val FIRST_ACTION = &quot;first&quot;<br>        const val FIRST_ACTION_EXTRA = &quot;first_extra&quot;<br><br>        const val TEXT_ACTION = &quot;text&quot;<br>    }<br><br>    override fun onReceive(context: Context?, intent: Intent?) {<br>        val channelId = intent?.extras?.getInt(CHANNEL_ID_EXTRA) ?: 0<br>        val firstActionExtra = intent?.extras?.getString(FIRST_ACTION_EXTRA)<br><br>        when(intent?.action) {<br>            FIRST_ACTION -&gt; {<br>                if (firstActionExtra != null) {<br>                    context?.let {<br>                        val notificationManager = it.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager<br><br>                        val pendingIntent = PendingIntent.getActivity(<br>                            it, 0, intent,<br>                            if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else PendingIntent.FLAG_UPDATE_CURRENT<br>                        )<br>                        val newNotification = it.setNotification(<br>                            it.getString(R.string.notification_channel_id),<br>                            &quot;Action&quot;,<br>                            &quot;Data is, $firstActionExtra&quot;,<br>                            null, null, pendingIntent<br>                        )<br><br>                        notificationManager.notify(channelId, newNotification.build())<br>                    }<br>                }<br>            }<br>            TEXT_ACTION -&gt; {<br>                if (getMessageText(intent) != null) {<br>                    context?.let {<br>                        val notificationManager = it.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager<br><br>                        val pendingIntent = PendingIntent.getActivity(<br>                            it, 0, intent,<br>                            if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else PendingIntent.FLAG_UPDATE_CURRENT<br>                        )<br>                        val newNotification = it.setNotification(<br>                            it.getString(R.string.notification_channel_id),<br>                            &quot;Success, message sent!&quot;,<br>                            getMessageText(intent).toString(),<br>                            null, null, pendingIntent<br>                        )<br><br>                        notificationManager.notify(channelId, newNotification.build())<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>    private fun getMessageText(intent: Intent): CharSequence? {<br>        return RemoteInput.getResultsFromIntent(intent)?.getCharSequence(TEXT_ACTION)<br>    }<br>}</pre><p>onReceive, we’ll receive channelId and firstActionExtra in Broadcast Receiver. Finally, we’ll check action type with intent?.action ,</p><ul><li>FIRST_ACTION is to handle simple action press on notification. In our example, we’ll retrieve the firstActionExtra data, overwrite current notification and show new notification with firstActionExtra.</li><li>TEXT_ACTION is for handling reply function. getMessageText will retrieve the sent message, overwrite current notification and show new notification with getMessageText.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*kghEiO8vbr9UIfB1vO6MNA.png" /><figcaption>Actions</figcaption></figure><pre>class NotificationsFragment : Fragment() {<br>    //...<br><br>    private val notificationManager by lazy { context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager }<br><br>    private val redirectChannelId = 1<br>    private val actionChannelID = 2<br><br>    private fun sendLocalTestNotificationWithRedirect() {<br>        //...<br>    }<br><br>    private fun sendLocalTestNotificationWithAction() {<br>        val intent = Intent(context, MainActivity::class.java)<br>        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP<br><br>        intent.putExtra(PATH_EXTRA, &quot;dashboard&quot;)<br><br>        val pendingIntent = PendingIntent.getActivity(<br>            context, 0, intent,<br>            if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else PendingIntent.FLAG_UPDATE_CURRENT<br>        )<br><br>        //Redirect Action<br>        val actionIntent = Intent(context, NotificationActionBroadcastReceiver::class.java).apply {<br>            action = FIRST_ACTION<br>            putExtra(FIRST_ACTION_EXTRA, &quot;Action Extra&quot;)<br>            putExtra(CHANNEL_ID_EXTRA, actionChannelID)<br>        }<br>        val actionPendingIntent = PendingIntent.getBroadcast(<br>            context, 0, actionIntent, if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else PendingIntent.FLAG_UPDATE_CURRENT<br>        )<br><br>        //Reply Action<br>        val remoteInput = RemoteInput.Builder(TEXT_ACTION).run {<br>            setLabel(&quot;Text Input&quot;)<br>            build()<br>        }<br>        val replyIntent = Intent(context, NotificationActionBroadcastReceiver::class.java).apply {<br>            action = TEXT_ACTION<br>            putExtra(CHANNEL_ID_EXTRA, actionChannelID)<br>        }<br>        val replyPendingIntent = PendingIntent.getBroadcast(<br>            context,<br>            10, //message id<br>            replyIntent,<br>            if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S) PendingIntent.FLAG_MUTABLE else PendingIntent.FLAG_UPDATE_CURRENT<br>        )<br><br>        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)<br>        val notification = context?.setNotification(<br>            getString(R.string.notification_channel_id),<br>            &quot;Local Notification Ch 2&quot;,<br>            &quot;Notification with action&quot;,<br>            defaultSoundUri,<br>            null,<br>            pendingIntent<br>        )<br><br>        notification?.apply {<br>            addAction(R.drawable.ic_dashboard_black_24dp, &quot;Action&quot;, actionPendingIntent)<br>            addAction(<br>                NotificationCompat.Action.Builder(<br>                    R.drawable.ic_stat_test, &quot;Reply&quot;, replyPendingIntent<br>                ).addRemoteInput(remoteInput).build()<br>            )<br>        }<br><br>        notificationManager.notify(actionChannelID, notification?.build())<br>    }<br>}</pre><p>In Redirect Action, we set action as FIRST_ACTION and send extra variables.</p><p>In Reply Action, again we set action and send extras. We use getBroadcast to retrieve a PendingIntent that will perform a broadcast.</p><p>Finally, we set the actions with addAction.</p><ul><li>For reply action, we pass remoteInput that we’ve created. A RemoteInput object specifies input to be collected from a user to be passed along with an intent inside a <a href="https://developer.android.com/reference/android/app/PendingIntent">PendingIntent</a> that is sent.</li></ul><p>That’s it! I hope it was useful. 👋👋</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*8V1lPrkhhgL4njho" /></figure><h3>Full Code</h3><p><a href="https://github.com/MrNtlu/Notification-Guide">MrNtlu/Notification-Guide: FCM &amp; Local Notification (github.com)</a></p><h3>Sources:</h3><ul><li><a href="https://developer.android.com/develop/ui/views/notifications/notification-permission#declare">Notification runtime permission | Android Developers</a></li><li><a href="https://developer.android.com/develop/ui/views/notifications">Notifications Overview | Android Developers</a></li><li><a href="https://firebase.google.com/docs/cloud-messaging/android/client#kotlin+ktx">Set up a Firebase Cloud Messaging client app on Android (google.com)</a></li><li><a href="https://developer.android.com/guide/components/broadcasts">Broadcasts overview | Android Developers</a></li><li><a href="https://developer.android.com/reference/android/app/PendingIntent">PendingIntent | Android Developers</a></li><li><a href="https://youtu.be/LP623htmWcI">https://youtu.be/LP623htmWcI</a></li><li><a href="https://stackoverflow.com/questions/3595232/android-remove-notification-from-notification-bar">Android: remove notification from notification bar — Stack Overflow</a></li><li><a href="https://stackoverflow.com/questions/39383157/how-to-open-particular-fragment-on-the-click-of-the-push-notification-message">android — How to open particular fragment on the click of the push notification message? — Stack Overflow</a></li><li><a href="https://developer.android.com/develop/ui/views/notifications/navigation">Start an Activity from a Notification | Android Developers</a></li><li><a href="https://developer.android.com/develop/ui/views/notifications/build-notification">Create a Notification | Android Developers</a></li></ul><p>You can contact me on,</p><ul><li><a href="https://www.linkedin.com/in/burak-fidan/">LinkedIn</a></li><li><a href="https://github.com/MrNtlu">Github</a></li><li><a href="https://twitter.com/BurakFNtlu">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13117f447255" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/fcm-push-notification-local-notification-13117f447255">FCM Push Notification &amp; Local Notification</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Process Death & Orientation Change in RecyclerView]]></title>
            <link>https://proandroiddev.com/process-death-orientation-change-in-recyclerview-8f9c902e491b?source=rss-a99dac39edcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f9c902e491b</guid>
            <category><![CDATA[recyclerview-in-android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-recyclerview]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[orientation-change]]></category>
            <dc:creator><![CDATA[Burak]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 12:54:22 GMT</pubDate>
            <atom:updated>2023-01-12T14:45:06.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0l-zDewW-ti12c1UGBHQCw.png" /></figure><p>This will be Part 2 of <strong>Everything You Need to Know About RecyclerView.</strong></p><p><a href="https://proandroiddev.com/everything-you-need-to-know-about-recyclerview-577bf9248298">Everything You Need to Know About RecyclerView</a></p><p>In this article, we’ll learn how to use savedStateHandle for Process Death and Orientation Change in RecyclerView.</p><h3>Getting Started</h3><h4>Process Death</h4><blockquote>As the system runs low on memory, it kills processes in the cache beginning with the process least recently used. When the user navigates back to the app, the system will restart the app in a new process.</blockquote><blockquote>Since this only happens if the user has not interacted with the app for a while, it <em>might</em> be permissible to have them return to the app and find it in the initial state.</blockquote><p>I recommend you to check these article and video to understand it better.</p><ul><li><a href="https://developer.android.com/codelabs/android-lifecycles#6">Incorporate Lifecycle-Aware Components | Android Developers</a></li><li><a href="https://www.youtube.com/watch?v=xGcZI4oDCtc">Learn Android Process Death in 6min — YouTube</a></li></ul><h4>Orientation Change</h4><blockquote>Some device configurations can change during runtime, such as screen orientation. When such a change occurs, Android restarts the running <a href="https://developer.android.com/reference/android/app/Activity">Activity</a> The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that match the new device configuration.</blockquote><p>To handle orientation change properly, we need to restore its previous state. For that, we’ll take advantage of <a href="https://developer.android.com/reference/android/app/Activity#onsaveinstancestate">onSaveInstanceState()</a> and ViewModel.</p><p>First of all, we cannot save large sets of data into our system as the <a href="https://developer.android.com/guide/topics/resources/runtime-changes#RetainingAnObject">documentation</a> states.</p><blockquote>… it is not designed to carry large objects (such as bitmaps) and the data within it must be serialized then deserialized on the main thread, which can consume a lot of memory and make the configuration change slow.</blockquote><p>So, what we’ll do is, we’ll take advantage of ViewModel. ViewModel objects are preserved across configuration changes, so they are the perfect place to keep UI data without having to query them again.</p><h3>Minor Code Changes</h3><p>We’ll work on our previous code base from <strong>Everything You Need to Know About RecyclerView</strong>. Before we do any implementation, we’ll need to make some changes.</p><pre>sealed class NetworkResponse&lt;out T&gt; {<br>    data class Loading(<br>        val isPaginating: Boolean = false,<br>    ): NetworkResponse&lt;Nothing&gt;()<br><br>    data class Success&lt;out T&gt;(<br>        val data: T,<br>        val isPaginationData: Boolean = false,<br>        val isPaginationExhausted: Boolean = false,<br>    ): NetworkResponse&lt;T&gt;()<br><br>    data class Failure(<br>        val errorMessage: String,<br>    ): NetworkResponse&lt;Nothing&gt;()<br>}</pre><p>In NetworkResponse, we’ll move handling PaginationExhaust task to Success because previously, in case of orientation change on PaginationExhaust, ViewModel was keeping the state value as Failure which causes empty list after the orientation change.</p><p>We’ll also need to make small adjustments in other classes.</p><pre>class MainRepository {<br>    //...<br><br>    fun fetchData(page: Int): Flow&lt;NetworkResponse&lt;ArrayList&lt;RecyclerViewModel&gt;&gt;&gt; = flow {<br>        emit(NetworkResponse.Loading(page != 1))<br><br>        kotlinx.coroutines.delay(2000L)<br><br>        try {<br>            if (page == 1)<br>                emit(NetworkResponse.Success(tempList.toList() as ArrayList&lt;RecyclerViewModel&gt;))<br>            else {<br>                val tempPaginationList = arrayListOf&lt;RecyclerViewModel&gt;().apply {<br>                    for (i in 0..PAGE_SIZE) {<br>                        add(RecyclerViewModel(UUID.randomUUID().toString(), &quot;Content ${i * 2}&quot;),)<br>                    }<br>                }<br><br>                if (page &lt; 4) {<br>                    emit(NetworkResponse.Success(<br>                        tempPaginationList,<br>                        isPaginationData = true,<br>                    ))<br>                } else {<br>                    // CHANGE<br>                    emit(NetworkResponse.Success(<br>                        arrayListOf(),<br>                        isPaginationData = true,<br>                        isPaginationExhausted = true<br>                    ))<br>                }<br>            }<br>        } catch (e: Exception) {<br>            // CHANGE<br>            if (page != 1) {<br>                emit(NetworkResponse.Success(<br>                    arrayListOf(),<br>                    isPaginationData = true,<br>                    isPaginationExhausted = true<br>                ))<br>            } else {<br>                emit(NetworkResponse.Failure(<br>                    e.message ?: e.toString(),<br>                ))<br>            }<br>        }<br>    }.flowOn(Dispatchers.IO)<br>}</pre><p>We’ve changed NetworkResponse.Failure to NetworkResponse.Success with empty list and isPaginationExhausted = true. We are sending empty list since we have no data left to paginate. <em>It can be changed depending on your endpoint&#39;s behavior.</em></p><pre>abstract class BaseAdapter&lt;T&gt;(open val interaction: Interaction&lt;T&gt;): RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt;() {<br>    //...<br><br>    fun setErrorView(errorMessage: String) {<br>        setState(RecyclerViewEnum.Error)<br>        this.errorMessage = errorMessage<br>        notifyDataSetChanged()<br>    }<br><br>    fun setData(<br>        newList: ArrayList&lt;T&gt;,<br>        isPaginationData: Boolean = false,<br>        isPaginationExhausted: Boolean = false<br>    ) {<br>        setState(if (isPaginationExhausted) RecyclerViewEnum.PaginationExhaust else RecyclerViewEnum.View)<br><br>        if (!isPaginationData) {<br>            if (arrayList.isNotEmpty())<br>                arrayList.clear()<br>            arrayList.addAll(newList)<br>            notifyDataSetChanged()<br>        } else {<br>            notifyItemRemoved(itemCount)<br><br>            newList.addAll(0, arrayList)<br>            handleDiffUtil(newList)<br>        }<br>    }<br>}</pre><p>Finally, in BaseAdapter we’ll change setErrorView and setData functions. setErrorView isn’t going to be responsible from PaginationExhaust. It’ll only update if there is an error.</p><p>In setData, we add isPaginationExhausted parameter and use it for setState function. And that’s it.</p><h3>Process Death &amp; Orientation Change</h3><p>Now, we are ready to implement <strong>Process Death</strong> and <strong>Orientation Change</strong>.</p><pre>// Key Values<br>const val PAGE_KEY = &quot;rv.page&quot;<br>const val SCROLL_POSITION_KEY = &quot;rv.scroll_position&quot;<br><br>class MainViewModel(<br>    private val savedStateHandle: SavedStateHandle<br>) : ViewModel() {<br>    // Other Variables<br>    // ...<br><br>    /** Process Death Restore<br>     * isRestoringData is necessary to handle recyclerview.scrollToPosition<br>     * scrollPosition is middle item&#39;s position on recyclerview<br>     */<br>    var isRestoringData = false<br>    private var page: Int = savedStateHandle[PAGE_KEY] ?: 1<br>    var scrollPosition: Int = savedStateHandle[SCROLL_POSITION_KEY] ?: 0<br>        private set<br><br>    // Variable for detecting orientation change<br>    var didOrientationChange = false<br><br>    init {<br>        if (page != 1) {<br>            restoreData()<br>        } else {<br>            fetchData()<br>        }<br>    }<br><br>    private fun restoreData() {<br>        isRestoringData = true<br><br>        var isPaginationExhausted = false<br>        val tempList = arrayListOf&lt;RecyclerViewModel&gt;()<br>        viewModelScope.launch(Dispatchers.IO) {<br>            for (p in 1..page) {<br>                val job = launch(Dispatchers.IO) {<br>                    repository.fetchData(p).collect { state -&gt;<br>                        if (state is NetworkResponse.Success) {<br>                            tempList.addAll(state.data)<br>                            isPaginationExhausted = state.isPaginationExhausted<br>                        }<br>                    }<br>                }<br>                job.join()<br>            }<br>            withContext(Dispatchers.Main) {<br>                _rvList.value = NetworkResponse.Success(tempList, isPaginationData = true, isPaginationExhausted = isPaginationExhausted)<br>            }<br>        }<br>    }<br><br>    private fun setPagePosition(newPage: Int) {<br>        page = newPage<br>        savedStateHandle[PAGE_KEY] = newPage<br>    }<br><br>    fun setScrollPosition(newPosition: Int) {<br>        if (!isRestoringData &amp;&amp; !didOrientationChange) {<br>            scrollPosition = newPosition<br>            savedStateHandle[SCROLL_POSITION_KEY] = newPosition<br>        }<br>    }<br>    <br>    // Other Functions<br>    // ...<br>}</pre><blockquote>SavedStateHandle is a key-value map that will let you write and retrieve objects to and from the saved state. These values will persist after the process is killed by the system and remain available via the same object.</blockquote><p>In ViewModel, we pass savedStateHandle in constructor.</p><p>isRestoringData and didOrientationChange is necessary to return to previous scroll positions.</p><p>In page and scrollPosition, if we’ve saved the values in savedStateHandle we receive them otherwise we return default values.</p><p>restoreData make requests to our “endpoint” from initial page number until the last page number that user was on before Process Death. We add all data into tempList and wait all requests to finish and finally send it back to UI. <em>This is not really ideal for most production scenarios since it causes user to wait a lot and makes a lot of consecutive requests. What you can do instead is to get data from caches and present it to the user which will be much more performant and user friendly.</em></p><p>setPagePosition simply sets the newPage value to page and also saves it to savedStateHandle.</p><p>setScrollPosition is similar to setPagePosition but with a condition. isRestoringData and didOrientationChange have to be false. Because without the condition check, in case of Process Death and Orientation Change scrollPosition sets itself to zero.</p><p>That’s it for MainViewModel.</p><pre>class MainFragment : BaseFragment&lt;FragmentMainBinding&gt;() {<br>    // ...<br><br>    override fun onSaveInstanceState(outState: Bundle) {<br>        super.onSaveInstanceState(outState)<br>        viewModel.didOrientationChange = true<br>    }<br><br>    private fun setObservers() {<br>        viewModel.rvList.observe(viewLifecycleOwner) { response -&gt;<br>            // ...<br><br>            when(response) {<br>                is NetworkResponse.Failure -&gt; {<br>                    recyclerViewAdapter?.setErrorView(response.errorMessage)<br>                }<br>                is NetworkResponse.Loading -&gt; {<br>                    recyclerViewAdapter?.setLoadingView(response.isPaginating)<br>                }<br>                is NetworkResponse.Success -&gt; {<br>                    recyclerViewAdapter?.setData(response.data, response.isPaginationData, response.isPaginationExhausted)<br><br>                    if (viewModel.isRestoringData || viewModel.didOrientationChange) {<br>                        binding.mainRV.scrollToPosition(viewModel.scrollPosition - 1)<br><br>                        if (viewModel.isRestoringData) {<br>                            viewModel.isRestoringData = false<br>                        } else {<br>                            viewModel.didOrientationChange = false<br>                        }<br>                    }<br>                }<br>            }<br>        }<br><br>        // ...<br>    }<br><br>    private fun setRecyclerView() {<br>        binding.mainRV.apply {<br>            // Recyclerview Implementation<br>            // ...<br><br>            var isScrolling = false<br>            addOnScrollListener(object: RecyclerView.OnScrollListener() {<br>                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {<br>                    super.onScrollStateChanged(recyclerView, newState)<br>                    isScrolling = newState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE<br>                }<br><br>                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {<br>                    super.onScrolled(recyclerView, dx, dy)<br>                    val itemCount = linearLayoutManager.itemCount<br>                    val lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition()<br>                    <br>                    // Set new position<br>                    val centerScrollPosition = (linearLayoutManager.findLastCompletelyVisibleItemPosition() + linearLayoutManager.findFirstCompletelyVisibleItemPosition()) / 2<br>                    viewModel.setScrollPosition(centerScrollPosition)<br><br>                    if (lastVisibleItemPosition &gt; PAGE_SIZE.plus(PAGE_SIZE.div(2)) &amp;&amp; dy &lt;= -75) {<br>                        binding.fab.show()<br>                    } else if (lastVisibleItemPosition &lt;= PAGE_SIZE.plus(PAGE_SIZE.div(2)) || dy &gt;= 60) {<br>                        binding.fab.hide()<br>                    }<br><br>                    recyclerViewAdapter?.let {<br>                        if (<br>                            isScrolling &amp;&amp;<br>                            lastVisibleItemPosition &gt;= itemCount.minus(5) &amp;&amp;<br>                            it.canPaginate &amp;&amp;<br>                            !it.isPaginating<br>                        ) {<br>                            viewModel.fetchData()<br>                        }<br>                    }<br>                }<br>            })<br>        }<br>    }<br>}</pre><p><em>I’ve removed or commented unnecessary codes, please ignore them, they are not related to this article. You can check full code at the bottom of this article.</em></p><p>In onSaveInstanceState, we set didOrientationChange = true to handle Orientation Change.</p><p>Inside of setObservers() &gt; is NetworkResponse.Success, we check isRestoringData or didOrientationChange is true and scroll to position that we keep on viewModel. After scrolling, we set the necessary variable to false.</p><p>Finally, in setRecyclerView() &gt; addOnScrollListener, we set centerScrollPosition value and send it to viewModel. <em>You can test and change scroll position however you like. I found setting the scroll position to the middle completely visible item is the best.</em></p><p>That’s it! I hope it was useful. 👋👋</p><p><em>Note: If you want to test Process Death, I recommend you to follow this article.</em></p><p><a href="https://medium.com/@amsavarthan/simulating-process-death-savedstatehandle-28d3ddc3ed97">Simulating Process Death — SavedStateHandle</a></p><h3>Full Code</h3><p><a href="https://github.com/MrNtlu/RecyclerView-Guide">MrNtlu/RecyclerView-Guide (github.com)</a></p><h3>Sources:</h3><ul><li><a href="https://youtu.be/xGcZI4oDCtc">https://youtu.be/xGcZI4oDCtc</a></li><li><a href="https://youtu.be/mnQ2s0w209M">https://youtu.be/mnQ2s0w209M</a></li><li><a href="https://developer.android.com/codelabs/android-lifecycles#6">Incorporate Lifecycle-Aware Components | Android Developers</a></li></ul><p>You can contact me on,</p><ul><li><a href="https://www.linkedin.com/in/burak-fidan/">LinkedIn</a></li><li><a href="https://github.com/MrNtlu">Github</a></li><li><a href="https://twitter.com/BurakFNtlu">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f9c902e491b" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/process-death-orientation-change-in-recyclerview-8f9c902e491b">Process Death &amp; Orientation Change in RecyclerView</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything You Need to Know About RecyclerView]]></title>
            <link>https://proandroiddev.com/everything-you-need-to-know-about-recyclerview-577bf9248298?source=rss-a99dac39edcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/577bf9248298</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Burak]]></dc:creator>
            <pubDate>Thu, 05 Jan 2023 13:18:51 GMT</pubDate>
            <atom:updated>2023-02-08T13:07:16.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>RecyclerView Guide — Pagination, View Types, Shimmer, Error Loading and more…</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWInruQouJjn6Dt-L57jxw.png" /></figure><p><strong>Before we start, y</strong>ou can check the <a href="https://www.youtube.com/shorts/ksq0Ebrl_kI">Youtube Demo Video</a> to understand what we’ll do in this article. We’ll be implementing RecyclerView with,</p><ul><li>State Management with multiple view types (Loading, Error, Pagination etc.)</li><li>View Binding</li><li>Pull to Refresh</li><li><a href="https://developer.android.com/reference/androidx/recyclerview/widget/DiffUtil">DiffUtil</a></li><li>Pagination</li><li>Shimmer Loading Animation</li><li>Scroll to Top FAB</li><li>Favorite Button</li><li>Error Handling</li><li>Popup Menu</li><li>Delete/Update/Insert Item</li></ul><p>I wanted to cover everything that you might need in your project. Hopefully this article will help you understand more about RecyclerView. It’s open to improvements and feedback. Please do let me know if you have any.</p><p><a href="https://youtube.com/shorts/ksq0Ebrl_kI?feature=share">RecyclerView Article Demo</a></p><p>You can check <strong>Part 2</strong> of this article from the link below,</p><p><a href="https://burakdev.medium.com/process-death-orientation-change-in-recyclerview-8f9c902e491b">Process Death &amp; Orientation Change in RecyclerView</a></p><h4>Table of Contents</h4><ul><li><a href="#bc13">Getting Started</a></li><li><a href="#385c">DiffUtil</a></li><li><a href="#7bf3">Adapters</a></li><li><a href="#26b4">ViewHolder</a></li><li><a href="#7823">Repository &amp; View Model</a></li><li><a href="#83f3">UI</a></li><li><a href="#a85d">Shimmer Loading</a></li></ul><h3>Prerequisites</h3><p>We won’t use anything fancy in this article but I’ll assume that you know basics of RecyclerView, View Holder, Live Data and how to implement it.</p><p>I’ll skip <strong>some parts of the code</strong>, so if you want to see the <strong>source code</strong>, you can find the link at the <a href="#35cf">bottom of this article</a>.</p><h3>Getting Started</h3><p>App level build.gradle file,</p><pre>android {<br>    //...<br>    buildFeatures {<br>        viewBinding true<br>    }<br>}<br><br>dependencies {<br>    //...<br>    implementation &#39;androidx.swiperefreshlayout:swiperefreshlayout:1.1.0&#39;<br>    implementation &#39;androidx.lifecycle:lifecycle-livedata-ktx:2.5.1&#39;<br>    implementation &#39;androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1&#39;<br>    implementation &#39;androidx.lifecycle:lifecycle-runtime-ktx:2.5.1&#39;<br>    implementation &quot;com.facebook.shimmer:shimmer:0.5.0&quot;<br>}</pre><p>Response Wrapper,</p><pre>sealed class NetworkResponse&lt;out T&gt; {<br>    data class Loading(<br>        val isPaginating: Boolean = false,<br>    ): NetworkResponse&lt;Nothing&gt;()<br><br>    data class Success&lt;out T&gt;(<br>        val data: T,<br>        val isPaginationData: Boolean = false,<br>    ): NetworkResponse&lt;T&gt;()<br><br>    data class Failure(<br>        val errorMessage: String,<br>        val isPaginationError: Boolean = false,<br>    ): NetworkResponse&lt;Nothing&gt;()<br>}</pre><p>You can learn more about it from this link, <a href="https://proandroiddev.com/handling-success-data-and-error-callback-responses-from-a-network-for-android-projects-using-b53a26214cef">Handling success data and error callback responses from a network for Android projects using Sandwich | by Jaewoong Eum | ProAndroidDev</a></p><p>This enum class to help us with view types, you’ll understand it better when we actually use it. Usage is very simple.</p><pre>enum class RecyclerViewEnum(val value: Int) {<br>    Empty(0),<br>    Loading(1),<br>    Error(2),<br>    View(3),<br>    PaginationLoading(4),<br>    PaginationExhaust(5),<br>}</pre><p>Operation will help us with Insert, Delete and Update “operations”, it’ll make things easier for us to handle upcoming changes.</p><pre>data class Operation&lt;out T&gt;(<br>    val data: T,<br>    val operationEnum: OperationEnum<br>)<br><br>enum class OperationEnum {<br>    Insert,<br>    Delete,<br>    Update,<br>}</pre><p>Finally, RecyclerViewModel data class,</p><pre>data class RecyclerViewModel(<br>    var id: String,<br>    var content: String = &quot;&quot;,<br>    var isLiked: Boolean = false,<br>) {<br>    val text: String<br>        get() = &quot;ID: $id&quot;<br><br>    override fun equals(other: Any?): Boolean {<br>        if (this === other)<br>            return true<br>        if (other !is RecyclerViewModel)<br>            return false<br>        return other.id == id<br>    }<br><br>    override fun hashCode() = Objects.hash(id)<br>}</pre><h3>DiffUtil</h3><p>In the past, I used to use notifyDataSetChanged and it was the easiest way to update RecyclerView but I’ve noticed that it created performance issues and caused bad user experience.</p><blockquote>This event does not specify what about the data set has changed, forcing any observers to assume that all existing items and structure may no longer be valid. LayoutManagers will be forced to fully rebind and relayout all visible views.</blockquote><blockquote>If you are writing an adapter it will always be more efficient to use the more specific change events if you can. Rely on notifyDataSetChanged() as a last resort.</blockquote><p>First, it updates all RecyclerView and causes performance issues, and it should be the last resort as <a href="https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.Adapter#notifyDataSetChanged()">Android documentation</a> points out.</p><p>Second, it has no animation and all list blinks and causes bad user experience.</p><blockquote>DiffUtil is a utility class that calculates the difference between two lists and outputs a list of update operations that converts the first list into the second one.</blockquote><p>DiffUtil comes for the rescue. It calculates the changes in the list and updates only necessary items.</p><pre>class RecyclerViewDiffUtilCallBack(<br>    private val oldList: List&lt;RecyclerViewModel&gt;,<br>    private val newList: List&lt;RecyclerViewModel&gt;,<br>): DiffUtil.Callback() {<br>    override fun getOldListSize() = oldList.size<br><br>    override fun getNewListSize() = newList.size<br><br>    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {<br>        return oldList[oldItemPosition].id == newList[newItemPosition].id<br>    }<br><br>    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {<br>        return when {<br>            oldList[oldItemPosition].id != newList[newItemPosition].id -&gt; false<br>            oldList[oldItemPosition].content != newList[newItemPosition].content -&gt; false<br>            oldList[oldItemPosition].isLiked != newList[newItemPosition].isLiked -&gt; false<br>            else -&gt; true<br>        }<br>    }<br>}</pre><p><a href="https://developer.android.com/reference/androidx/recyclerview/widget/DiffUtil.ItemCallback#areContentsTheSame(T,T)">areContentsTheSame</a> is Called to check whether two items have the same data.</p><p><a href="https://developer.android.com/reference/androidx/recyclerview/widget/DiffUtil.ItemCallback#areItemsTheSame(T,T)">areItemsTheSame</a> is called to check whether two objects represent the same item.</p><h3>Adapters</h3><p>Before we start, we’ll create two adapters. First is generic BaseAdapter&lt;T&gt; which most of the implementation will be here and the second one is RecyclerViewAdapter. We could use single adapter but having BaseAdapter makes things a lot easier for future usages. If you have more than one RecyclerView with similar necessity, instead of repeating the same codes, we can create base adapter and extend from it.</p><pre>@Suppress(&quot;UNCHECKED_CAST&quot;)<br>@SuppressLint(&quot;NotifyDataSetChanged&quot;)<br>abstract class BaseAdapter&lt;T&gt;(open val interaction: Interaction&lt;T&gt;): RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt;() {<br>    private var errorMessage: String? = null<br>    var isLoading = true<br>    var isPaginating = false<br>    var canPaginate = true<br><br>    protected var arrayList: ArrayList&lt;T&gt; = arrayListOf()<br><br>    protected abstract fun handleDiffUtil(newList: ArrayList&lt;T&gt;)<br><br>    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {<br>        when(getItemViewType(position)) {<br>            RecyclerViewEnum.View.value -&gt; {<br>                (holder as ItemViewHolderBind&lt;T&gt;).bind(arrayList[position], position, interaction)<br>            }<br>            RecyclerViewEnum.Error.value -&gt; {<br>                (holder as ErrorViewHolderBind&lt;T&gt;).bind(errorMessage, interaction)<br>            }<br>            RecyclerViewEnum.PaginationExhaust.value -&gt; {<br>                (holder as PaginationExhaustViewHolderBind&lt;T&gt;).bind(interaction)<br>            }<br>        }<br>    }<br><br>    override fun getItemViewType(position: Int) : Int {<br>        return if (isLoading)<br>            RecyclerViewEnum.Loading.value<br>        else if (errorMessage != null)<br>            RecyclerViewEnum.Error.value<br>        else if (isPaginating &amp;&amp; position == arrayList.size)<br>            RecyclerViewEnum.PaginationLoading.value<br>        else if (!canPaginate &amp;&amp; position == arrayList.size)<br>            RecyclerViewEnum.PaginationExhaust.value<br>        else if (arrayList.isEmpty())<br>            RecyclerViewEnum.Empty.value<br>        else<br>            RecyclerViewEnum.View.value<br>    }<br><br>    override fun getItemCount(): Int {<br>        return if (isLoading || errorMessage != null || arrayList.isEmpty())<br>            1<br>        else {<br>            if (arrayList.isNotEmpty() &amp;&amp; !isPaginating &amp;&amp; canPaginate) //View Type<br>                arrayList.size<br>            else<br>                arrayList.size.plus(1)<br>        }<br>    }<br><br>    fun setError(errorMessage: String, isPaginationError: Boolean) {<br>        //...<br>    }<br><br>    fun setLoadingView(isPaginating: Boolean) {<br>        //...<br>    }<br><br>    fun handleOperation(operation: Operation&lt;T&gt;) {<br>        //...<br>    }<br><br>    fun setData(newList: ArrayList&lt;T&gt;, isPaginationData: Boolean = false) {<br>        //...<br>    }<br><br>    private fun setState(rvEnum: RecyclerViewEnum) {<br>        //...<br>    }</pre><p>We’ll implement commented functions later. Let’s check one by one.</p><p>handleDiffUtil will be implemented in each adapter with corresponding models. We’ll just keep it as abstract.</p><p>errorMessage, isLoading, isPaginating and canPaginate values will be used for view types.</p><ul><li>When errorMessage is not null, we’ll show Error view type.</li><li>When isLoading is true, we’ll show Loading view type.</li><li>When isPaginating is true and position is equal to list size, we’ll show PaginationLoading view type.</li><li>When canPaginate is false and position is equal to list size, we’ll show PaginationExhaust view type.</li></ul><blockquote>getItemViewType returns the view type of the item at position for the purposes of view recycling. Consider using id resources to uniquely identify item view types.</blockquote><p>In getItemViewType we are using RecyclerViewEnum that we’ve created earlier. We could just pass numbers like 0, 1, 2 etc. but to make things easier to read we are using enum class.</p><p>Let’s start implementing commented functions.</p><pre>fun setErrorView(errorMessage: String, isPaginationError: Boolean) {<br>    if (isPaginationError) {<br>        setState(RecyclerViewEnum.PaginationExhaust)<br>        notifyItemInserted(itemCount)<br>    } else {<br>        setState(RecyclerViewEnum.Error)<br>        this.errorMessage = errorMessage<br>        notifyDataSetChanged()<br>    }<br>}<br><br>fun setLoadingView(isPaginating: Boolean) {<br>    if (isPaginating) {<br>        setState(RecyclerViewEnum.PaginationLoading)<br>        notifyItemInserted(itemCount)<br>    } else {<br>        setState(RecyclerViewEnum.Loading)<br>        notifyDataSetChanged()<br>    }<br>}</pre><p>Both setErrorView and setLoadingView have similar implementations for different cases. If it’s pagination, we call notifyItemInserted and append corresponding view to the end of the list. If it’s not pagination, we set the state and use notifyDataSetChanged. We are minimizing usage of notifyDataSetChanged but in this case it’s necessary.</p><pre>fun handleOperation(operation: Operation&lt;T&gt;) {<br>    val newList = arrayList.toMutableList()<br><br>    when(operation.operationEnum) {<br>        OperationEnum.Insert -&gt; {<br>            newList.add(operation.data)<br>        }<br>        OperationEnum.Delete -&gt; {<br>            newList.remove(operation.data)<br>        }<br>        OperationEnum.Update -&gt; {<br>            val index = newList.indexOfFirst {<br>                it == operation.data<br>            }<br>            newList[index] = operation.data<br>        }<br>    }<br><br>    handleDiffUtil(newList as ArrayList&lt;T&gt;)<br>}</pre><p>First, we copy the list with toMutableList to prevent reference pass and take the necessary action according to the operation. After that we pass new list to handleDiffUtil and DiffUtil does its “magic”.</p><pre>fun setData(newList: ArrayList&lt;T&gt;, isPaginationData: Boolean = false) {<br>    setState(RecyclerViewEnum.View)<br><br>    if (!isPaginationData) {<br>        if (arrayList.isNotEmpty())<br>            arrayList.clear()<br>        arrayList.addAll(newList)<br>        notifyDataSetChanged()<br>    } else {<br>        notifyItemRemoved(itemCount)<br><br>        newList.addAll(0, arrayList)<br>        handleDiffUtil(newList)<br>    }<br>}</pre><p>This function will be used to insert new data to the list. If we are not paginating, we clear the list and add all new items and finally refresh the list. If we are paginating, we notifyItemRemoved to remove pagination view at the end of the list and add new items and notify DiffUtil.</p><pre>private fun setState(rvEnum: RecyclerViewEnum) {<br>    when(rvEnum) {<br>        RecyclerViewEnum.Empty -&gt; {<br>            isLoading = false<br>            isPaginating = false<br>            errorMessage = null<br>        }<br>        RecyclerViewEnum.Loading -&gt; {<br>            isLoading = true<br>            isPaginating = false<br>            errorMessage = null<br>            canPaginate = true<br>        }<br>        RecyclerViewEnum.Error -&gt; {<br>            isLoading = false<br>            isPaginating = false<br>        }<br>        RecyclerViewEnum.View -&gt; {<br>            isLoading = false<br>            isPaginating = false<br>            errorMessage = null<br>        }<br>        RecyclerViewEnum.PaginationLoading -&gt; {<br>            isLoading = false<br>            isPaginating = true<br>            errorMessage = null<br>        }<br>        RecyclerViewEnum.PaginationExhaust -&gt; {<br>            isLoading = false<br>            isPaginating = false<br>            canPaginate = false<br>        }<br>    }<br>}</pre><p>Finally, this function is simply setting the values according to the state. Again, this function is to makes easier to understand.</p><p>That’s it for BaseAdapter, let’s implement RecyclerViewAdapter.</p><pre>@Suppress(&quot;UNCHECKED_CAST&quot;)<br>class RecyclerViewAdapter(<br>    override val interaction: Interaction&lt;RecyclerViewModel&gt;,<br>    private val extraInteraction: RecyclerViewInteraction,<br>): BaseAdapter&lt;RecyclerViewModel&gt;(interaction) {<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {<br>        return when(viewType) {<br>            RecyclerViewEnum.View.value -&gt; ItemViewHolder(CellItemBinding.inflate(LayoutInflater.from(parent.context), parent, false), extraInteraction)<br>            RecyclerViewEnum.Loading.value -&gt; LoadingViewHolder(CellLoadingBinding.inflate(LayoutInflater.from(parent.context), parent, false))<br>            RecyclerViewEnum.PaginationLoading.value -&gt; PaginationLoadingViewHolder(CellPaginationLoadingBinding.inflate(LayoutInflater.from(parent.context), parent, false))<br>            RecyclerViewEnum.PaginationExhaust.value -&gt; PaginationExhaustViewHolder(CellPaginationExhaustBinding.inflate(LayoutInflater.from(parent.context), parent, false))<br>            RecyclerViewEnum.Error.value -&gt; ErrorItemViewHolder(CellErrorBinding.inflate(LayoutInflater.from(parent.context), parent, false))<br>            else -&gt; EmptyViewHolder(CellEmptyBinding.inflate(LayoutInflater.from(parent.context), parent, false))<br>        }<br>    }<br><br>    override fun handleDiffUtil(newList: ArrayList&lt;RecyclerViewModel&gt;) {<br>        val diffUtil = RecyclerViewDiffUtilCallBack(<br>            arrayList,<br>            newList,<br>        )<br>        val diffResults = DiffUtil.calculateDiff(diffUtil, true)<br><br>        arrayList = newList.toList() as ArrayList&lt;RecyclerViewModel&gt;<br><br>        diffResults.dispatchUpdatesTo(this)<br>    }<br>}</pre><p>Since we’ve made all the implementations in BaseAdapter, it’s very easy to create adapter. We only need to pass view holders and implement handleDiffUtil.</p><p>Small notes, interaction and extraInteraction are interfaces to handle actions. You can check them from the <a href="#35cf">source code</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*bvE4rC5o5KZc0Tn_Nj1E6A.png" /><figcaption>View Type Designs</figcaption></figure><h3>View Holder</h3><p>It’s already a long article, so I’ll skip the implementations of view holders except the ItemViewHolder. You can check other view holders from the <a href="#35cf">source code</a>. If you have any questions, feel free to ask.</p><pre>class ItemViewHolder(<br>    private val binding: CellItemBinding,<br>    private val extraInteraction: RecyclerViewInteraction,<br>): RecyclerView.ViewHolder(binding.root), ItemViewHolderBind&lt;RecyclerViewModel&gt; {<br>    override fun bind(item: RecyclerViewModel, position: Int, interaction: Interaction&lt;RecyclerViewModel&gt;) {<br><br>        val text = &quot;Position: $position ${item.text}&quot;<br>        binding.contentTV.text = item.content.ifBlank { text }<br>        binding.idTV.text = item.id<br>        binding.favButton.setImageDrawable(ContextCompat.getDrawable(binding.root.context, if (item.isLiked) R.drawable.ic_heart else R.drawable.ic_empty_heart))<br><br>        binding.moreButton.setOnClickListener {<br>            val popupMenu = PopupMenu(binding.root.context, binding.moreButton)<br>            popupMenu.inflate(R.menu.popup_menu)<br><br>            popupMenu.setOnMenuItemClickListener {<br>                when(it.itemId) {<br>                    R.id.delete -&gt; {<br>                        try {<br>                            extraInteraction.onDeletePressed(item)<br>                        } catch (e: Exception) {<br>                            Toast.makeText(<br>                                binding.root.context,<br>                                &quot;Please wait before doing any operation.&quot;,<br>                                Toast.LENGTH_SHORT<br>                            ).show()<br>                        }<br>                        return@setOnMenuItemClickListener true<br>                    }<br>                    R.id.update -&gt; {<br>                        try {<br>                            extraInteraction.onUpdatePressed(item)<br>                        } catch (e: Exception) {<br>                            Toast.makeText(<br>                                binding.root.context,<br>                                &quot;Please wait before doing any operation.&quot;,<br>                                Toast.LENGTH_SHORT<br>                            ).show()<br>                        }<br>                        return@setOnMenuItemClickListener true<br>                    }<br>                    else -&gt; {<br>                        return@setOnMenuItemClickListener false<br>                    }<br>                }<br>            }<br><br>            popupMenu.show()<br>        }<br><br>        binding.favButton.setOnClickListener {<br>            extraInteraction.onLikePressed(item)<br>        }<br><br>        binding.root.setOnClickListener {<br>            try {<br>                interaction.onItemSelected(item)<br>            } catch (e: Exception) {<br>                Toast.makeText(<br>                    binding.root.context,<br>                    &quot;Please wait before doing any operation.&quot;,<br>                    Toast.LENGTH_SHORT<br>                ).show()<br>            }<br>        }<br>    }<br>}</pre><p>In bind function, we set the UI elements and click events. Again, there is nothing “magical” about this.</p><h3>Repository &amp; View Model</h3><pre>const val PAGE_SIZE = 50<br><br>class MainRepository {<br><br>    private val tempList = arrayListOf&lt;RecyclerViewModel&gt;().apply {<br>        for (i in 0..PAGE_SIZE) {<br>            add(RecyclerViewModel(UUID.randomUUID().toString(), &quot;Content $i&quot;),)<br>        }<br>    }<br><br>    fun fetchData(page: Int): Flow&lt;NetworkResponse&lt;ArrayList&lt;RecyclerViewModel&gt;&gt;&gt; = flow {<br>        emit(NetworkResponse.Loading(page != 1))<br><br>        kotlinx.coroutines.delay(2000L)<br><br>        try {<br>            if (page == 1)<br>                emit(NetworkResponse.Success(tempList.toList() as ArrayList&lt;RecyclerViewModel&gt;))<br>            else {<br>                val tempPaginationList = arrayListOf&lt;RecyclerViewModel&gt;().apply {<br>                    for (i in 0..PAGE_SIZE) {<br>                        add(RecyclerViewModel(UUID.randomUUID().toString(), &quot;Content ${i * 2}&quot;),)<br>                    }<br>                }<br><br>                if (page &lt; 4) {<br>                    emit(NetworkResponse.Success(<br>                        tempPaginationList,<br>                        isPaginationData = true,<br>                    ))<br>                } else {<br>                    emit(NetworkResponse.Failure(<br>                        &quot;Pagination failed.&quot;,<br>                        isPaginationError = true<br>                    ))<br>                }<br>            }<br>        } catch (e: Exception) {<br>            emit(NetworkResponse.Failure(<br>                e.message ?: e.toString(),<br>                isPaginationError = page != 1<br>            ))<br>        }<br>    }.flowOn(Dispatchers.IO)<br><br>    fun deleteData(item: RecyclerViewModel): Flow&lt;NetworkResponse&lt;Operation&lt;RecyclerViewModel&gt;&gt;&gt; = flow {<br>        kotlinx.coroutines.delay(1000L)<br><br>        try {<br>            emit(NetworkResponse.Success(Operation(item, OperationEnum.Delete)))<br>        } catch (e: Exception) {<br>            emit(NetworkResponse.Failure(e.message ?: e.toString()))<br>        }<br>    }.flowOn(Dispatchers.IO)<br><br>    fun updateData(item: RecyclerViewModel): Flow&lt;NetworkResponse&lt;Operation&lt;RecyclerViewModel&gt;&gt;&gt; = flow {<br>        kotlinx.coroutines.delay(1000L)<br><br>        try {<br>            item.content = &quot;Updated Content ${(0..10).random()}&quot;<br>            emit(NetworkResponse.Success(Operation(item, OperationEnum.Update)))<br>        } catch (e: Exception) {<br>            emit(NetworkResponse.Failure(e.message ?: e.toString()))<br>        }<br>    }.flowOn(Dispatchers.IO)<br><br>    fun toggleLikeData(item: RecyclerViewModel): Flow&lt;NetworkResponse&lt;Operation&lt;RecyclerViewModel&gt;&gt;&gt; = flow {<br>        kotlinx.coroutines.delay(1000L)<br><br>        try {<br>            item.isLiked = !item.isLiked<br>            emit(NetworkResponse.Success(Operation(item, OperationEnum.Update)))<br>        } catch (e: Exception) {<br>            emit(NetworkResponse.Failure(e.message ?: e.toString()))<br>        }<br>    }.flowOn(Dispatchers.IO)<br><br>    fun insertData(item: RecyclerViewModel): Flow&lt;NetworkResponse&lt;Operation&lt;RecyclerViewModel&gt;&gt;&gt; = flow {<br>        emit(NetworkResponse.Loading())<br><br>        kotlinx.coroutines.delay(1000L)<br><br>        try {<br>            emit(NetworkResponse.Success(Operation(item, operationEnum = OperationEnum.Insert)))<br>        } catch (e: Exception) {<br>            emit(NetworkResponse.Failure(e.message ?: e.toString()))<br>        }<br>    }.flowOn(Dispatchers.IO)<br>}</pre><p>We’ll try to pretend like we are making a network request, waiting for it to finish and present the data. We’ll use flows to present NetworkResponse.</p><p>For example, in fetchData first we send loading state with NetworkResponse.Loading and wait 2 seconds. After waiting, if page number is 1 which means we are either refreshing or it’s initial fetch, we send NetworkResponse.Success with data. If page number is something other than 1, it means we are paginating and we send NetworkResponse.Success with isPaginationData = true.</p><p>Since we mimic the network request, if page number is 4, we exhaust the pagination and sent NetworkResponse.Failure with isPaginationError = true to show pagination exhaust view.</p><p>We have a similar logic for other functions too. Only difference is, in some cases we use NetworkResponse with Operation. These functions are used to mimic insert, update and delete.</p><pre>class MainViewModel : ViewModel() {<br>    private val repository = MainRepository()<br><br>    private val _rvList = MutableLiveData&lt;NetworkResponse&lt;ArrayList&lt;RecyclerViewModel&gt;&gt;&gt;()<br>    val rvList: LiveData&lt;NetworkResponse&lt;ArrayList&lt;RecyclerViewModel&gt;&gt;&gt; = _rvList<br><br>    private val _rvOperation = MutableLiveData&lt;NetworkResponse&lt;Operation&lt;RecyclerViewModel&gt;&gt;&gt;()<br>    val rvOperation: LiveData&lt;NetworkResponse&lt;Operation&lt;RecyclerViewModel&gt;&gt;&gt; = _rvOperation<br><br>    private var page: Int = 1<br><br>    init {<br>        fetchData()<br>    }<br><br>    fun refreshData() {<br>        page = 1<br>        fetchData()<br>    }<br><br>    fun fetchData() = viewModelScope.launch(Dispatchers.IO) {<br>        repository.fetchData(page).collect { state -&gt;<br>            withContext(Dispatchers.Main) {<br>                _rvList.value = state<br><br>                if (state is NetworkResponse.Success) {<br>                    page += 1<br>                }<br>            }<br>        }<br>    }<br><br>    fun deleteData(item: RecyclerViewModel) = viewModelScope.launch(Dispatchers.IO) {<br>        repository.deleteData(item).collect { state -&gt;<br>            withContext(Dispatchers.Main) {<br>                _rvOperation.value = state<br>            }<br>        }<br>    }<br><br>    fun updateData(item: RecyclerViewModel) = viewModelScope.launch(Dispatchers.IO) {<br>        repository.updateData(item).collect { state -&gt;<br>            withContext(Dispatchers.Main) {<br>                _rvOperation.value = state<br>            }<br>        }<br>    }<br><br>    fun toggleLikeData(item: RecyclerViewModel) = viewModelScope.launch(Dispatchers.IO) {<br>        repository.toggleLikeData(item).collect { state -&gt;<br>            withContext(Dispatchers.Main) {<br>                _rvOperation.value = state<br>            }<br>        }<br>    }<br><br>    fun insertData(item: RecyclerViewModel) = viewModelScope.launch(Dispatchers.IO) {<br>        repository.insertData(item).collect { state -&gt;<br>            withContext(Dispatchers.Main) {<br>                _rvOperation.value = state<br>            }<br>        }<br>    }<br><br>    fun throwError() = viewModelScope.launch(Dispatchers.Main) {<br>        _rvList.value = NetworkResponse.Failure(&quot;Error occured!&quot;)<br>    }<br><br>    fun exhaustPagination() = viewModelScope.launch(Dispatchers.Main) {<br>        _rvList.value = NetworkResponse.Failure(<br>            &quot;Pagination Exhaust&quot;,<br>            true<br>        )<br>    }<br>}</pre><p>View model is only here to present the data to UI. We’ll have two LiveData, rvList and rvOperation. rvList will be used to listen changes on our list and rvOperation will be used to listen operations e.g., new item gets inserted and we’ll listen to that operation and handle it in UI.</p><h3>UI</h3><pre>class MainFragment : BaseFragment&lt;FragmentMainBinding&gt;() {<br>    private lateinit var viewModel: MainViewModel<br>    private var recyclerViewAdapter: RecyclerViewAdapter? = null<br>    private var loadingDialog: Dialog? = null<br><br>    //OnCreate and OnCreateView commented.<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br><br>        setDialog(view.context)<br>        setListeners()<br>        setRecyclerView()<br>        setObservers()<br>    }<br><br>    private fun setDialog(context: Context) {<br>        loadingDialog = Dialog(context)<br>        loadingDialog?.setCancelable(false)<br>        loadingDialog?.setContentView(R.layout.dialog_loading)<br>        loadingDialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))<br>    }<br><br>    private fun setListeners() {<br>        binding.swipeRefreshLayout.setOnRefreshListener {<br>            viewModel.refreshData()<br><br>            binding.swipeRefreshLayout.isRefreshing = false<br>        }<br><br>        binding.errorButton.setOnClickListener {<br>            viewModel.throwError()<br>        }<br><br>        binding.appendButton.setOnClickListener {<br>            if (recyclerViewAdapter?.canPaginate == true &amp;&amp; recyclerViewAdapter?.isPaginating == false)<br>                viewModel.fetchData()<br><br>            binding.mainRV.scrollToPosition(recyclerViewAdapter?.itemCount ?: 0)<br>        }<br><br>        binding.insertButton.setOnClickListener {<br>            viewModel.insertData(RecyclerViewModel(UUID.randomUUID().toString()))<br>        }<br><br>        binding.paginateErrorButton.setOnClickListener {<br>            viewModel.exhaustPagination()<br>        }<br><br>        binding.fab.setOnClickListener {<br>            viewLifecycleOwner.lifecycleScope.launch {<br>                binding.mainRV.quickScrollToTop()<br>            }<br>        }<br>    }<br><br>    private fun setObservers() {<br>        viewModel.rvList.observe(viewLifecycleOwner) { response -&gt;<br>            binding.swipeRefreshLayout.isEnabled = when (response) {<br>                is NetworkResponse.Success -&gt; {<br>                    true<br>                }<br>                is NetworkResponse.Failure -&gt; {<br>                    response.isPaginationError<br>                }<br>                else -&gt; false<br>            }<br><br>            when(response) {<br>                is NetworkResponse.Failure -&gt; {<br>                    recyclerViewAdapter?.setErrorView(response.errorMessage, response.isPaginationError)<br>                }<br>                is NetworkResponse.Loading -&gt; {<br>                    recyclerViewAdapter?.setLoadingView(response.isPaginating)<br>                }<br>                is NetworkResponse.Success -&gt; {<br>                    recyclerViewAdapter?.setData(response.data, response.isPaginationData)<br>                }<br>            }<br>        }<br><br>        viewModel.rvOperation.observe(viewLifecycleOwner) { response -&gt;<br>            when(response) {<br>                is NetworkResponse.Failure -&gt; {<br>                    if (loadingDialog?.isShowing == true)<br>                        loadingDialog?.dismiss()<br>                }<br>                is NetworkResponse.Loading -&gt; {<br>                    if (recyclerViewAdapter?.isLoading == false)<br>                        loadingDialog?.show()<br>                }<br>                is NetworkResponse.Success -&gt; {<br>                    if (loadingDialog?.isShowing == true)<br>                        loadingDialog?.dismiss()<br>                    recyclerViewAdapter?.handleOperation(response.data)<br>                }<br>            }<br>        }<br>    }<br><br>    private fun setRecyclerView() {<br>        //... Later<br>    }<br>}</pre><p>We’ll implement setRecyclerView function later,</p><p>setListeners function is to set click or refresh listeners. Most buttons are for testing purposes and not really necessary. <em>binding.fab is scroll to top button. </em><em>quickScrollToTop is custom function by </em><a href="https://medium.com/u/560a85bfeb34"><em>Patrick Elmquist</em></a><em>. You can check his article from </em><a href="https://medium.com/flat-pack-tech/quickly-scroll-to-the-top-of-a-recyclerview-da15b717f3c4"><em>this link</em></a><em>.</em></p><p>In rvList.observe,</p><ul><li>We set the swipeRefreshLayout.isEnabled since we don’t want user to refresh again when we are already loading the data.</li><li>In when(response), we check NetworkResponse type and call necessary function with recyclerViewAdapter.</li></ul><p>Same logic in rvOperation.observe,</p><ul><li>We check the response in when(response) and call necessary function.<br>Only difference is, we show or dismiss loading dialog.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*RP4OjGsWZjwLsRMm_lvpLg.png" /><figcaption>Loading Dialog</figcaption></figure><pre>private fun setRecyclerView() {<br>    binding.mainRV.apply {<br>        val linearLayoutManager = LinearLayoutManager(context)<br>        layoutManager = linearLayoutManager<br>        addItemDecoration(DividerItemDecoration(context, linearLayoutManager.orientation))<br>        recyclerViewAdapter = RecyclerViewAdapter(object: Interaction&lt;RecyclerViewModel&gt; {<br>            override fun onItemSelected(item: RecyclerViewModel) {<br>                Toast.makeText(context, &quot;Item ${item.content}&quot;, Toast.LENGTH_SHORT).show()<br>            }<br><br>            override fun onErrorRefreshPressed() {<br>                viewModel.refreshData()<br>            }<br><br>            override fun onExhaustButtonPressed() {<br>                viewLifecycleOwner.lifecycleScope.launch {<br>                    quickScrollToTop()<br>                }<br>            }<br>        }, object: RecyclerViewInteraction {<br>            override fun onUpdatePressed(item: RecyclerViewModel) {<br>                viewModel.updateData(item.copy())<br>            }<br><br>            override fun onDeletePressed(item: RecyclerViewModel) {<br>                viewModel.deleteData(item)<br>            }<br><br>            override fun onLikePressed(item: RecyclerViewModel) {<br>                viewModel.toggleLikeData(item.copy())<br>            }<br><br>        })<br>        adapter = recyclerViewAdapter<br><br>        var isScrolling = false<br>        addOnScrollListener(object: RecyclerView.OnScrollListener() {<br>            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {<br>                super.onScrollStateChanged(recyclerView, newState)<br>                isScrolling = newState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE<br>            }<br><br>            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {<br>                super.onScrolled(recyclerView, dx, dy)<br>                val itemCount = linearLayoutManager.itemCount<br>                val lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition()<br><br>                if (lastVisibleItemPosition &gt; PAGE_SIZE.plus(PAGE_SIZE.div(2)) &amp;&amp; dy &lt;= -75) {<br>                    binding.fab.show()<br>                } else if (lastVisibleItemPosition &lt;= PAGE_SIZE.plus(PAGE_SIZE.div(2)) || dy &gt;= 60) {<br>                    binding.fab.hide()<br>                }<br><br>                recyclerViewAdapter?.let {<br>                    if (<br>                        isScrolling &amp;&amp;<br>                        lastVisibleItemPosition &gt;= itemCount.minus(5) &amp;&amp;<br>                        it.canPaginate &amp;&amp;<br>                        !it.isPaginating<br>                    ) {<br>                        viewModel.fetchData()<br>                    }<br>                }<br>            }<br>        })<br>    }<br>}</pre><p>Finally, setRecyclerView function. We create and set recyclerViewAdapter to binding.mainRV.</p><p>We also implement addScrollListener which will be used to show/hide fab and trigger the pagination.</p><ul><li>For fab.show, we check if we’ve scrolled enough and certain number of items visible. If so, if we’ve also scrolled certain number in negative direction. fab.hide is the reverse of that. You can try yourself and set numbers yourself.</li><li>For pagination, we check if we are scrolling &amp; if we are certain number before the last visible item &amp; if canPaginate &amp; if we are not already paginating.</li></ul><h3>Shimmer</h3><p>We’ll separate shimmer into two parts, first will be normal layout part and second will be ShimmerFrameLayout,</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:layout_marginVertical=&quot;6dp&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/shimmerIdTV&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginStart=&quot;12dp&quot;<br>        android:layout_marginTop=&quot;8dp&quot;<br>        android:layout_marginEnd=&quot;12dp&quot;<br>        android:textColor=&quot;@color/black&quot;<br>        android:background=&quot;@color/shimmer_color&quot;<br>        app:layout_constraintEnd_toStartOf=&quot;@+id/shimmerFavButton&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/shimmerContentTV&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginStart=&quot;12dp&quot;<br>        android:layout_marginTop=&quot;8dp&quot;<br>        android:layout_marginEnd=&quot;12dp&quot;<br>        android:layout_marginBottom=&quot;8dp&quot;<br>        android:background=&quot;@color/shimmer_color&quot;<br>        android:textColor=&quot;@color/black&quot;<br>        android:textSize=&quot;14sp&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toStartOf=&quot;@+id/shimmerFavButton&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@+id/shimmerIdTV&quot; /&gt;<br><br>    &lt;ImageView<br>        android:id=&quot;@+id/shimmerFavButton&quot;<br>        android:layout_width=&quot;32dp&quot;<br>        android:layout_height=&quot;32dp&quot;<br>        android:layout_marginEnd=&quot;8dp&quot;<br>        android:background=&quot;@color/shimmer_color&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;@+id/shimmerMoreButton&quot;<br>        app:layout_constraintEnd_toStartOf=&quot;@+id/shimmerMoreButton&quot;<br>        app:layout_constraintTop_toTopOf=&quot;@+id/shimmerMoreButton&quot;<br>        app:layout_constraintVertical_bias=&quot;0.407&quot; /&gt;<br><br>    &lt;ImageView<br>        android:id=&quot;@+id/shimmerMoreButton&quot;<br>        android:layout_width=&quot;32dp&quot;<br>        android:layout_height=&quot;32dp&quot;<br>        android:layout_marginEnd=&quot;8dp&quot;<br>        android:background=&quot;@color/shimmer_color&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;/&gt;<br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p><em>simmerColor code is #BFBDBD</em></p><p>We’ve simply copied and pasted RecyclerView item design and added background=”@color/shimmer_color” to each one of them.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;com.facebook.shimmer.ShimmerFrameLayout<br>    android:id=&quot;@+id/shimmerLoadingLayout&quot;<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    app:shimmer_auto_start=&quot;true&quot;<br>    app:shimmer_duration=&quot;1300&quot;&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:orientation=&quot;vertical&quot;&gt;<br><br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>        &lt;include layout=&quot;@layout/cell_shimmer&quot;/&gt;<br>    &lt;/LinearLayout&gt;<br>&lt;/com.facebook.shimmer.ShimmerFrameLayout&gt;</pre><p>Inside of ShimmerFrameLayout, we set auto_start=&quot;true&quot; to start animation automatically. duration is how long it takes to finis the animation. You can see more about it <a href="https://facebook.github.io/shimmer-android/">here</a>.</p><p>You can decrease or increase the number of included layouts. I’ve tried to add as low as I can to cover whole screen. Less is better for performance, I think :)</p><p>That’s it! I hope it was useful. 👋👋</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*lyAh0Rio9OEMN_1t" /></figure><h3>Full Code</h3><p><a href="https://github.com/MrNtlu/RecyclerView-Guide/tree/article_1">MrNtlu/RecyclerView-Guide at article_1 (github.com)</a></p><h3>Sources:</h3><ul><li><a href="https://medium.com/flat-pack-tech/quickly-scroll-to-the-top-of-a-recyclerview-da15b717f3c4">Quickly scroll to the top of a list | by Patrick Elmquist | Flat Pack Tech | Medium</a></li><li><a href="https://stackoverflow.com/questions/60423596/how-to-use-viewbinding-in-a-recyclerview-adapter">android — How to use ViewBinding in a RecyclerView.Adapter? — Stack Overflow</a></li><li><a href="https://www.youtube.com/watch?v=cppys4VYyvA&amp;ab_channel=Stevdza-San">DiffUtil — Improve RecyclerView’s Performance | Android Studio Tutorial — YouTube</a></li><li><a href="https://stackoverflow.com/questions/59560135/diffutil-itemcallback-doesnt-update-item-position-after-a-deleting">android — DiffUtil.ItemCallback doesn’t update item position (after a deleting) — Stack Overflow</a></li><li><a href="https://stackoverflow.com/questions/59043638/how-to-call-suspend-function-from-fragment-or-activity">android — How to call suspend function from Fragment or Activity? — Stack Overflow</a></li><li><a href="https://stackoverflow.com/questions/30301451/how-to-disable-pull-to-refresh-action-and-use-only-indicator">android — How to disable “pull to refresh” action and use only indicator? — Stack Overflow</a></li><li><a href="https://stackoverflow.com/questions/20545742/padding-not-working-on-imagebutton">android — Padding not working on ImageButton — Stack Overflow</a></li><li><a href="https://stackoverflow.com/questions/52847477/kotlin-how-to-override-hashcode">equals — kotlin — how to override hashcode — Stack Overflow</a></li><li><a href="https://stackoverflow.com/questions/37601346/create-options-menu-for-recyclerview-item">android — Create Options Menu for RecyclerView-Item — Stack Overflow</a></li><li><a href="https://www.youtube.com/watch?v=lNgvyUIUfuc&amp;ab_channel=TechProjects">shimmer effect in android studio | shimmer effect recycler view android | Tech Projects — YouTube</a></li><li><a href="https://m2.material.io/components/buttons-floating-action-button/android#using-fabs">Buttons: floating action button — Material Design</a></li><li><a href="https://stackoverflow.com/questions/28937106/how-to-make-custom-dialog-with-rounded-corners-in-android">How to make custom dialog with rounded corners in android — Stack Overflow</a></li></ul><p>You can contact me on,</p><ul><li><a href="https://www.linkedin.com/in/burak-fidan/">LinkedIn</a></li><li><a href="https://github.com/MrNtlu">Github</a></li><li><a href="https://twitter.com/BurakFNtlu">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=577bf9248298" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/everything-you-need-to-know-about-recyclerview-577bf9248298">Everything You Need to Know About RecyclerView</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Authentication and Refresh Token in Android with Retrofit Interceptor & Authenticator]]></title>
            <link>https://proandroiddev.com/jwt-authentication-and-refresh-token-in-android-with-retrofit-interceptor-authenticator-da021f7f7534?source=rss-a99dac39edcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/da021f7f7534</guid>
            <category><![CDATA[okhttp]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-retrofit]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Burak]]></dc:creator>
            <pubDate>Wed, 28 Dec 2022 14:42:50 GMT</pubDate>
            <atom:updated>2022-12-29T08:05:07.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K20haelxHIHOlmqnF8wSAw.png" /></figure><p>In this article, we’ll be implementing JWT (JSON Web Token) authentication and silent refresh with Retrofit Interceptor and Authenticator. Silent token refresh is necessary when token expires and response from the server is 401 Unauthorized. Instead of logging out the user, we’ll refresh token and continue the request.</p><h4>Table of Contents</h4><ul><li><a href="#d4bd">Getting Started</a></li><li><a href="#cb70">API Endpoint &amp; Models</a></li><li><a href="#9e43">Retrofit Setup</a></li><li><a href="#6bd3">Token DataStore</a></li><li><a href="#656a">Helpers</a></li><li><a href="#23d3">Repository &amp; View Model</a></li><li><a href="#27c4">Interceptor &amp; Authenticator</a></li><li><a href="#1755">Hilt Module</a></li><li><a href="#2a5f">UI</a></li></ul><h3>Prerequisites</h3><p>We’ll use LiveData, Hilt, Retrofit, OkHttp and DataStore in this article, so it’s better you know how they work.</p><p>I’ll skip some parts of the Hilt setup, so if you want to see the source code, you can find the link at the bottom of this article.</p><h3>Getting Started</h3><p>App level build.gradle file,</p><pre>//DataStore<br>implementation &quot;androidx.datastore:datastore-preferences:1.0.0&quot;<br><br>//Retrofit<br>def retrofit_version = &quot;2.9.0&quot;<br>implementation &quot;com.squareup.retrofit2:retrofit:$retrofit_version&quot;<br>implementation &quot;com.squareup.retrofit2:converter-gson:$retrofit_version&quot;<br><br>//Hilt<br>def hilt_version = &quot;2.44&quot;<br>implementation &quot;com.google.dagger:hilt-android:$hilt_version&quot;<br>kapt &quot;com.google.dagger:hilt-compiler:$hilt_version&quot;<br><br>//OkHttp<br>def okhttp_version = &quot;4.10.0&quot;<br>implementation &quot;com.squareup.okhttp3:okhttp:$okhttp_version&quot;<br>implementation &quot;com.squareup.okhttp3:logging-interceptor:$okhttp_version&quot;</pre><p>Don’t forget to add Internet permission in AndroidManifest.xml,</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><h3>API Endpoint &amp; Models</h3><p>I’ve created my own backend to test token authentication. You can check it from this link. <a href="https://github.com/MrNtlu/JWT-Test-API">MrNtlu/JWT-Test-API (github.com)</a></p><p>Also, if you want to run it locally, you can follow <a href="https://github.com/MrNtlu/JWT-Test-API">these instructions</a>. It’s very simple Rest API. Token will be refreshed in every 30 seconds and we’ll have to refresh the old token with the new one.</p><p><em>Note: You can get timeout error while testing. It’s free tier on render.com so it has limitations. Please keep trying until you get the result successfully.</em></p><p>We’ll need to create couple of request/response models for Rest API,</p><p>POST auth/login request,</p><pre>data class Auth(<br>    @SerializedName(&quot;email_address&quot;)<br>    val email: String,<br>    val password: String<br>)</pre><p>POST auth/login and GET auth/refresh response,</p><pre>data class LoginResponse(<br>    @SerializedName(&quot;access_token&quot;)<br>    val token: String<br>)</pre><p>GET user/info response,</p><p><em>Please put them into different files. I’ve put them into one code block to make it easier to read.</em></p><pre>data class UserInfoResponse(<br>    @SerializedName(&quot;data&quot;)<br>    val userInfo: UserInfo,<br>    val message: String<br>)<br>data class UserInfo(<br>    val _id: String,<br>    val email_address: String<br>)</pre><p>Finally ErrorResponse ,</p><pre>data class ErrorResponse(<br>    val code: Int,<br>    val message: String<br>)</pre><h3>Retrofit Setup</h3><p>We’ll have two separate API Service files. First one is AuthApiService ,</p><pre>interface AuthApiService {<br>    @POST(&quot;auth/login&quot;)<br>    suspend fun login(<br>        @Body auth: Auth,<br>    ): Response&lt;LoginResponse&gt;<br><br>    @GET(&quot;auth/refresh&quot;)<br>    suspend fun refreshToken(<br>        @Header(&quot;Authorization&quot;) token: String,<br>    ): Response&lt;LoginResponse&gt;<br>}</pre><p>Second one is MainApiService,</p><pre>interface MainApiService {<br>    @GET(&quot;user/info&quot;)<br>    suspend fun getUserInfo(): Response&lt;UserInfoResponse&gt;<br>}</pre><p>That’s it for now, we’ll create the Retrofit instance later in this article.</p><h3>Token DataStore</h3><p>When a user logged in and reopened the application, we’ll need a way to save that token and use it. DataStore will help us for this problem. We’ll save the token locally and use it when needed.</p><pre>class TokenManager(private val context: Context) {<br>    companion object {<br>        private val TOKEN_KEY = stringPreferencesKey(&quot;jwt_token&quot;)<br>    }<br><br>    fun getToken(): Flow&lt;String?&gt; {<br>        return context.dataStore.data.map { preferences -&gt;<br>            preferences[TOKEN_KEY]<br>        }<br>    }<br><br>    suspend fun saveToken(token: String) {<br>        context.dataStore.edit { preferences -&gt;<br>            preferences[TOKEN_KEY] = token<br>        }<br>    }<br><br>    suspend fun deleteToken() {<br>        context.dataStore.edit { preferences -&gt;<br>            preferences.remove(TOKEN_KEY)<br>        }<br>    }<br>}</pre><p>That’s it. There is nothing special. Just a small note, context.dataStore won’t work and you’ll see error. Don’t worry. We’ll add it later on Hilt Module part.</p><h3>Helpers</h3><p>Before we start implementing Repository and View Model, we’ll create helper classes.</p><p>First ApiResponse , this will help us manage the API requests and UI state management. We’ll be able to show the necessary UI to the user and extract data easily.</p><pre>sealed class ApiResponse&lt;out T&gt; {<br>    object Loading: ApiResponse&lt;Nothing&gt;()<br><br>    data class Success&lt;out T&gt;(<br>        val data: T<br>    ): ApiResponse&lt;T&gt;()<br><br>    data class Failure(<br>        val errorMessage: String,<br>        val code: Int,<br>    ): ApiResponse&lt;Nothing&gt;()<br>}</pre><p>Second is apiRequestFlow , this class will help us to make API calls on the <a href="https://developer.android.com/kotlin/coroutines/coroutines-adv">IO thread</a> and emit the state. Currently the timeout is set to 20 seconds, you can change it depending on your needs.</p><pre>fun&lt;T&gt; apiRequestFlow(call: suspend () -&gt; Response&lt;T&gt;): Flow&lt;ApiResponse&lt;T&gt;&gt; = flow {<br>    emit(ApiResponse.Loading)<br><br>    withTimeoutOrNull(20000L) {<br>        val response = call()<br><br>        try {<br>            if (response.isSuccessful) {<br>                response.body()?.let { data -&gt;<br>                    emit(ApiResponse.Success(data))<br>                }<br>            } else {<br>                response.errorBody()?.let { error -&gt;<br>                    error.close()<br>                    val parsedError: ErrorResponse = Gson().fromJson(error.charStream(), ErrorResponse::class.java)<br>                    emit(ApiResponse.Failure(parsedError.message, parsedError.code))<br>                }<br>            }<br>        } catch (e: Exception) {<br>            emit(ApiResponse.Failure(e.message ?: e.toString(), 400))<br>        }<br>    } ?: emit(ApiResponse.Failure(&quot;Timeout! Please try again.&quot;, 408))<br>}.flowOn(Dispatchers.IO)</pre><p>Finally BaseViewModel, this class will help us catch and present errors on correct thread and cancel the job when necessary.</p><pre>open class BaseViewModel : ViewModel() {<br>    private var mJob: Job? = null<br><br>    protected fun &lt;T&gt; baseRequest(liveData: MutableLiveData&lt;T&gt;, errorHandler: CoroutinesErrorHandler, request: () -&gt; Flow&lt;T&gt;) {<br>        mJob = viewModelScope.launch(Dispatchers.IO + CoroutineExceptionHandler { _, error -&gt;<br>            viewModelScope.launch(Dispatchers.Main) {<br>                errorHandler.onError(error.localizedMessage ?: &quot;Error occured! Please try again.&quot;)<br>            }<br>        }){<br>            request().collect {<br>                withContext(Dispatchers.Main) {<br>                    liveData.value = it<br>                }<br>            }<br>        }<br>    }<br><br>    override fun onCleared() {<br>        super.onCleared()<br>        mJob?.let {<br>            if (it.isActive) {<br>                it.cancel()<br>            }<br>        }<br>    }<br>}<br><br>interface CoroutinesErrorHandler {<br>    fun onError(message:String)<br>}</pre><p>That’s it. Now we can start implementing Repository &amp; ViewModel.</p><h3>Repository &amp; View Model</h3><p>Since we’ve already implemented apiRequestFlow , repository classes will be very short.</p><pre>class AuthRepository @Inject constructor(<br>    private val authApiService: AuthApiService,<br>) {<br>    fun login(auth: Auth) = apiRequestFlow {<br>        authApiService.login(auth)<br>    }<br>}</pre><pre>class MainRepository @Inject constructor(<br>    private val mainApiService: MainApiService,<br>) {<br>    fun getUserInfo() = apiRequestFlow {<br>        mainApiService.getUserInfo()<br>    }<br>}</pre><p>Same goes for view models, only thing that is extra is LiveData objects. Both view models extend BaseViewModel which we’ve created earlier.</p><pre>@HiltViewModel<br>class AuthViewModel @Inject constructor(<br>    private val authRepository: AuthRepository,<br>): BaseViewModel() {<br><br>    private val _loginResponse = MutableLiveData&lt;ApiResponse&lt;LoginResponse&gt;&gt;()<br>    val loginResponse = _loginResponse<br><br>    fun login(auth: Auth, coroutinesErrorHandler: CoroutinesErrorHandler) = baseRequest(<br>        _loginResponse,<br>        coroutinesErrorHandler<br>    ) {<br>        authRepository.login(auth)<br>    }<br>}</pre><pre>@HiltViewModel<br>class MainViewModel @Inject constructor(<br>    private val mainRepository: MainRepository,<br>): BaseViewModel() {<br><br>    private val _userInfoResponse = MutableLiveData&lt;ApiResponse&lt;UserInfoResponse&gt;&gt;()<br>    val userInfoResponse = _userInfoResponse<br><br>    fun getUserInfo(coroutinesErrorHandler: CoroutinesErrorHandler) = baseRequest(<br>        _userInfoResponse,<br>        coroutinesErrorHandler,<br>    ) {<br>        mainRepository.getUserInfo()<br>    }<br>}</pre><p>Finally, we are going to create one more view model for Token.</p><pre>@HiltViewModel<br>class TokenViewModel @Inject constructor(<br>    private val tokenManager: TokenManager,<br>): ViewModel() {<br><br>    val token = MutableLiveData&lt;String?&gt;()<br><br>    init {<br>        viewModelScope.launch(Dispatchers.IO) {<br>            tokenManager.getToken().collect {<br>                withContext(Dispatchers.Main) {<br>                    token.value = it<br>                }<br>            }<br>        }<br>    }<br><br>    fun saveToken(token: String) {<br>        viewModelScope.launch(Dispatchers.IO) {<br>            tokenManager.saveToken(token)<br>        }<br>    }<br><br>    fun deleteToken() {<br>        viewModelScope.launch(Dispatchers.IO) {<br>            tokenManager.deleteToken()<br>        }<br>    }<br>}</pre><p>In this view model, we have only 1 variable which is token live data object. When we initialize the view model, we are setting token value to tokenManager.token and listen for changes.</p><p>Whenever we call saveToken or deleteToken , token value will be updated on tokenManager.getToken().collect so we don’t have to worry about anything else.</p><p>That’s it! Now we can implement Interceptor and Authenticator.</p><h3>Interceptor &amp; Authenticator</h3><p>Interceptor is very simple,</p><pre>class AuthInterceptor @Inject constructor(<br>    private val tokenManager: TokenManager,<br>): Interceptor {<br>    override fun intercept(chain: Interceptor.Chain): Response {<br>        val token = runBlocking {<br>            tokenManager.getToken().first()<br>        }<br>        val request = chain.request().newBuilder()<br>        request.addHeader(&quot;Authorization&quot;, &quot;Bearer $token&quot;)<br>        return chain.proceed(request.build())<br>    }<br>}</pre><p>We are getting the token from tokenManager by blocking the current thread until completion with <a href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html">runBlocking</a>. After that, we add Authorization header to the ongoing request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*WjKvjIIcG8aK2oEX2mmkqg@2x.png" /><figcaption><a href="https://square.github.io/okhttp/features/interceptors/">Interceptors — OkHttp (square.github.io)</a></figcaption></figure><p>There is a small problem, what if token is empty or outdated? The solution is simple, Authenticator.</p><blockquote>Performs either <strong>preemptive</strong> authentication before connecting to a proxy server, or <strong>reactive</strong> authentication after receiving a challenge from either an origin web server or proxy server.</blockquote><blockquote>When reactive authentication is requested by an origin web server, the response code is 401 and the implementation should respond with a new request that sets the “Authorization” header.</blockquote><blockquote>For more info, you can click <a href="https://square.github.io/okhttp/4.x/okhttp/okhttp3/-authenticator/">the link</a>.</blockquote><pre>class AuthAuthenticator @Inject constructor(<br>    private val tokenManager: TokenManager,<br>): Authenticator {<br><br>    override fun authenticate(route: Route?, response: Response): Request? {<br>        val token = runBlocking {<br>            tokenManager.getToken().first()<br>        }<br>        return runBlocking {<br>            val newToken = getNewToken(token)<br><br>            if (!newToken.isSuccessful || newToken.body() == null) { //Couldn&#39;t refresh the token, so restart the login process<br>                tokenManager.deleteToken()<br>            }<br><br>            newToken.body()?.let {<br>                tokenManager.saveToken(it.token)<br>                response.request.newBuilder()<br>                    .header(&quot;Authorization&quot;, &quot;Bearer ${it.token}&quot;)<br>                    .build()<br>            }<br>        }<br>    }<br><br>    private suspend fun getNewToken(refreshToken: String?): retrofit2.Response&lt;LoginResponse&gt; {<br>        val loggingInterceptor = HttpLoggingInterceptor()<br>        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY<br>        val okHttpClient = OkHttpClient.Builder().addInterceptor(loggingInterceptor).build()<br><br>        val retrofit = Retrofit.Builder()<br>            .baseUrl(&quot;https://jwt-test-api.onrender.com/api/&quot;)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .client(okHttpClient)<br>            .build()<br>        val service = retrofit.create(AuthApiService::class.java)<br>        return service.refreshToken(&quot;Bearer $refreshToken&quot;)<br>    }<br>}</pre><p><em>Authenticator will not intercept every time, it’s going to be reactive to response and react accordingly. So, if token is valid, authenticator won’t interfere but if token is not valid, it’ll intercept and refresh the token.</em></p><p>Again, before we do anything we get the token with runBlocking. After it, we use getNewToken function to request new token with the old token then we are checking if we’ve retrieved the new token successfully.</p><p>If we couldn’t get new token, we use deleteToken function which will trigger TokenViewModel token live data and on UI part we’ll force user to logout.</p><p>If we’ve retrieved the new refresh token successfully, we’ll update the old token value with new token and make the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*vu5IBWDQDgCGfYoV-eJn7g.png" /><figcaption>Authenticator Flow</figcaption></figure><p>As you can see from the image, we make the request (1) but token is expired, so we make another request to auth/refresh for a new token and successfully retrieve it (2). After that we make the request to user/info and successfully fetch the data (3).</p><h3>Hilt Module</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6671547ac9ee70be42c97a8fcb26492b/href">https://medium.com/media/6671547ac9ee70be42c97a8fcb26492b/href</a></iframe><p>This class doesn’t need much of an explanation but some small notes,</p><ul><li>Like I’ve mentioned earlier, we set the Context.dataStore extension at the top of this class.</li><li>HttpLogginInterceptor which logs request and response information.</li><li>Instead of providing Retrofit instance, I’ve providedRetrofit.Builder because AuthApiService won’t use OkHttpClient but MainApiService will. To make the separation I am passing only the Retrofit.Builder instance.</li></ul><p>That’s it. Now we can implement UI.</p><h3>UI</h3><p>We’ll have Login and Main fragments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7df9ecf4aedb7b423188d78a46e0ede0/href">https://medium.com/media/7df9ecf4aedb7b423188d78a46e0ede0/href</a></iframe><p><em>Views are poorly set, please ignore them.</em></p><p>In LoginFragment, we have two view models, AuthViewModel and TokenViewModel. We’ve used activityViewModels because TokenViewModel should be scoped to Activity, not fragment.</p><blockquote>activityViewModels() is pretty self-explanatory. It is used to scoped to its activity and when its activity get destroy, activityViewModels() will be destroyed as well. <a href="https://skynight1996.medium.com/navigation-component-comparison-between-viewmodels-activityviewmodels-and-ae0145734228">Source Link</a>.</blockquote><p>We are observing two live data objects, token and loginResponse. When user clicks the loginButton and makes the viewModel.login request, we’ll retrieve the data.token from loginResponse and save it. When saved, token will observe and when it’s set and not null we’ll navigate to MainFragment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53134f73ab2eceb1b68c7cb0d899fe9f/href">https://medium.com/media/53134f73ab2eceb1b68c7cb0d899fe9f/href</a></iframe><p>MainFragment is very similar to LoginFragment. On infoButton click, we make the request and observe it. When we receive the userInfoResponse we present it to infoTV text view.</p><p>Also, we are observing the tokenViewModel token live data, when token is set to null, that means we should log out and move back to login screen.</p><p>Let’s see the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*cYK1g43u4bXGvTvR" /></figure><p>That’s it! I hope it was useful. 👋👋</p><h4>Full Code</h4><p><a href="https://github.com/MrNtlu/Token-Authentication">MrNtlu/Token-Authentication (github.com)</a></p><h4>Sources:</h4><ul><li><a href="https://stackoverflow.com/questions/73258301/add-access-token-to-retrofit-request-header-and-refresh-it-through-refresh-token/73258302#73258302">kotlin — add access token to retrofit request header and refresh it through refresh token — Stack Overflow</a></li><li><a href="https://github.com/Giga99/MediumRepos/tree/main/interceptors">https://github.com/Giga99/MediumRepos/tree/main/interceptors</a></li><li><a href="https://stackoverflow.com/questions/64985634/fragment-not-being-restored-from-backstack-also-hilt-recreating-viewmodel-with">android — Fragment not being restored from backstack, also Hilt recreating ViewModel with Fragment’s lifecycle — Stack Overflow</a></li><li><a href="https://developer.android.com/topic/libraries/architecture/datastore">App Architecture: Data Layer — DataStore — Android Developers</a></li><li><a href="https://youtu.be/SJePkypZCzo">https://youtu.be/SJePkypZCzo</a></li><li><a href="https://skynight1996.medium.com/navigation-component-comparison-between-viewmodels-activityviewmodels-and-ae0145734228">Navigation Component — Comparison between viewModels(), activityViewModels() and navGraphViewModels() | by Teo | Medium</a></li></ul><p>You can contact me on,</p><ul><li><a href="https://www.linkedin.com/in/burak-fidan/">LinkedIn</a></li><li><a href="https://github.com/MrNtlu">Github</a></li><li><a href="https://twitter.com/BurakFNtlu">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da021f7f7534" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/jwt-authentication-and-refresh-token-in-android-with-retrofit-interceptor-authenticator-da021f7f7534">JWT Authentication and Refresh Token in Android with Retrofit Interceptor &amp; Authenticator</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching and Pagination with Paging 3 in Android & Jetpack Compose]]></title>
            <link>https://proandroiddev.com/caching-and-pagination-with-paging-3-in-android-jetpack-compose-b636aaf116ce?source=rss-a99dac39edcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b636aaf116ce</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[android-pagination]]></category>
            <category><![CDATA[android-paging]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Burak]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 15:12:16 GMT</pubDate>
            <atom:updated>2022-12-24T15:00:00.937Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1sHJ0fXVe25XDgSuvaUTXA.png" /></figure><p>In this article we’ll be implementing caching and pagination with Paging 3. We’ll use Jetpack Compose but you can also follow this article and learn from it even if you are not going to use Jetpack Compose. Except the UI layer, most of it will be similar.</p><h4>Table of Contents</h4><ul><li><a href="#67f1">Getting Started</a></li><li><a href="#3f17">API Endpoint &amp; Creating Models</a></li><li><a href="#79f7">Room &amp; Retrofit Setup</a></li><li><a href="#bbe3">Remote Mediator</a></li><li><a href="#ea3f">Pager</a></li><li>UI Layer<br>- <a href="#669c">List Setup</a><br>- <a href="#b4b1">Loading and Error Handling</a></li></ul><h3>Prerequisites</h3><p>We’ll use Room, Retrofit and Hilt in this article, so it’s better you know how they work.</p><p>I’ll also assume that you know the basics of how Paging 3 works. If you don’t, I recommend you check this article before this.</p><p><a href="https://proandroiddev.com/pagination-in-jetpack-compose-with-and-without-paging-3-e45473a352f4">Pagination in Jetpack Compose with and without Paging 3</a></p><h3>Getting Started</h3><p>App level build.gradle file,</p><pre>//Paging 3<br>def paging_version = &quot;3.1.1&quot;<br>implementation &quot;androidx.paging:paging-runtime:$paging_version&quot;<br>implementation &quot;androidx.paging:paging-compose:1.0.0-alpha17&quot;<br><br>//Retrofit<br>def retrofit_version = &quot;2.9.0&quot;<br>implementation &quot;com.squareup.retrofit2:retrofit:$retrofit_version&quot;<br>implementation &quot;com.squareup.retrofit2:converter-gson:$retrofit_version&quot;<br><br>//Hilt<br>def hilt_version = &quot;2.44&quot;<br>implementation &quot;com.google.dagger:hilt-android:$hilt_version&quot;<br>kapt &quot;com.google.dagger:hilt-compiler:$hilt_version&quot;<br>implementation &quot;androidx.hilt:hilt-navigation-compose:1.0.0&quot;<br><br>//Room<br>def room_version = &quot;2.4.3&quot;<br>implementation &quot;androidx.room:room-runtime:$room_version&quot;<br>kapt &quot;androidx.room:room-compiler:$room_version&quot;<br>implementation &quot;androidx.room:room-ktx:$room_version&quot;<br>implementation &quot;androidx.room:room-paging:$room_version&quot;<br><br>//Coil<br>implementation &quot;io.coil-kt:coil-compose:2.2.2&quot;</pre><p>Don’t forget to add Internet permission in AndroidManifest.xml,</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><h3>API Endpoint &amp; Creating Models</h3><p>We’re going to use TheMovieDB API version 3. You can <a href="https://www.themoviedb.org/signup">register</a> and get your API key from <a href="https://www.themoviedb.org/settings/api">this link</a>. We will use <a href="https://developers.themoviedb.org/3/movies/get-popular-movies">/movie/popular</a> endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*1M48SpOG1sLQR71fhhm7ZQ.png" /><figcaption>API Key</figcaption></figure><p>Response models,</p><p><em>Please put them into different files. I’ve put them into one code block to make it easier to read.</em></p><pre>data class MovieResponse(<br>    val page: Int,<br>    @SerializedName(value = &quot;results&quot;)<br>    val movies: List&lt;Movie&gt;,<br>    @SerializedName(&quot;total_pages&quot;)<br>    val totalPages: Int,<br>    @SerializedName(&quot;total_results&quot;)<br>    val totalResults: Int<br>)<br><br>@Entity(tableName = &quot;movies&quot;)<br>data class Movie(<br>    @PrimaryKey(autoGenerate = false)<br>    val id: Int,<br>    @ColumnInfo(name = &quot;original_title&quot;)<br>    @SerializedName(&quot;original_title&quot;)<br>    val ogTitle: String,<br>    @ColumnInfo(name = &quot;overview&quot;)<br>    val overview: String,<br>    @ColumnInfo(name = &quot;popularity&quot;)<br>    val popularity: Double,<br>    @ColumnInfo(name = &quot;poster_path&quot;)<br>    @SerializedName(&quot;poster_path&quot;)<br>    val posterPath: String?,<br>    @ColumnInfo(name = &quot;release_date&quot;)<br>    @SerializedName(&quot;release_date&quot;)<br>    val releaseDate: String,<br>    @ColumnInfo(name = &quot;title&quot;)<br>    val title: String,<br>    @ColumnInfo(name = &quot;page&quot;)<br>    var page: Int,<br>)</pre><p>That’s it for this part.</p><h3>Room &amp; Retrofit Setup</h3><p>Let’s start by creating and implementing Retrofit. API service will be very simple since we are going to use only 1 endpoint.</p><pre>interface MoviesApiService {<br>    @GET(&quot;movie/popular?api_key=${MOVIE_API_KEY}&amp;language=en-US&quot;)<br>    suspend fun getPopularMovies(<br>        @Query(&quot;page&quot;) page: Int<br>    ): MovieResponse<br>}</pre><p>API service is ready, we’ll create Retrofit instance at the end of this part after finishing Room implementation.</p><p>That’s it for Retrofit, now we can implement Room. Before we start, we’ll need to create a new model for caching.</p><pre>@Entity(tableName = &quot;remote_key&quot;)<br>data class RemoteKeys(<br>    @PrimaryKey(autoGenerate = false)<br>    @ColumnInfo(name = &quot;movie_id&quot;)<br>    val movieID: Int,<br>    val prevKey: Int?,<br>    val currentPage: Int,<br>    val nextKey: Int?,<br>    @ColumnInfo(name = &quot;created_at&quot;)<br>    val createdAt: Long = System.currentTimeMillis()<br>)</pre><blockquote>When remote keys are not directly associated with list items, it is best to store them in a separate table in the local database. While this can be done in the Movie table, creating a new table for the next and previous remote keys associated with a Movie allows us to have a better <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a>.</blockquote><p>This model is necessary to keep track of pagination. When we get the last item loaded from the PagingState, there’s no way to know the index of the page it belonged to. To solve this problem, we added another table that stores the next, current and previous page keys for each Movie. Keys are page numbers. createdAt is necessary for cache timeout. If you don’t need to check when was the last time we’ve cached the data, you can remove it.</p><p>Now we can create Dao for both Movie and RemoteKeys,</p><pre>@Dao<br>interface MoviesDao {<br>    @Insert(onConflict = OnConflictStrategy.REPLACE)<br>    suspend fun insertAll(movies: List&lt;Movie&gt;)<br><br>    @Query(&quot;Select * From movies Order By page&quot;)<br>    fun getMovies(): PagingSource&lt;Int, Movie&gt;<br><br>    @Query(&quot;Delete From movies&quot;)<br>    suspend fun clearAllMovies()<br>}</pre><pre>@Dao<br>interface RemoteKeysDao {<br>    @Insert(onConflict = OnConflictStrategy.REPLACE)<br>    suspend fun insertAll(remoteKey: List&lt;RemoteKeys&gt;)<br><br>    @Query(&quot;Select * From remote_key Where movie_id = :id&quot;)<br>    suspend fun getRemoteKeyByMovieID(id: Int): RemoteKeys?<br><br>    @Query(&quot;Delete From remote_key&quot;)<br>    suspend fun clearRemoteKeys()<br><br>    @Query(&quot;Select created_at From remote_key Order By created_at DESC LIMIT 1&quot;)<br>    suspend fun getCreationTime(): Long?<br>}</pre><p>Finally, we need to create Database class.</p><pre>@Database(<br>    entities = [Movie::class, RemoteKeys::class],<br>    version = 1,<br>)<br>abstract class MoviesDatabase: RoomDatabase() {<br>    abstract fun getMoviesDao(): MoviesDao<br>    abstract fun getRemoteKeysDao(): RemoteKeysDao<br>}</pre><p>That’s it. Now let’s create Retrofit &amp; Room instances.</p><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>class SingletonModule {<br>    @Singleton<br>    @Provides<br>    fun provideRetrofitInstance(): MoviesApiService =<br>        Retrofit.Builder()<br>            .baseUrl(&quot;https://api.themoviedb.org/3/&quot;)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>            .create(MoviesApiService::class.java)<br><br>    @Singleton<br>    @Provides<br>    fun provideMovieDatabase(@ApplicationContext context: Context): MoviesDatabase =<br>        Room<br>            .databaseBuilder(context, MoviesDatabase::class.java, &quot;movies_database&quot;)<br>            .build()<br><br>    @Singleton<br>    @Provides<br>    fun provideMoviesDao(moviesDatabase: MoviesDatabase): MoviesDao = moviesDatabase.getMoviesDao()<br><br>    @Singleton<br>    @Provides<br>    fun provideRemoteKeysDao(moviesDatabase: MoviesDatabase): RemoteKeysDao = moviesDatabase.getRemoteKeysDao()<br>}</pre><h3>Remote Mediator</h3><p>Before we start implementing, let’s try to understand what Remote Mediator is and why do we need it.</p><p>Remote Mediator acts as a signal from the Paging library when the app has run out of cached data. You can use this signal to load additional data from the network and store it in the local database, where a PagingSource can load it and provide it to the UI to display.</p><p>When additional data is needed, the Paging library calls the <a href="https://developer.android.com/reference/kotlin/androidx/paging/RemoteMediator#load">load()</a> method from the Remote Mediator implementation. This function typically fetches the new data from a network source and saves it to local storage.</p><p>A Remote Mediator implementation helps load paged data from the network into the database but doesn&#39;t load data directly into the UI. Instead, the app uses the database as the <a href="https://developer.android.com/jetpack/guide/data-layer#source-of-truth">source of truth</a>. In other words, the app only displays data that has been cached in the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*j0e8mepFZOGmiJf6p3uIBw.png" /></figure><p>Now, we can start implementing Remote Mediator. Let’s implement part by part. First, we’ll implement load method.</p><pre>@OptIn(ExperimentalPagingApi::class)<br>class MoviesRemoteMediator (<br>    private val moviesApiService: MoviesApiService,<br>    private val moviesDatabase: MoviesDatabase,<br>): RemoteMediator&lt;Int, Movie&gt;() {<br><br>    override suspend fun load(<br>        loadType: LoadType,<br>        state: PagingState&lt;Int, Movie&gt;<br>    ): MediatorResult {<br>        val page: Int = when (loadType) {<br>            LoadType.REFRESH -&gt; {<br>                //...<br>            }<br>            LoadType.PREPEND -&gt; {<br>                //...<br>            }<br>            LoadType.APPEND -&gt; {<br>                //...<br>            }<br>        }<br><br>        try {<br>            val apiResponse = moviesApiService.getPopularMovies(page = page)<br><br>            val movies = apiResponse.movies<br>            val endOfPaginationReached = movies.isEmpty()<br><br>            moviesDatabase.withTransaction {<br>                if (loadType == LoadType.REFRESH) {<br>                    moviesDatabase.getRemoteKeysDao().clearRemoteKeys()<br>                    moviesDatabase.getMoviesDao().clearAllMovies()<br>                }<br>                val prevKey = if (page &gt; 1) page - 1 else null<br>                val nextKey = if (endOfPaginationReached) null else page + 1<br>                val remoteKeys = movies.map {<br>                    RemoteKeys(movieID = it.id, prevKey = prevKey, currentPage = page, nextKey = nextKey)<br>                }<br><br>                moviesDatabase.getRemoteKeysDao().insertAll(remoteKeys)<br>                moviesDatabase.getMoviesDao().insertAll(movies.onEachIndexed { _, movie -&gt; movie.page = page })<br>            }<br>            return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)<br>        } catch (error: IOException) {<br>            return MediatorResult.Error(error)<br>        } catch (error: HttpException) {<br>            return MediatorResult.Error(error)<br>        }<br>    }<br>}</pre><blockquote>state parameter gives us information about the pages that were loaded before, the most recently accessed index in the list, and the PagingConfig we defined when initializing the paging stream.</blockquote><blockquote>loadType tells us whether we need to load data at the end (LoadType.APPEND) or at the beginning of the data (LoadType.PREPEND) that we previously loaded,<br>or if this the first time we’re loading data (LoadType.REFRESH).</blockquote><p>We’ll implement page attribute later, so let’s start with try/catch block. First, we make API request and get movies and set endOfPaginationReach to movies.isEmpty. If there is no item left to load, we assume it’s exhausted.</p><p>Then we start database transaction. Inside of it, we check If loadType is REFRESH and we delete caches. After that, we create RemoteKeys by mapping movies and extract movie.id. Finally, we cache all retrieved movies and remoteKeys.</p><p>Now, let’s check how we retrieve page number with RemoteKeys,</p><pre>@OptIn(ExperimentalPagingApi::class)<br>class MoviesRemoteMediator (<br>    private val moviesApiService: MoviesApiService,<br>    private val moviesDatabase: MoviesDatabase,<br>): RemoteMediator&lt;Int, Movie&gt;() {<br>    override suspend fun load(<br>        loadType: LoadType,<br>        state: PagingState&lt;Int, Movie&gt;<br>    ): MediatorResult {<br>        val page: Int = when (loadType) {<br>            LoadType.REFRESH -&gt; {<br>                val remoteKeys = getRemoteKeyClosestToCurrentPosition(state)<br>                remoteKeys?.nextKey?.minus(1) ?: 1<br>            }<br>            LoadType.PREPEND -&gt; {<br>                val remoteKeys = getRemoteKeyForFirstItem(state)<br>                val prevKey = remoteKeys?.prevKey<br>                prevKey ?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null)<br>            }<br>            LoadType.APPEND -&gt; {<br>                val remoteKeys = getRemoteKeyForLastItem(state)<br>                val nextKey = remoteKeys?.nextKey<br>                nextKey ?: return MediatorResult.Success(endOfPaginationReached = remoteKeys != null)<br>            }<br>        }<br>        <br>        try {<br>          //Previously implemented<br>        } //...<br>    }<br><br>    private suspend fun getRemoteKeyClosestToCurrentPosition(state: PagingState&lt;Int, Movie&gt;): RemoteKeys? {<br>        return state.anchorPosition?.let { position -&gt;<br>            state.closestItemToPosition(position)?.id?.let { id -&gt;<br>                moviesDatabase.getRemoteKeysDao().getRemoteKeyByMovieID(id)<br>            }<br>        }<br>    }<br><br>    private suspend fun getRemoteKeyForFirstItem(state: PagingState&lt;Int, Movie&gt;): RemoteKeys? {<br>        return state.pages.firstOrNull {<br>            it.data.isNotEmpty()<br>        }?.data?.firstOrNull()?.let { movie -&gt;<br>            moviesDatabase.getRemoteKeysDao().getRemoteKeyByMovieID(movie.id)<br>        }<br>    }<br><br>    private suspend fun getRemoteKeyForLastItem(state: PagingState&lt;Int, Movie&gt;): RemoteKeys? {<br>        return state.pages.lastOrNull {<br>            it.data.isNotEmpty()<br>        }?.data?.lastOrNull()?.let { movie -&gt;<br>            moviesDatabase.getRemoteKeysDao().getRemoteKeyByMovieID(movie.id)<br>        }<br>    }<br>}</pre><p><strong>LoadType.REFRESH, </strong>gets called when it’s the first time we’re loading data, or when refresh() is called.</p><p><strong>LoadType.PREPEND, </strong>when we need to load data at the beginning of the currently loaded data set, the load parameter is LoadType.PREPEND.</p><p><strong>LoadType.APPEND,</strong> when we need to load data at the end of the currently loaded data set, the load parameter is LoadType.APPEND.</p><p><strong>getRemoteKeyClosestToCurrentPosition</strong>, based on anchorPosition from the state, we can get the closest Movie item to that position by calling closestItemToPosition and retrieve RemoteKeys from database. If RemoteKeys is null, we return the first page number which is 1 in our example.</p><p><strong>getRemoteKeyForFirstItem</strong>, we get the first Movie item loaded from the database.</p><p><strong>getRemoteKeyForLastItem, </strong>we get the last Movie item loaded from the database.</p><p>Finally, let’s implement caching timeout,</p><pre>@OptIn(ExperimentalPagingApi::class)<br>class MoviesRemoteMediator (<br>    private val moviesApiService: MoviesApiService,<br>    private val moviesDatabase: MoviesDatabase,<br>): RemoteMediator&lt;Int, Movie&gt;() {<br><br>    override suspend fun initialize(): InitializeAction {<br>        val cacheTimeout = TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS)<br><br>        return if (System.currentTimeMillis() - (moviesDatabase.getRemoteKeysDao().getCreationTime() ?: 0) &lt; cacheTimeout) {<br>            InitializeAction.SKIP_INITIAL_REFRESH<br>        } else {<br>            InitializeAction.LAUNCH_INITIAL_REFRESH<br>        }<br>    }<br><br>    //...<br>}</pre><blockquote>initialize this method is to check whether cached data is out of date and decide whether to trigger a remote refresh. This method runs before any loading is performed, so you can manipulate the database (for example, to clear old data) before triggering any local or remote loads.</blockquote><p>In cases where the local data needs to be fully refreshed, initialize should return LAUNCH_INITIAL_REFRESH. This causes the Remote Mediator to perform a remote refresh to fully reload the data.</p><p>In cases where the local data doesn’t need to be refreshed, initialize should return SKIP_INITIAL_REFRESH. This causes the Remote Mediator to skip the remote refresh and load the cached data.</p><p>In our example, we’ve set the timeout to 1 hour and retrieve cache time from RemoteKeys database.</p><p>That’s it. You can find the RemoteMediator code <a href="https://github.com/MrNtlu/JetpackCompose-PaginationCaching/blob/595472a70e72fc56d352d65c7192c7fa9095846c/app/src/main/java/com/mrntlu/jetpackcompose_paginationcaching/repository/MoviesRemoteMediator.kt">here</a>, also you can find the full code at the end of this article.</p><h3>Pager</h3><p>This is going to be a simple one,</p><pre>const val PAGE_SIZE = 20<br><br>@HiltViewModel<br>class MoviesViewModel @Inject constructor(<br>    private val moviesApiService: MoviesApiService,<br>    private val moviesDatabase: MoviesDatabase,<br>): ViewModel() {<br>    @OptIn(ExperimentalPagingApi::class)<br>    fun getPopularMovies(): Flow&lt;PagingData&lt;Movie&gt;&gt; =<br>        Pager(<br>            config = PagingConfig(<br>                pageSize = PAGE_SIZE,<br>                prefetchDistance = 10,<br>                initialLoadSize = PAGE_SIZE,<br>            ),<br>            pagingSourceFactory = {<br>                moviesDatabase.getMoviesDao().getMovies()<br>            },<br>            remoteMediator = MoviesRemoteMediator(<br>                moviesApiService,<br>                moviesDatabase,<br>            )<br>        ).flow<br>}</pre><blockquote>This is similar to creating a Pager from a simple network data source, but there are two things you must do differently:</blockquote><blockquote>Instead of passing a PagingSource constructor directly, you must provide the query method that returns a PagingSource object from the DAO.</blockquote><blockquote>You must provide an instance of your RemoteMediator implementation as the remoteMediator parameter.</blockquote><p>The pagingSourceFactory lambda should always return a brand new PagingSource when invoked as PagingSource instances are not reusable.</p><p>Finally, we can start implementing UI Layer.</p><h3>UI Layer</h3><h4>List Setup</h4><p>List implementation will be very simple,</p><pre>@Composable<br>fun MainScreen() {<br>    val moviesViewModel = hiltViewModel&lt;MoviesViewModel&gt;()<br><br>    val movies = moviesViewModel.getPopularMovies().collectAsLazyPagingItems()<br><br>    LazyColumn {<br>        items(<br>            items = movies<br>        ) { movie -&gt;<br>            movie?.let {<br>                Row(<br>                    horizontalArrangement = Arrangement.Center,<br>                    verticalAlignment = Alignment.CenterVertically,<br>                ) {<br>                    if (movie.posterPath != null) {<br>                        var isImageLoading by remember { mutableStateOf(false) }<br><br>                        val painter = rememberAsyncImagePainter(<br>                            model = &quot;https://image.tmdb.org/t/p/w154&quot; + movie.posterPath,<br>                        )<br><br>                        isImageLoading = when(painter.state) {<br>                            is AsyncImagePainter.State.Loading -&gt; true<br>                            else -&gt; false<br>                        }<br><br>                        Box (<br>                            contentAlignment = Alignment.Center<br>                        ) {<br>                            Image(<br>                                modifier = Modifier<br>                                    .padding(horizontal = 6.dp, vertical = 3.dp)<br>                                    .height(115.dp)<br>                                    .width(77.dp)<br>                                    .clip(RoundedCornerShape(8.dp)),<br>                                painter = painter,<br>                                contentDescription = &quot;Poster Image&quot;,<br>                                contentScale = ContentScale.FillBounds,<br>                            )<br><br>                            if (isImageLoading) {<br>                                CircularProgressIndicator(<br>                                    modifier = Modifier<br>                                        .padding(horizontal = 6.dp, vertical = 3.dp),<br>                                    color = MaterialTheme.colors.primary,<br>                                )<br>                            }<br>                        }<br>                    }<br>                    Text(<br>                        modifier = Modifier<br>                            .padding(vertical = 18.dp, horizontal = 8.dp),<br>                        text = it.title<br>                    )<br>                }<br>                Divider()<br>            }<br>        }<br>    }<br>}</pre><p>For detailed explanation of list implementation, you can check <a href="https://proandroiddev.com/pagination-in-jetpack-compose-with-and-without-paging-3-e45473a352f4#a9fe">this link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*FjV4jk0QvpW-axr1dwz-FA.png" /><figcaption>List UI</figcaption></figure><h4>Loading and Error Handling</h4><pre>@Composable<br>fun MainScreen() {<br>    val moviesViewModel = hiltViewModel&lt;MoviesViewModel&gt;()<br><br>    val movies = moviesViewModel.getPopularMovies().collectAsLazyPagingItems()<br><br>    LazyColumn {<br>        //... Movie items<br><br>        val loadState = movies.loadState.mediator<br>        item {<br>            if (loadState?.refresh == LoadState.Loading) {<br>                Column(<br>                    modifier = Modifier<br>                        .fillParentMaxSize(),<br>                    horizontalAlignment = Alignment.CenterHorizontally,<br>                    verticalArrangement = Arrangement.Center,<br>                ) {<br>                    Text(<br>                        modifier = Modifier<br>                            .padding(8.dp),<br>                        text = &quot;Refresh Loading&quot;<br>                    )<br><br>                    CircularProgressIndicator(color = MaterialTheme.colors.primary)<br>                }<br>            }<br><br>            if (loadState?.append == LoadState.Loading) {<br>                Box(<br>                    modifier = Modifier<br>                        .fillMaxWidth()<br>                        .padding(16.dp),<br>                    contentAlignment = Alignment.Center,<br>                ) {<br>                    CircularProgressIndicator(color = MaterialTheme.colors.primary)<br>                }<br>            }<br><br>            if (loadState?.refresh is LoadState.Error || loadState?.append is LoadState.Error) {<br>                val isPaginatingError = (loadState.append is LoadState.Error) || movies.itemCount &gt; 1<br>                val error = if (loadState.append is LoadState.Error)<br>                        (loadState.append as LoadState.Error).error<br>                else<br>                        (loadState.refresh as LoadState.Error).error<br><br>                val modifier = if (isPaginatingError) {<br>                    Modifier.padding(8.dp)<br>                } else {<br>                    Modifier.fillParentMaxSize()<br>                }<br>                Column(<br>                    modifier = modifier,<br>                    verticalArrangement = Arrangement.Center,<br>                    horizontalAlignment = Alignment.CenterHorizontally,<br>                ) {<br>                    if (!isPaginatingError) {<br>                        Icon(<br>                            modifier = Modifier<br>                                .size(64.dp),<br>                            imageVector = Icons.Rounded.Warning, contentDescription = null<br>                        )<br>                    }<br><br>                    Text(<br>                        modifier = Modifier<br>                            .padding(8.dp),<br>                        text = error.message ?: error.toString(),<br>                        textAlign = TextAlign.Center,<br>                    )<br><br>                    Button(<br>                        onClick = {<br>                            movies.refresh()<br>                        },<br>                        content = {<br>                            Text(text = &quot;Refresh&quot;)<br>                        },<br>                        colors = ButtonDefaults.buttonColors(<br>                            backgroundColor = MaterialTheme.colors.primary,<br>                            contentColor = Color.White,<br>                        )<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Since we are using Remote Mediator, we’ll use loadState.mediator. We’ll only check refresh and append,</p><p>When refresh is LoadState.Loading we’ll show loading screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*xqneWrEbEsrnI-nJh_UeKA.png" /><figcaption>refresh Loading State</figcaption></figure><p>When append is LoadState.Loading we’ll show pagination loading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*qO7IlzoRGo1cCA-fAwTO7w.png" /><figcaption>append Loading</figcaption></figure><p>For errors, we check if either refresh or append is LoadState.Error. If we got error on refresh that means, we got an error on initial fetch and we’ll show error screen. If we got error on append that means, we got an error while paginating and we’ll show error at the end of the list.</p><p>Let’s see the final result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*OPkrkV71QeswiA-J" /></figure><p>That’s it! I hope it was useful. 👋👋</p><h4>Full Code</h4><p><a href="https://github.com/MrNtlu/JetpackCompose-PaginationCaching">MrNtlu/JetpackCompose-PaginationCaching (github.com)</a></p><h4>Sources:</h4><ul><li><a href="https://developer.android.com/topic/libraries/architecture/paging/v3-network-db">Page from network and database | Android Developers</a></li><li><a href="https://developer.android.com/topic/libraries/architecture/paging/v3-paged-data">Load and display paged data | Android Developers</a></li><li><a href="https://developer.android.com/topic/libraries/architecture/paging/v3-overview">Paging library overview | Android Developers</a></li><li><a href="https://developer.android.com/codelabs/android-paging">Android Paging Advanced codelab | Android Developers</a></li></ul><p>You can contact me on,</p><ul><li><a href="https://www.linkedin.com/in/burak-fidan/">LinkedIn</a></li><li><a href="https://github.com/MrNtlu">Github</a></li><li><a href="https://twitter.com/BurakFNtlu">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b636aaf116ce" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/caching-and-pagination-with-paging-3-in-android-jetpack-compose-b636aaf116ce">Caching and Pagination with Paging 3 in Android &amp; Jetpack Compose</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pagination in Jetpack Compose with and without Paging 3]]></title>
            <link>https://proandroiddev.com/pagination-in-jetpack-compose-with-and-without-paging-3-e45473a352f4?source=rss-a99dac39edcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45473a352f4</guid>
            <category><![CDATA[paging3]]></category>
            <category><![CDATA[android-pagination]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Burak]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 10:01:22 GMT</pubDate>
            <atom:updated>2022-12-27T15:10:47.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Co3qLokg_FEp1m_5L_7L2A.png" /></figure><h4>Table of Contents</h4><ul><li><a href="#1b2d">Gettings Started</a></li><li><a href="#9652">Setting up Retrofit</a></li><li><a href="#3674">Pagination with Paging 3</a></li><li><a href="#622d">Pagination without Paging 3</a></li></ul><h3><strong>Prerequisites</strong></h3><p>We’ll use Retrofit &amp; Hilt in this article, so it’s better you know how they work.</p><p>Also, we’ll use <a href="https://newsapi.org/">this</a> API for testing. I recommend you register and get your API key.</p><h3>Getting Started</h3><pre>def paging_version = &quot;3.1.1&quot;<br>implementation &quot;androidx.paging:paging-runtime:$paging_version&quot;<br>implementation &quot;androidx.paging:paging-compose:1.0.0-alpha17&quot;<br><br>//Other Dependencies<br>def retrofit_version = &quot;2.9.0&quot;<br>implementation &quot;com.squareup.retrofit2:retrofit:$retrofit_version&quot;<br>implementation &quot;com.squareup.retrofit2:converter-gson:$retrofit_version&quot;<br><br>def hilt_version = &quot;2.44&quot;<br>implementation &quot;com.google.dagger:hilt-android:$hilt_version&quot;<br>kapt &quot;com.google.dagger:hilt-compiler:$hilt_version&quot;<br>implementation &quot;androidx.hilt:hilt-navigation-compose:1.0.0&quot;</pre><p>Don’t forget to add Internet permission in AndroidManifest.xml,</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><h3>Setting up Retrofit</h3><p>Before we setup Retrofit, let’s see the response of the endpoint that we’ll use. Endpoint, <a href="https://newsapi.org/v2/everything?q=apple&amp;sortBy=popularity&amp;apiKey=APIKEY&amp;pageSize=20&amp;page=1"><em>https://newsapi.org/v2/everything?q=apple&amp;sortBy=popularity&amp;apiKey=APIKEY&amp;pageSize=20&amp;page=1</em></a></p><pre>{<br>  &quot;status&quot;: &quot;ok&quot;,<br>  &quot;totalResults&quot;: 65739,<br>  &quot;articles&quot;: [<br>    {<br>      &quot;source&quot;: {<br>        &quot;id&quot;: &quot;wired&quot;,<br>        &quot;name&quot;: &quot;Wired&quot;<br>      },<br>      &quot;author&quot;: &quot;Parker Hall&quot;,<br>      &quot;title&quot;: &quot;Apple Music Sing Adds &#39;Karaoke Mode&#39; to Streaming Songs&quot;,<br>      &quot;description&quot;: &quot;America&#39;s most popular music streaming service is adding the ability to turn down the vocals and sing along.&quot;,<br>      &quot;url&quot;: &quot;https://www.wired.com/story/apple-music-sing/&quot;,<br>      &quot;urlToImage&quot;: &quot;https://media.wired.com/photos/638f959b54aee410695ffa12/191:100/w_1280,c_limit/Apple-Music-Sing-Featured-Gear.jpg&quot;,<br>      &quot;publishedAt&quot;: &quot;2022-12-06T20:51:11Z&quot;,<br>      &quot;content&quot;: &quot;When it comes to advanced technical features and seamless compatibility with iOS devices, Apple Music has Spotify well and truly beaten. The Swedish streaming giant has essentially the same content l… [+3348 chars]&quot;<br>    },<br>  ]<br>}</pre><p>Response models,</p><p><em>Please put them into different files. I’ve put them into one code block to make it easier to read.</em></p><pre>data class NewsResponse(<br>    val articles: List&lt;Article&gt;,<br>    val status: String,<br>    val totalResults: Int<br>)<br>data class Source(<br>    val id: String,<br>    val name: String<br>)<br>data class Article(<br>    val author: String,<br>    val content: String,<br>    val description: String,<br>    val publishedAt: String,<br>    val source: Source,<br>    val title: String,<br>    val url: String,<br>    val urlToImage: String<br>)</pre><p>Now let’s create API Service &amp; repository, it’s going to be a simple one,</p><pre>interface NewsApiService {<br>    @GET(&quot;everything?q=apple&amp;sortBy=popularity&amp;apiKey=${Constants.API_KEY}&amp;pageSize=20&quot;)<br>    suspend fun getNews(<br>        @Query(&quot;page&quot;) page: Int<br>    ): NewsResponse<br>}</pre><p>That’s it. Now we can start implementing pagination.</p><h3>Pagination with Paging 3</h3><ul><li><a href="#cad7">Paging Source</a></li><li><a href="#b49c">Repository &amp; View Model</a></li><li><a href="#2595">UI Layer</a></li></ul><h4>Paging Source</h4><p>Let’s start by creating <a href="https://developer.android.com/reference/kotlin/androidx/paging/PagingSource">Paging Source</a>,</p><pre>class NewsPagingSource(<br>    private val newsApiService: NewsApiService,<br>): PagingSource&lt;Int, Article&gt;() {<br>    override fun getRefreshKey(state: PagingState&lt;Int, Article&gt;): Int? {<br>        return state.anchorPosition?.let { anchorPosition -&gt;<br>            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)<br>                ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)<br>        }<br>    }<br><br>    override suspend fun load(params: LoadParams&lt;Int&gt;): LoadResult&lt;Int, Article&gt; {<br>        return try {<br>            val page = params.key ?: 1<br>            val response = newsApiService.getNews(page = page)<br><br>            LoadResult.Page(<br>                data = response.articles,<br>                prevKey = if (page == 1) null else page.minus(1),<br>                nextKey = if (response.articles.isEmpty()) null else page.plus(1),<br>            )<br>        } catch (e: Exception) {<br>            LoadResult.Error(e)<br>        }<br>    }<br>}</pre><blockquote>The primary Paging library component in the repository layer is <a href="https://developer.android.com/reference/kotlin/androidx/paging/PagingSource">PagingSource</a>. Each PagingSource object defines a source of data and how to retrieve data from that source. A PagingSource object can load data from any single source, including network sources and local databases.</blockquote><p>In our example, PagingSource extends &lt;Int, Article&gt;,</p><p>Int is the type of paging key, for our case it’s index numbers for pages.</p><p>Article is the type of data loaded.</p><p>getRefreshKey, provides a key used for the initial load for the next <a href="https://developer.android.com/reference/kotlin/androidx/paging/PagingSource">PagingSource</a> due to invalidation of this <a href="https://developer.android.com/reference/kotlin/androidx/paging/PagingSource">PagingSource</a>.</p><p>load, function will be called by the Paging library to asynchronously fetch more data to be displayed as the user scrolls around.</p><p>That’s it for PagingSource, we can create repository &amp; view model.</p><h4>Repository &amp; View Model</h4><p><em>It’s not really necessary to have repository since </em><em>PagingSource acts like one, you can remove repository and make the same function calls in view model.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sBNuMGfSf2Bz3oTwgwkiQ.png" /><figcaption>Paging 3 Lifecycle</figcaption></figure><pre>class NewsRepository @Inject constructor(<br>     private val newsApiService: NewsApiService<br>) {<br>    fun getNews() = Pager(<br>        config = PagingConfig(<br>            pageSize = 20,<br>        ),<br>        pagingSourceFactory = {<br>            NewsPagingSource(newsApiService)<br>        }<br>    ).flow<br>}</pre><pre>@HiltViewModel<br>class NewsViewModel @Inject constructor(<br>    private val repository: NewsRepository,<br>): ViewModel() {<br><br>    fun getBreakingNews(): Flow&lt;PagingData&lt;Article&gt;&gt; = repository.getNews().cachedIn(viewModelScope)<br>}</pre><blockquote>The <a href="https://developer.android.com/reference/kotlin/androidx/paging/Pager">Pager</a> component provides a public API for constructing instances of PagingData that are exposed in reactive streams, based on a PagingSource object and a <a href="https://developer.android.com/reference/kotlin/androidx/paging/PagingConfig">PagingConfig</a> configuration object.</blockquote><p>PagingConfig, this class sets options regarding how to load content from a PagingSource such as how far ahead to load, the size request for the initial load, and others. The only mandatory parameter you have to define is the page size</p><p>pagingSourceFactory, function that defines how to create the PagingSource.</p><p>That’s it. Now we can implement UI and see the results.</p><h4>UI Layer</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e321e2667bbbdd7e02af6806c288c84f/href">https://medium.com/media/e321e2667bbbdd7e02af6806c288c84f/href</a></iframe><blockquote>collectAsLazyPagingItems, collects values from this <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html">Flow</a> of <a href="https://developer.android.com/reference/kotlin/androidx/paging/PagingData">PagingData</a> and represents them inside a <a href="https://developer.android.com/reference/kotlin/androidx/paging/compose/LazyPagingItems">LazyPagingItems</a> instance. The <a href="https://developer.android.com/reference/kotlin/androidx/paging/compose/LazyPagingItems">LazyPagingItems</a> instance can be used by the <a href="https://developer.android.com/reference/kotlin/androidx/paging/compose/package-summary#(androidx.compose.foundation.lazy.LazyListScope).items(androidx.paging.compose.LazyPagingItems,kotlin.Function1,kotlin.Function2)">items</a> and <a href="https://developer.android.com/reference/kotlin/androidx/paging/compose/package-summary#(androidx.compose.foundation.lazy.LazyListScope).itemsIndexed(androidx.paging.compose.LazyPagingItems,kotlin.Function2,kotlin.Function3)">itemsIndexed</a> methods from <a href="https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/LazyListScope">LazyListScope</a> in order to display the data obtained from a <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/index.html">Flow</a> of <a href="https://developer.android.com/reference/kotlin/androidx/paging/PagingData">PagingData</a>.</blockquote><p>First, we create LazyColumn and inside of it we use items which expects LazyPagingItems&lt;T&gt; and set a unique value for key. That’s it. We don’t have to do anything, as we fetch &amp; paginate data will be inserted into LazyColumn.</p><p>Since we also need to indicate when our data is being fetched, we’ll need to show loading UI to users. LazyPagingItems comes for the rescue. LazyPagingItems&lt;T&gt; has loadState object which is CombinedLoadStates.</p><p>CombinedLoadStates.source is a LoadStates type, with fields for three different types of LoadState:</p><ul><li>LoadStates.append: For the LoadState of items being fetched after the user&#39;s current position.</li><li>LoadStates.prepend: For the LoadState of items being fetched before the user&#39;s current position.</li><li>LoadStates.refresh: For the LoadState of the initial load.</li></ul><p>Each LoadState itself can be one of the following:</p><ul><li>LoadState.Loading: Items are being loaded.</li><li>LoadState.NotLoading: Items are not being loaded.</li><li>LoadState.Error: There was a loading error.</li></ul><p>For the initial load, we check articles.loadState.refresh and if state is LoadState.Loading we show loading UI.</p><p>For the pagination, we check articles.loadState.append and if state is LoadState.Loading again and show loading UI.</p><p><em>You can find the full code at the end of the article.</em></p><p>That’s it. Let’s see the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*8W2CY_FOmMyYlNnq" /><figcaption>Paging 3 Pagination</figcaption></figure><h3>Pagination without Paging 3</h3><ul><li><a href="#7050">Repository</a></li><li><a href="#5406">View Model</a></li><li><a href="#a9fe">UI Layer</a></li></ul><p>Before we start, you might ask why do we reinvent the wheel? Because in some cases Paging 3 can cause boilerplate code and increase the complexity. Implementing pagination without Paging 3 can give us more freedom and less boilerplate code.</p><p>Since we’ve already implemented ApiService, we can start by creating repository.</p><h4>Repository</h4><pre>class NewsManuelPagingRepository @Inject constructor(<br>    private val newsApiService: NewsApiService<br>) {<br>    suspend fun getNews(page: Int): Flow&lt;NewsResponse&gt; = flow {<br>       try {<br>           emit(newsApiService.getNews(page))<br>       } catch (error: Exception) {<br>           emit(NewsResponse(emptyList(), error.message ?: &quot;&quot;, 0))<br>       }<br>    }.flowOn(Dispatchers.IO)<br>}</pre><p>This is very simple and poorly executed for our example, and I do not recommend you use it this way in production. You can check these articles for more information,</p><ul><li><a href="https://proandroiddev.com/modeling-retrofit-responses-with-sealed-classes-and-coroutines-9d6302077dfe">Modeling Retrofit Responses With Sealed Classes and Coroutines | by Jaewoong Eum | ProAndroidDev</a></li><li><a href="https://proandroiddev.com/modeling-retrofit-responses-with-sealed-classes-and-coroutines-9d6302077dfe">Modeling Retrofit Responses With Sealed Classes and Coroutines | by Jaewoong Eum | ProAndroidDev</a></li></ul><h4>View Model</h4><p>Before we create view model, we’ll create enum class for List State.</p><pre>enum class ListState {<br>    IDLE,<br>    LOADING,<br>    PAGINATING,<br>    ERROR,<br>    PAGINATION_EXHAUST,<br>}</pre><p>This enum class will help us for managing state. Now we can create view model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd827be431b53ce88bd7bb0c9701d23d/href">https://medium.com/media/fd827be431b53ce88bd7bb0c9701d23d/href</a></iframe><p>First, we have 3 variables,</p><p>page is for keeping the page number. canPaginate is to check if we can paginate further or if there is any error. listState is the state variable for the UI.</p><p>Inside of init we make the first request, we are fetching first page when view model object created.</p><p>getNews function’s logic can be change depending on the endpoints and requirements. In this example, we set listState to Loading or Paginating depending on the page number and make the endpoint call.</p><p>Since endpoint returns status: &quot;ok&quot; for successful request, we check if it is successful or not. If it is successful, we insert new items to the list and set the values for canPaginate and listState.</p><p>That’s it. Logic is very simple and open to improvements. You can test it yourself and change it accordingly.</p><p>Finally, let’s see the UI.</p><h4>UI Layer</h4><p>This is going to be a little longer, so we’ll go part by part.</p><pre>val viewModel = hiltViewModel&lt;NewsManuelPagingViewModel&gt;()<br>val lazyColumnListState = rememberLazyListState()<br>val coroutineScope = rememberCoroutineScope()<br><br>val shouldStartPaginate = remember {<br>    derivedStateOf {<br>        viewModel.canPaginate &amp;&amp; (lazyColumnListState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -9) &gt;= (lazyColumnListState.layoutInfo.totalItemsCount - 6)<br>    }<br>}<br><br>val articles = viewModel.newsList</pre><p>lazyColumnListState is necessary to get the visible item info for Lazy Column.</p><p>shouldStartPaginate is to determine whether or not we should start paginating. We’ll use derivedStateOffor better performance. You can read more from <a href="https://medium.com/androiddevelopers/jetpack-compose-when-should-i-use-derivedstateof-63ce7954c11b">this link</a>.</p><p>First, we check if we can paginate or not, viewModel.canPaginate,</p><p>Then, we get the last visible item’s index, lazyColumnListState.layoutInfo.visibleItemsInfo.lastOrNull()?.index, and check if the index number is bigger than or equal to total number of item count, lazyColumnListState.layoutInfo.totalItemsCount, minus some number that you decide. I decided to set it 6 for our case. You can change it depending on your list and size.</p><pre>LaunchedEffect(key1 = shouldStartPaginate.value) {<br>    if (shouldStartPaginate.value &amp;&amp; viewModel.listState == ListState.IDLE)<br>        viewModel.getNews()<br>}</pre><p>We’ll use <a href="https://developer.android.com/jetpack/compose/side-effects#launchedeffect">LaunchedEffect</a> to start pagination and make request. Whenever shouldStartPaginate.value changes, we start the pagination and that’s it.</p><p>Now, we can create Lazy Column,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd06d7f5d8ad2dd7122daae6da27d994/href">https://medium.com/media/cd06d7f5d8ad2dd7122daae6da27d994/href</a></iframe><p>Setting state = lazyColumnListState is very important to listen pagination, don’t forget it!</p><p>I think only part that requires a little bit of an explanation is when(viewModel.listState) and it’s very simple. With the help of enum class that we’ve created earlier, we check the state of the list and show necessary UI.</p><p><em>You can find the full code at the end of the article.</em></p><p>That’s it. Let’s see the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*ULWIzJMqzMPmVsOn" /><figcaption>Pagination without Paging 3</figcaption></figure><h4>Full Code</h4><p><a href="https://github.com/MrNtlu/JetpackCompose-Pagination">MrNtlu/JetpackCompose-Pagination (github.com)</a></p><h4>Whats Next</h4><p>You can check my other blog on <strong>Caching and Pagination with Paging 3</strong>,</p><p><a href="https://proandroiddev.com/caching-and-pagination-with-paging-3-in-android-jetpack-compose-b636aaf116ce">Caching and Pagination with Paging 3 in Android &amp; Jetpack Compose</a></p><h4><strong>Sources:</strong></h4><ul><li><a href="https://betterprogramming.pub/jetpack-compose-pagination-287ea6e782e3">Jetpack Compose Pagination | by Igor Stevanovic | Better Programming</a></li><li><a href="https://developer.android.com/codelabs/android-paging-basics">https://developer.android.com/codelabs/android-paging-basics</a></li><li><a href="https://www.simplifiedcoding.net/pagination-in-jetpack-compose/">Pagination in Jetpack Compose using Paging 3 (simplifiedcoding.net)</a></li><li><a href="https://developer.android.com/codelabs/android-paging-basics#9">Android Paging Basics</a></li></ul><p>You can contact me on,</p><ul><li><a href="https://www.linkedin.com/in/burak-fidan/">LinkedIn</a></li><li><a href="https://github.com/MrNtlu">Github</a></li><li><a href="https://twitter.com/BurakFNtlu">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45473a352f4" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/pagination-in-jetpack-compose-with-and-without-paging-3-e45473a352f4">Pagination in Jetpack Compose with and without Paging 3</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AdMob Banner & Interstitial in Jetpack Compose]]></title>
            <link>https://itnext.io/admob-banner-interstitial-in-jetpack-compose-47a1b700198c?source=rss-a99dac39edcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/47a1b700198c</guid>
            <category><![CDATA[admob]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[admob-interstitial-ads]]></category>
            <dc:creator><![CDATA[Burak]]></dc:creator>
            <pubDate>Tue, 13 Dec 2022 20:07:32 GMT</pubDate>
            <atom:updated>2022-12-13T20:07:32.277Z</atom:updated>
            <content:encoded><![CDATA[<h3>AdMob Banner &amp; Interstitial Ads in Jetpack Compose</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xadnwdROWhFJF189D4ksSA.png" /></figure><p>Unfortunately, AdMob is not natively supported in Jetpack Compose yet, but that doesn’t mean that we can’t add AdMob.</p><h3>Getting Started</h3><p>I will assume you’ve already registered your app with AdMob. So, you should prepare your <a href="https://support.google.com/admob/answer/7356431?utm_source=developers.google.com">AdMob App ID</a>.</p><p>We need to add Play Service dependency first.</p><pre>implementation &#39;com.google.android.gms:play-services-ads:21.3.0&#39;</pre><p>Now, we need AdMob App ID. Open AndroidManifest.xml file and add this line.</p><pre>&lt;manifest&gt;<br>    &lt;application&gt;<br>        &lt;!-- Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 --&gt;<br>        &lt;meta-data<br>            android:name=&quot;com.google.android.gms.ads.APPLICATION_ID&quot;<br>            android:value=&quot;ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy&quot;/&gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><p>Finally, initialize Ads. (You can initialize in MainActivity onCreate)</p><pre>MobileAds.initialize(this)<br>//Optional if you want to add test device<br>val configuration = RequestConfiguration.Builder()<br>            .setTestDeviceIds(Collections.singletonList(&quot;DEVICE ID&quot;))<br>            .build()<br>MobileAds.setRequestConfiguration(configuration)</pre><h3>Banner</h3><pre>@Composable<br>fun BannerAdView() {<br>    AndroidView(<br>        modifier = Modifier<br>            .fillMaxWidth(),<br>        factory = { context -&gt;<br>            AdView(context).apply {<br>                setAdSize(AdSize.BANNER)<br>                // Add your adUnitID, this is for testing.<br>                adUnitId = &quot;ca-app-pub-3940256099942544/6300978111&quot;<br>                loadAd(AdRequest.Builder().build())<br>            }<br>        }<br>    )<br>}</pre><p>Since we don’t have native support, we’ll wrap AdView in <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary#AndroidView(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)">AndroidView</a>. You can find your adUnitId from <a href="https://support.google.com/admob/answer/7356431?utm_source=developers.google.com">this link</a> again.</p><p>That’s it for Banner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJQHqm5e0xFotnER-qaQnw.png" /></figure><h3>Interstitial</h3><p><em>I’ve come up with my way, you can change and optimize it.</em></p><p>This one is different than Banner Ad and requires different logic. We’ll create separate file for Interstitial.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4daeb4f71ad899993721c434de3b1536/href">https://medium.com/media/4daeb4f71ad899993721c434de3b1536/href</a></iframe><p>loadInterstitial function loads interstitial ad.</p><p>showInterstitial function will show the ad. After ad being dismissed by user, it’ll reload the ad. onAdDismissed function is optional. It’ll be triggered when user dismisses the ad.</p><p>removeInterstitial is used to prevent memory leak.</p><p>Also, findActivity is a custom extension function.</p><pre>fun Context.findActivity(): Activity? = when (this) {<br>    is Activity -&gt; this<br>    is ContextWrapper -&gt; baseContext.findActivity()<br>    else -&gt; null<br>}</pre><p>Now, let’s implement it inside UI. In MainActivity,</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        //...<br>        loadInterstitial(this)<br>    }<br><br>    override fun onDestroy() {<br>        removeInterstitial()<br>        super.onDestroy()<br>    }<br>}</pre><p>Finally, you can call showInterstitial from any Composable you want,</p><pre>showInterstitial(context) {<br>    //On Ad Dismiss Lambda Function<br>    //e.g. you can show dialog to the user or redirect them etc.<br>}</pre><p>That’s it! I hope it was useful. 👋👋</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*hfRspjhn1vXxtSC4RSr6tw.png" /></figure><h4>Sources:</h4><ul><li><a href="https://developers.google.com/admob/android/quick-start">Get Started | Android | Google Developers</a></li><li><a href="https://andresand.medium.com/add-admob-ad-banner-using-android-compose-9ba78c8f1591">Add AdMob Ad banner using Android Compose | by Andres Sandoval | Medium</a></li></ul><p>You can contact me on,</p><ul><li><a href="https://www.linkedin.com/in/burak-fidan/">LinkedIn</a></li><li><a href="https://github.com/MrNtlu">Github</a></li><li><a href="https://twitter.com/BurakFNtlu">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a1b700198c" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/admob-banner-interstitial-in-jetpack-compose-47a1b700198c">AdMob Banner &amp; Interstitial in Jetpack Compose</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Floating Action Button in Jetpack Compose with Material 3]]></title>
            <link>https://itnext.io/floating-action-button-in-jetpack-compose-with-material-3-10ba8bff415a?source=rss-a99dac39edcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/10ba8bff415a</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[floating-action-button]]></category>
            <dc:creator><![CDATA[Burak]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 15:07:30 GMT</pubDate>
            <atom:updated>2022-12-12T15:18:03.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nzn_MmYmxdmJJqwpKXuvA.png" /></figure><blockquote>The FAB represents the most important action on a screen. It puts key actions within reach. FAB typically contains an icon, for a FAB with text and an icon, see <a href="https://developer.android.com/reference/kotlin/androidx/compose/material3/package-summary#ExtendedFloatingActionButton(kotlin.Function0,androidx.compose.ui.Modifier,androidx.compose.ui.graphics.Shape,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.material3.FloatingActionButtonElevation,androidx.compose.foundation.interaction.MutableInteractionSource,kotlin.Function1)">ExtendedFloatingActionButton</a>.</blockquote><h3>Table of contents</h3><ul><li><a href="#714f">Getting Started</a></li><li>Floating Action Button<br>- <a href="#c409">FAB</a><br>- <a href="#0f89">Large FAB</a><br>- <a href="#866b">Small FAB &amp; Extended FAB</a></li><li><a href="#d457">FAB with SharedViewModel &amp; LazyColumn (List)</a></li></ul><h3>Getting Started</h3><p>First, let’s add Material 3 dependency. You can check the latest M3 versions on the <a href="https://developer.android.com/jetpack/androidx/releases/compose-material3">Compose Material 3 releases page</a>.</p><pre>def material3_version = &quot;1.0.1&quot;<br>implementation &quot;androidx.compose.material3:material3:$material3_version&quot;</pre><p>Optionally, if you are already using Material 2, you can follow <a href="https://material.io/blog/migrating-material-3">this blog</a> and migrate to Material 3.</p><h3>Floating Action Button</h3><p>FAB implementation is very easy. With Material 3 we have 4 different FAB options to select from.</p><h4>FAB</h4><pre>FloatingActionButton(<br>    onClick = {<br>        //OnClick Method<br>    },<br>    containerColor = MaterialTheme.colors.secondary,<br>    shape = RoundedCornerShape(16.dp),<br>) {<br>    Icon(<br>        imageVector = Icons.Rounded.Add,<br>        contentDescription = &quot;Add FAB&quot;,<br>        tint = Color.White,<br>    )<br>}</pre><p>containerColor, the color used for the background of this FAB.</p><p>shape, defines the shape of this FAB’s container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*-DnhKHlfcR1JFRHi7Mjxqg.png" /><figcaption>FAB</figcaption></figure><h4>Large FAB</h4><blockquote>Large FAB is useful when the layout calls for a clear and prominent primary action, and where a larger footprint would help the user engage. For example, when appearing on taller and larger device screens.</blockquote><pre>LargeFloatingActionButton(<br>    onClick = {<br>        //OnClick Method<br>    },<br>    containerColor = MaterialTheme.colors.secondary,<br>) {<br>    Icon(<br>        imageVector = Icons.Rounded.Add,<br>        contentDescription = &quot;Add FAB&quot;,<br>        tint = Color.White,<br>    )<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*wXonT5JHrxG_V3qy9RGYPw.png" /><figcaption>Large FAB. It doesn’t really look nice on small screen :)</figcaption></figure><h4>Small FAB &amp; Extended FAB</h4><blockquote>Small FAB is used for a secondary, supporting action, or in place of a default FAB on smaller screens. One or more small FABs can be paired with a default FAB or extended FAB.</blockquote><blockquote>Extended FAB is the most visually prominent button. Use an extended FAB on screens with long, scrolling views that require persistent access to an action, such as a check-out screen. Do not use an extended FAB in a view that cannot scroll.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0b459a9e2687d9f1b610851683dd3d0/href">https://medium.com/media/d0b459a9e2687d9f1b610851683dd3d0/href</a></iframe><p>Small FAB &amp; Extended FAB implementation is very similar to FAB. Only difference is Extended FAB has text, optional icon and expanded parameters.</p><p>expanded, controls the expansion state of this FAB. In an expanded state, the FAB will show both the icon and text. In a collapsed state, the FAB will show only the icon.</p><p>As you might’ve noticed, onClick &amp; expanded is using sharedViewModel. In the next section, we’ll implement SharedViewModel and see how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*Uy6X2cXo1eZi5FJCi_scQw.png" /><figcaption>Small FAB &amp; Extended FAB</figcaption></figure><h3>FAB with SharedViewModel &amp; LazyColumn (List)</h3><p>Let’s create SharedViewModel first,</p><pre>class SharedViewModel: ViewModel() {<br>    var fabOnClick = mutableStateOf({})<br>    var smallFabOnClick = mutableStateOf({})<br><br>    val expandedFab = mutableStateOf(true)<br>}</pre><p>Now we can create example screen,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6772f4edff32ce4932809bb9579dfa3/href">https://medium.com/media/e6772f4edff32ce4932809bb9579dfa3/href</a></iframe><blockquote>derivedStateOf is used when your state or key is changing more than you want to update your UI.</blockquote><p>If first visible item index in LazyColumn is 0, expandedFabState is true else false. When expandedFabState changes, LaunchedEffect will be triggered and update sharedViewModel.expandedFab.</p><p>Also, we use LaunchedEffect(key1 = Unit) for one time usage, when we enter the Composable it’ll set the fabOnClick and smallFabOnClick. We can set different values for different screens with the same method.</p><p>Finally, in LazyColumn we set state value to react to scroll position changes.</p><p>That’s it! I hope it was useful. 👋👋</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*O5R6Qo1KeifSEQ5b" /></figure><h4>Sources:</h4><ul><li>[<a href="https://m3.material.io/components/floating-action-button/overview">FAB — Material Design 3</a>]</li><li>[<a href="https://developer.android.com/reference/kotlin/androidx/compose/material3/package-summary#floatingactionbutton">androidx.compose.material3 | Android Developers</a>]</li><li>[<a href="https://m3.material.io/components/extended-fab/overview">Extended FAB — Material Design 3</a>]</li><li>[<a href="https://developer.android.com/reference/kotlin/androidx/compose/material3/package-summary#ExtendedFloatingActionButton(kotlin.Function0,androidx.compose.ui.Modifier,androidx.compose.ui.graphics.Shape,androidx.compose.ui.graphics.Color,androidx.compose.ui.graphics.Color,androidx.compose.material3.FloatingActionButtonElevation,androidx.compose.foundation.interaction.MutableInteractionSource,kotlin.Function1)">androidx.compose.material3 | Android Developers</a>]</li><li><a href="https://stackoverflow.com/questions/70144298/compose-remember-with-keys-vs-derivedstateof">kotlin — Compose: remember() with keys vs. derivedStateOf() — Stack Overflow</a></li></ul><p>You can contact me on,</p><ul><li><a href="https://www.linkedin.com/in/burak-fidan/">LinkedIn</a></li><li><a href="https://github.com/MrNtlu">Github</a></li><li><a href="https://twitter.com/BurakFNtlu">Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10ba8bff415a" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/floating-action-button-in-jetpack-compose-with-material-3-10ba8bff415a">Floating Action Button in Jetpack Compose with Material 3</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>