<?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 İsmail Emre Bayırlı on Medium]]></title>
        <description><![CDATA[Stories by İsmail Emre Bayırlı on Medium]]></description>
        <link>https://medium.com/@iebayirli?source=rss-a65875570486------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YoXS83lDPomt10KuJOMLZQ.jpeg</url>
            <title>Stories by İsmail Emre Bayırlı on Medium</title>
            <link>https://medium.com/@iebayirli?source=rss-a65875570486------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:34:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iebayirli/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[States in Jetpack Compose]]></title>
            <link>https://medium.com/adessoturkey/states-in-jetpack-compose-9d1cb11068fd?source=rss-a65875570486------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d1cb11068fd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[İsmail Emre Bayırlı]]></dc:creator>
            <pubDate>Tue, 30 May 2023 13:52:37 GMT</pubDate>
            <atom:updated>2024-09-04T08:05:58.613Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytauR3DuhZjUmV8Sr8LXnA.png" /></figure><p>Jetpack Compose is a modern UI toolkit for building Android applications. One of its key concepts is state management, which allows you to handle and update data in a reactive manner. In this article, we will explore the basics of state management in Jetpack Compose and discuss the important question of where to hoist state in your Compose UI hierarchy.</p><h3>Types of states</h3><p>When we talk about UI State, we come across two different definitions:</p><p><strong>Screen UI State: </strong>This is basically what you need to display on the screen. Let’s say you have a list that you obtain data from an API and show to the user. When the lists change, the UI also needs to be updated. This logic is not relevant to UI components. We refer to this kind of logic as the screen UI state. It is typically connected with other layers of the hierarchy because it contains app data.</p><p><strong>UI Element State: </strong>The<strong> </strong>UI element state is managed externally to the composable and can be moved to the calling composable function or a state holder. Unlike Android Views, where the state is managed internally, Jetpack Compose treats state as separate from the composable.</p><p>Let’s examine each one in depth:</p><h4>Screen UI State</h4><p>In Jetpack Compose, the screen UI state is determined by applying business rules. To manage this state, it is common practice to hoist the screen UI state to a screen-level state holder, often implemented as a ViewModel. By hoisting the state to the ViewModel, it allows for centralized management and coordination of the screen’s UI state, ensuring consistency and separation of concerns in the application architecture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8318a618fd4d3b16c0ef75d72777c765/href">https://medium.com/media/8318a618fd4d3b16c0ef75d72777c765/href</a></iframe><p>As seen in the example above, we have handled all the situations that may occur on the screen in the ViewModel class. This state is connected with other layers of the hierarchy and contains app data to be displayed to the user.</p><p>We used <em>Sealed Interface </em>for screen state. However, we can also use the <em>data class</em> for screen states as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac523af943cfbbb9ba107549b666c4b8/href">https://medium.com/media/ac523af943cfbbb9ba107549b666c4b8/href</a></iframe><p>While these two approaches serve the same purpose, however, the logic of handling the state in <em>composables</em> is different.</p><p>While using the <em>data class,</em> we can overlap UI components; when we use the <em>sealed interface</em>, we can show UI components belonging to only one state.</p><h4>UI Element State</h4><p>The UI element state refers to characteristics of UI elements that affect how they look and behave. For example, a UI element can be shown or hidden, have a specific font, font size, or font color. Also, the state is stored separately from the UI element itself. It can be placed in the surrounding code or a designated state holder. This allows for more flexibility and control over how the UI elements behave and appear.</p><p>Let’s examine with an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/524d18bda43d181a71e52bfec4d66332/href">https://medium.com/media/524d18bda43d181a71e52bfec4d66332/href</a></iframe><p>In the above example, we keep the component visibility state and the animation state inside the composable method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2jGOOePoCvKkQQk84qMYw.gif" /><figcaption>Expandable component demo</figcaption></figure><h3><strong>What Is State Hoisting?</strong></h3><p>State hoisting in Jetpack Compose is a pattern where the state of a composable is moved to its caller, making the composable itself stateless. This is achieved by replacing the state variable with two parameters: the current value to display and an event handler that triggers a change in the value. By hoisting the state, we ensure a single source of truth, the encapsulation of state modification within stateful composables, the ability to share state across multiple composables, the interception and modification of events by callers, and the decoupling of the state from the composable itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84beefd4ffe2f4e85c5ab88bbefac9de/href">https://medium.com/media/84beefd4ffe2f4e85c5ab88bbefac9de/href</a></iframe><p>In the official example case, you extract the <em>name</em> and the <em>onValueChange</em> out of HelloContent and move them up the tree to a HelloScreen composable that calls HelloContent.</p><p>State hoisting simplifies the understanding, reusability, and testing of the HelloContent composable. By moving the state out of HelloContent, it becomes independent of how the state is stored. This decoupling ensures that modifications or replacements of HelloScreen don’t require changes to the implementation of HelloContent.</p><p>Lastly, we will talk about state hoisting key points before finishing the article:</p><p><strong>Key Point:</strong> When hoisting state, there are three rules to help you figure out where the state should go:</p><ol><li>The state should be hoisted to at <em>least</em> the <strong>lowest common parent</strong> of all composables that use the state (read):</li></ol><p>This means that the state should be moved to a level in the composable hierarchy where all the composables that need to access or read the state can reach it. By hoisting the state to this common parent, it ensures that all relevant composables have access to the state.</p><p>2. The state should be hoisted to at <em>least</em> the <strong>highest level at which it may be changed </strong>(write):</p><p>This rule suggests that the state should be moved to a level where it can be modified or changed by the relevant composable. By hoisting the state to this highest level, it ensures that the necessary composables have the ability to update the state when needed.</p><p>3. <strong>If</strong> <strong>two states change in response to the same events,</strong> they should be <strong>hoisted together:</strong></p><p>If multiple states are modified or updated in response to the same events or actions, it is recommended to hoist them together. By hoisting them together, it maintains the relationship between these states and ensures that they are managed consistently when changes occur.</p><p>To summarize, it’s worth noting that while you can hoist state higher than these rules require, underhoisting state (not hoisting it to the appropriate level) can make it challenging, or even impossible to follow the desired unidirectional flow of data between composables. Therefore, it is important to carefully consider these rules while hoisting state to maintain a clear and manageable data flow in your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d1cb11068fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adessoturkey/states-in-jetpack-compose-9d1cb11068fd">States in Jetpack Compose</a> was originally published in <a href="https://medium.com/adessoturkey">adessoTurkey</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Jetpack Compose — Projenin Temellerini Oluşturma]]></title>
            <link>https://iebayirli.medium.com/android-jetpack-compose-projenin-temellerini-olu%C5%9Fturma-d005107b9b68?source=rss-a65875570486------2</link>
            <guid isPermaLink="false">https://medium.com/p/d005107b9b68</guid>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[İsmail Emre Bayırlı]]></dc:creator>
            <pubDate>Wed, 14 Dec 2022 08:38:24 GMT</pubDate>
            <atom:updated>2022-12-14T08:38:24.017Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Jetpack Compose — Projenin Temellerini Oluşturma</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oTsrBAbGHzFswzMTwApVA.png" /></figure><p>Öncelikler herkese selamlar. Buradaki yazımızda Jetpack Compose kullanarak bir Android projesinin temellerini oluşturmaya çalışacağız.</p><p>Projeyi oluştururken Google’ın bizlere sunduğu örnek proje olan <strong>NowInAndroid</strong> uygulamasını referans alacağız. Projenin temellerini oluşturduktan sonra, temel yapıyı koruyarak, kendi ihtiyacınıza göre ekranları ekleyip projenizi ilerletebileceksiniz.</p><p>Kısaca projeden bahsedecek olursam; projemizde genelde uygulamalarda kullandığımız yapıları kullanacağız. Projemizde bir tane BottomAppBar ve TopAppBar olacak ve 3 adet ekran içerecektir.</p><h3>1- Kütüphanelerin eklenmesi</h3><p>Dependency işlemleri için Hilt kütüphanesini, navigasyon işlemleri için Jetpack Navigation kütüphanesini ekleyeceğiz. <strong><em>app level</em> build.gradle</strong>’ı açıp, dependencies içerisine kütüphaneleri ekliyoruz. Hilt kurulumu için ise ek olarak aynı sayfa içerisinde plugins bloğuna eklemeler yapıyoruz. İşlemler sonunda gradle dosyanız aşağıdaki gibi gözükecektir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78b4e997dff8a5007cb89b94fa73eaa7/href">https://medium.com/media/78b4e997dff8a5007cb89b94fa73eaa7/href</a></iframe><p>Son olarak <strong><em>project</em> level build.gradle</strong> dosyamızı açıyoruz ve yine plugins bloğu içerisine Hilt için gerekli olan son eklemeyi gerçekleştiriyoruz. İşlem sonucunda gradle dosyanız aşağıdaki gibi gözükecektir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01859a9d09913db8df945e16bf4e9064/href">https://medium.com/media/01859a9d09913db8df945e16bf4e9064/href</a></iframe><h3>2- Hilt kurulumu</h3><p>Projemizi oluşturmaya başlamadan önce Hilt kütüphanesi için gerekli olan kurulumları yapalım. Application() class’ını extend eden bir sınıfa ihtiyacımız var. <strong><em>application</em></strong> adında bir package oluşturalım ve içerisine <strong>___Application</strong> isminde bir class yaratalım. Buradaki prefix’in ne olacağı size kalmış. Ben, oluşturacağımız uygulama için DemoAppApplication isimlendirmesini kullanacağım.</p><p>Sınıfı oluşturduktan sonra sınıfın başına <strong>@HiltAndroidApp</strong> notasyonunu ekleyeceğiz. Bu notasyon ile ilgili daha detaylı bilgiler için <a href="https://developer.android.com/training/dependency-injection/hilt-jetpack">Hilt</a> kütüphanesini inceleyebilirsiniz.</p><p>Bu işlemlerden sonra kodunuz aşağıdaki gibi gözükmesi gerekmektedir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hgdvq1nqZVZa94z0bWTYwQ.png" /></figure><p>Son olarak eklediğimiz application sınıfını uygulamamızın manifestine tanıtmamız gerekiyor. name tag’ını kullanarak ekleyeceğiz. Manifest dosyasınızın son hali aşağıdaki gibi olmalıdır:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTfvQrQRg1JxSHjucMUWRw.png" /></figure><p>Hilt kurulumumuz tamamlandı. Kod yazmaya başlayabiliriz.</p><h3>3- İlk ekranı oluşturma</h3><p>Uygulamamızda ekranlarımız presentation katmanında olacağı için <strong><em>presentation</em></strong> adında bir package oluşturuyoruz. İlk ekranımız Home ekranı olacak ve uygulama açıldığında ilk bu ekran gözükecek. Temiz bir yapı kurmak istediğimiz için <strong><em>presentation</em></strong> package’i içerisine bir de <strong><em>home</em> </strong>adında bir package oluşturalım.</p><p>Daha sonra <strong>HomeScreen</strong> adında bir Kotlin dosyası oluşturuyoruz.</p><p>Burada iki tane Composable fonksiyon oluşturacağız. Bir tanesi ekranda göstereceğimiz içeriği(UI components) barındırırken, diğer fonksiyonumuz içerikte gösterilecek datayı(state) pasladığımız ve kullanıcı etkileşimlerini(events) alıp business logic’e gönderdiğimiz, aynı zamanda navigasyonda kullanacağımız parça olacak.</p><p>Peki bu yapının bize faydası nedir? Öncelikle bu yapı, state hoisting dediğimiz bir programlama kalıbını takip ederek oluşturduğumuz bir yapı. Bu yapı sayesinde içeriği gösterdiğimiz composable metotlarımız <strong>Screen UI state’</strong>e bağımlı olmuyor. Bu sayede ise bu composable metodu daha rahat test edebiliyor, tekrar kullanabiliyor ve bug oluşturma eğiliminin de önüne geçmiş bulunuyoruz. Google’ın da önerdiği state hoisting ile alakalı daha fazla bilgi almak isterseniz takip eden uzantılardan ulaşabilirsiniz: <a href="https://developer.android.com/jetpack/compose/state">Referans-1</a>, <a href="https://developer.android.com/jetpack/compose/state-hoisting">Referans-2</a>, <a href="https://developer.android.com/topic/architecture/ui-layer/stateholders#ui-logic">Referans-3</a></p><p>HomeRoute ve HomeScreen adında iki tane composable metot oluşturalım:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15fa2349f53af63614f21f1fef508494/href">https://medium.com/media/15fa2349f53af63614f21f1fef508494/href</a></iframe><p>Yukarıda bahsettiğim gibi HomeRoute metodu içerisinde Screen UI state’i tutacak ve bunu HomeScreen adı verdiğimiz, Screen UI state bağımsız, içerisinde UI componentleri bulunan metodumuza paslayacak. Aynı zamanda HomeScreen tarafından yakalanan eventleri de business logic kısmına iletmemize aracılık edecek.</p><p><strong>3–1- Home Screen’in navigasyona hazır hale getirilmesi:</strong></p><p>Ekran kurulumu tamamlandı. Son olarak HomeScreen’i navigasyonda kullanabilir hale getireceğiz ve bu ekran bizim için hazır hale gelecek. <strong><em>presentation/home</em> </strong>paketi içerisinde <strong><em>navigation</em></strong> adında bir paket daha oluşturuyoruz. Bu paket içerisine de HomeNavigation adında bir Kotlin dosyası oluşturalım ve içini aşağıdaki gibi dolduralım:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/868f96304385a09b54d9fffef58ea1b2/href">https://medium.com/media/868f96304385a09b54d9fffef58ea1b2/href</a></iframe><p>Öncelikle Home ekranı için navigasyon esnasında kullacağımız bir string nesnesine ihtiyacımız olacak. Bunu ilk olarak tanımlıyoruz.</p><p>Daha sonra 2 tane extension metodumuz var. Bunlardan ilki <strong>NavController </strong>için yazılmış. Bu extension sayesinde Home ekranına, <strong>navConroller</strong> nesnesi olan her yerden kolaylıkla geçiş yapabiliriz. Burada default değeri null olan NavOptions’ı da dilediğimiz zaman kullanabiliriz.</p><p>Diğer extension ise <strong>NavGraphBuilder</strong> için yazılmış. Burada oluşturduğumuz ekranı compose navigation’a ekliyoruz diyebiliriz. Yukarıda da görüldüğü üzere öncelikle ilgili ekranın route’unu belirliyoruz. Daha sonra içerideki blokta da ilgili ekranı <strong>NavGraphBuilder</strong>’a paslıyoruz. Bu yaptığımız işlem sayesinde <strong>NavGraphBuilder</strong> bu route üzerinde hangi ekrana gitmesi gerektiğini biliyor. Dikkat edeceğiniz üzere ekranı paslarken <strong>HomeScreen</strong> yerine <strong>HomeRoute</strong>’u kullandık. Bunun sebebi yukarıda da bahsettiğim gibi, state hoisting yaparak HomeScreen’i state bağımsız ve tekrar kullanılabilir hale getirdik. Bundan sonra bu ekran için tek muhattabımız HomeRoute olacak.</p><p>İlk ekranımızı oluşturduk. Buna ek olarak Profile ve Favorites ekranlarını da oluşturacağız. Yazının uzunluğu sebebiyle bu ekranların oluşturulmasının detaylarını göstermeyeceğim. Uygulamanın belirli bir pattern’i takip etmesi önemli, bu sebeple diğer ekranları da yukarıda anlattığım yapıyı takip ederek oluşturabilirsiniz. Son olarak package yapısı aşağıdaki gibi gözükmelidir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*srZ5B_8y1oi8oMP4xuBYnA.png" /></figure><blockquote>Burada oluşturulan ViewModel sınıfları kafanızı karıştırmasın. Hilt’e uygun şekilde yaratılmış ve içleri boştur. Hilt viewModel kurulumunu incelemek için takip eden uzantıya bakabilirsiniz. <a href="https://developer.android.com/training/dependency-injection/hilt-jetpack">Referans-4</a></blockquote><h3>4- BottomAppBar ve TopAppBar oluşturulması</h3><h4>4–1 - BottomAppBar oluşturulması</h4><p>BottomAppBar’a Home ve Profile ekranlarını ekleyeceğiz. Yani bu ekranlar için bize bir title, selectedIconId ve unselectedIconId gerekli. Şimdi bunları oluşturmaya başlayabiliriz. İlk önce yeni bir paket oluşturuyoruz ve buna <strong><em>navigation</em></strong> ismini veriyoruz. Uygulama içerisinde sınıfların sorumlulukları ile alakalı isimlendirmeler alan paketler içinde bulunması önemli. Bu bize daha kolay bir yönetim sağlayacak. Bu paket içerisine <strong>TopLevelDestinations </strong>adında bir <strong>enum class </strong>oluşturuyoruz.</p><p>Bu enum’u doldurmadan önce bu sınıfın altına aşağıdaki sealed class’ı ekliyoruz:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/578b6a09f60270586985e0a0b083e31d/href">https://medium.com/media/578b6a09f60270586985e0a0b083e31d/href</a></iframe><p>Bu sealed class <strong>NowInAndroid</strong> projesinde bulunmaktadır. Burada kullanacağımız ikonların farklı tiplerde olsa da yönetimini kolaylaştıran bir ortak tip olarak düşünebilirsiniz.</p><p><strong>TopLevelDestinations enum’</strong>a<strong> </strong>bir constructor ekleyeceğiz. Burada oluşturduğumuz item’ları <strong>BottomNavigationItem </strong>olarak kullanacağımız için bize title, selectedIconId ve unselectedIconId olacak şekilde üç tane değişken gerekmekte. Home ve Profile ekranlarını aşağıdaki gibi enum class içerisinde tanımlıyoruz ve sınıfımız son halini alıyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b4833fb4bd3f7f6ca48dee1cb997162/href">https://medium.com/media/1b4833fb4bd3f7f6ca48dee1cb997162/href</a></iframe><blockquote>Yukarıda da göreceğiniz üzere Icon sealed class’ı sayesinde, Home için material ikonları kullanırken, Profile için drawable üzerinden vektör kullanabildik.</blockquote><p>Daha sonra ilk proje oluşturulduğunda gelen <strong><em>ui </em></strong>paketi içerisine gidip <strong><em>component </em></strong>adında bir paket oluşturabiliriz. Bu paketin içerisinde <strong>__BottomAppBar </strong>adında bir Kotlin dosyası oluşturuyoruz. Burada prefix size kalmış. Ben <strong>DemoAppBottomAppBar</strong> isimlendirmesini yapacağım.</p><p>Yine aynı ismi kullanarak bir composable fonksiyon oluşturacağız. Bu fonksiyon üç tane parametre alacak; 1- Liste halinde <strong>TopLevelDestination</strong> içerisinde oluşturduğumuz ekranları, 2- Mevcut ekranı, 3- BottomNavigationItem tıklandığı zaman aksiyon almak için, tıklanan ekranın bilgisini paslayan bir Kotlin function type parametresi. İlgili component’in son hali aşağıdaki gibi olmalıdır:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4f57e1169ec38a9c82913807f74d125/href">https://medium.com/media/a4f57e1169ec38a9c82913807f74d125/href</a></iframe><p>Peki burada ne yapıyoruz? Aslında karmaşık bir durum yok. Compose component’i olan BottomAppBar’ı oluşturuyoruz. Daha sonra TopLevelDestinations içerisinde bulunan ekranlarımız için bir BottomNavigationItem oluşturuyoruz. Seçili olup-olmama durumu için gerekli logic’i ayarlıyoruz. Tıklanma durumunda ise hangi item’a tıklandı bilgisini Kotlin function type parametresini kullanarak bir üst tarafa aktarıyoruz. Bu kısmı ilerleyen kısımlarda daha iyi anlayacaksınız.</p><blockquote>En altta bulunan extension metodu karmaşık gözükse de mantığı basit. Mevcut destination, bizim tanımladığımız TopLevelDestination’lar içerisinde var mı kontrolü yapılıyor. Buradan dönen değere göre BotttomAppBar’daki item’lar üzerinde selected-unselected durumu ayarlanıyor.</blockquote><h4>4–2- TopAppBar oluşturulması</h4><p>TopAppBar için de oluşturduğumuz <strong><em>ui/component </em></strong>paketi içerisine <strong>__TopAppBar </strong>isminde bir Kotlin dosyası oluşturuyoruz. Prefix size kalmış, ben <strong>DemoAppTopAppBar</strong> isimlendirmesini yapacağım. Dosya adıyla aynı şekilde DemoAppTopAppBar isminde bir composable fonksiyon oluşturalım. TopAppBar üzerinde sadece ilgili ekranın title değerini göstereceğimiz için burada ekstra bir logic kurmayacağız. Sınıfın son hali aşağıdaki gibi olmalıdır:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7bf12dd8ba40063056e4d38ed65c563/href">https://medium.com/media/f7bf12dd8ba40063056e4d38ed65c563/href</a></iframe><blockquote>Sınıfların, sorumlulukları ile alakalı isimlendirmeler alan paketlerin içinde olmasının yanı sıra component’lerin de ayrı sınıflarda olması, proje büyüdükten sonra yönetimi kolaylaştıracaktır.</blockquote><h3>5- AppState oluşturulması</h3><p>Öncelikle AppState nedir ve bize faydaları nelerdir kısaca buna değinmeye çalışacağım. AppState, içerisinde UI state ve UI logic’i barındıran, Activity lifecycle’ına bağımlı (Activity tekrar yaratıldığında tekrar yaratılan) bir state holder sınıfıdır. Burada oluşturulan UI scoped datalar aynı lifecycle’ı paylaştıkları için güvenle tutulabilir.</p><p>AppState sınıfını oluşturarak uygulama iskeletinde göstereceğimiz component’leri tek bir yerden rahatlıkla yönetebileceğiz. Örneğin, BottomAppBar görünürlüğünü ve navigasyonunu, aynı zamanda toolbar title’ını buradan yöneteceğiz. Daha kompleks UI state ve UI logic işlemlerini de buraya ekleyip uygulamamızı kolaylıkla genişletebileceğiz.</p><p>Öncelikle <strong><em>ui </em></strong>paketi içerisine gideceğiz ve burada <strong>__AppState </strong>isminde bir Kotlin dosyası oluşturacağız. Prefix’i dilediğiniz gibi yapabilirsiniz, ben DemoAppState olarak oluşturacağım. AppState’imiz bir state holder sınıfı olduğu için <strong>DemoAppState </strong>adında bir sınıf oluşturalım. Bu sınıf constructor’da bir <strong>NavHostController </strong>değişkeni alacaktır. Yukarıda da yazdığım gibi BottomAppBar navigasyonunu buradan yöneteceğiz ve uygulamanın diğer noktalarında ihtiyacımız olacak UI state datalarını buradan sağlayacağız.</p><p>Sınıfı oluşturduktan sonra bir tane composable metoda ihtiyacımız olacak. Bu sınıf bir state holder sınıfı ama bizim bu sınıfı çağırıldığı yerlere state olarak sağlamamız gerekli. Örneğin <strong>LazyLisState</strong> sınıfını ele alalım. Kendisi bir state holder sınıfı ve listenin state’ini tutmakta. Biz bu sınıfı composable metotlarımız içerisinde nasıl çağırıyoruz? <strong>rememberLazyListState() </strong>metodunu kullanarak.</p><p>Bu amaçla<strong> rememberDemoAppState </strong>adında bir composable metot oluşturuyoruz. Bu metodun dönüş değeri ise <strong>DemoAppState</strong> olmalı. Fakat return ederken composition cycle’a eklemek için <strong>remember{}</strong> içerisinde return edeceğiz. Aynı zamanda <strong>DemoAppState </strong>sınıfımız bir <strong>NavHostController </strong>değişkenine ihtiyaç duyduğu için bu metodumuz da parametre olarak bu değişkeni alacak ve sınıfa paslayacak. Yazıda hayal etmesi zor olabilir ama yaptığımız işlem aslında basit. Günün sonunda composable metodunu aşağıdaki gibi gözükecektir:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25ff3dfc60759bafe26b70271ab22ece/href">https://medium.com/media/25ff3dfc60759bafe26b70271ab22ece/href</a></iframe><p>Metodu oluşturduk, class’ı da oluşturup üzerinden bir geçelim. AppState class’ınız aşağıdaki gibi olacaktır:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e8a83426ece24b1d936628749aeeb69/href">https://medium.com/media/4e8a83426ece24b1d936628749aeeb69/href</a></iframe><p>UI state ve UI logic diye iki tane kavramdan bahsettim. Nedir bunlar diye aklınıza geldiyse burada netleşeceğiniz düşünüyorum. AppState sınıfımız UI ile alakalı ve bu sınıf içerisinde oluşturduğumuz <strong>değişkenler</strong> <strong>UI state</strong>’leri temsil ederken; bu sınıf içerisindeki <strong>metotlar</strong> <strong>UI logic</strong>’leri temsil etmektedir.</p><p>Peki buradaki değişkenlerimiz nedir? İsimlendirmelerden de anlaşılacağı gibi <strong>currentDestination </strong>mevcut konumu, <strong>currentTopLevelDestination </strong>değişkeninde de navigasyonda <strong>BottomAppBar’da </strong>gösterilen mevcut item’ı tutuyoruz. TopLevelDestinations listesi ise BottomAppBar’da gösterilecek itemler tutuluyor. Bu değişkeni BottomAppBar’ı oluştururken kullanacağız.</p><p>Peki buradaki metotlarımız ne yapıyor? <strong>onBackPressed() </strong>adına uygun bir şekilde backPress event’lerinde çağrılmakta. <strong>navigateTopLevelDestinations() </strong>metodu ise BottomAppBar’da gezinirken yapılan navigasyon işlemini yönettiğimiz metot olarak karşımıza çıkmaktadır. Metodun detayları da içerisinde açıklama olarak mevcuttur.</p><p>Günün sonunda AppState sınıfını ve bunu provide ettiğimiz composable metodumuzu oluşturduk.</p><p>Daha kompleks AppState işlemleri için referans projemiz NowInAndroid’i inceleyebilirsiniz. <a href="https://github.com/android/nowinandroid/blob/main/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt">Referans-5</a></p><h3>6- NavHost’un oluşturulması</h3><p>Uygulamayı tamamlamamıza az kaldı. Şimdi bize bir adet <strong>NavHost</strong> gerekli. NavHost’u xml’li yapılarda kullandığımız <strong>FragmentContainerView </strong>olarak düşünebilirsiniz. Uygulamada göstereceğimiz bütün ekranları buraya ekleyecek ve BottomAppBar navigasyon işlemleri dışında kalan navigasyon işlemlerini burada gerçekleştireceğiz.</p><p>Daha önce oluşturduğumuz <strong><em>navigation </em></strong>paketi içerisinde gidip <strong>__NavHost</strong> adında bir Kotlin dosyası oluşturuyoruz. Ben <strong>DemoAppNavHost</strong> isimlendirmesini kullanacağım. Bu dosya içerisinde <strong>DemoAppNavHost </strong>adında bir composable fonksiyon oluştuyoruz. Bu fonksiyon parametre olarak Modifier, NavHostController ve onBackClick adında 3 tane parametre alacak. Daha sonra fonksiyon bloğu içerisine navigation compose component olan <strong>NavHost </strong>oluşturup parametre olarak modifier, navHostController ve start destination’ı tanımlıyoruz. <strong>NavGraphBuilder</strong> kısmında ise ekranlarımızı ekliyoruz. Dosyanın son hali aşağıdaki gibi olacaktır:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44dc6a44125deabb75c7fcb77e8e71f9/href">https://medium.com/media/44dc6a44125deabb75c7fcb77e8e71f9/href</a></iframe><p>Her ekranımızı oluştururken bir de <strong><em>navigation</em></strong> paketi oluşturup, içerisinde <strong>__Navigation </strong>sınıfları oluşturmuştuk ve <strong>NavGraphBuilder </strong>bir extension yazıp ekranın tanıtılmasını burada gerçekleştirmiştik. <strong>NavHost</strong> içerisinde bu extension’ı kullanıyoruz. Bu sayede son derece sade, anlaşılır ve yönetimi kolay bir yapı elde ettik.</p><p>Burada Profile ekranında Favorites ekranına bir geçiş olduğunu farkedeceksiniz. Bunu da property drilling dediğimiz işlem kullanarak gerçekleştiriyoruz.</p><h4>6–1 Profile -&gt; Favorites navigasyonu</h4><p>Profile ekranında bir butonumuz mevcut. Bu butona tıklandığında Favorites ekranına geçiş yapıyoruz. Peki kurduğumuz bu yapıda bunu nasıl gerçekleştiriyoruz.</p><p>Öncelikle buton click event’ini Screen state’ini tutan ProfileRoute composable fonksiyona döndürmemiz gerekiyor. Bu tarz işlemler için ise en iyi yardımcımız Kotlin function type parametreler olarak karşımıza çıkıyor. Function Type parametreler hakkında daha detaylı bilgi almak için takip eden uzantıya gidebilirsiniz. <a href="https://kotlinlang.org/docs/lambdas.html">Referans-</a>6</p><p>Screen State’i tutan <strong>__Route </strong>isimlendirmeli fonskiyondan da <strong>NavGraphBuilder’a</strong> yazdığımız extension’a bu event’i paslıyoruz. En sonunda da buton click event’ini <strong>NavHost</strong> içerinde yakalayıp aksiyon alabiliyoruz. Bu parametre içerisinde değer de taşıyıp ekranlar arası veri de aktarma yapabiliriz. Bu işlem property drilling’e örnektir.</p><p>Görsel olarak property drilling işlemi aşağıdaki gibi olmaktadır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l17p4PwivreBKN0lV6rXZQ.png" /></figure><h3>7- App content’in oluşturulması</h3><p>Oluşturmamız gereken yapıları tamamladık. Şimdi uygulama iskeletimizi oluşturacağız. BottomAppBar ve TopAppBar’ı ekleyecek; AppState’i bağlayacak ve uygulamayı kullanıma hazır hale getireceğiz.</p><p><strong><em>ui</em></strong> paketi altına gidip <strong>__App </strong>adında bir Kotlin dosyası oluşturuyoruz. Ben <strong>DemoApp</strong> ismini kullanacağım. Bundan sonra DemoApp adında bir composable fonksiyon oluşturalım.</p><p>Bu fonksiyon appState’i parametre olarak alacak ve default değeri tanımladığımız <strong>rememberAppState() </strong>fonksiyonu olacak. Bu sayede appState’i bu composable’a state olarak provide etmiş oluyoruz.</p><p>Fonksiyon bloğu içerisinde bir Scaffold oluşturacak ve TopAppBar, BottomAppBar ve NavHost component’lerimizi ilgili yerlere ekleyeceğiz. Fonksiyonun son hali aşağıdaki gibi gözükmelidir:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47b6eb8539c60ee0a95173d3094b487d/href">https://medium.com/media/47b6eb8539c60ee0a95173d3094b487d/href</a></iframe><p>Burada component’lere ek logic’ler de ekledik. Biz sadece <strong>TopLevelDestination’</strong>da tanımladığımız ekranlar için <strong>BottomAppBar</strong> ve <strong>TopAppBar</strong> göstermek istiyoruz. Aynı zamanda <strong>TopAppBar</strong>’daki title değişkenini de <strong>TopLevelDestinations</strong>’tan almak istiyoruz. Buradaki UI logic ve UI state işlemlerini de <strong>AppState</strong> içerisinde oluşturup yönetiyoruz.</p><p>En sonunda MainActivity’e gidip oluşturduğumuz App content’i ekliyoruz ve uygulamamız çalışmaya hazır hale gelmiş oluyor. MainActivity sınıfınız aşağıdaki gibi gözükmelidir:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52c533510fec1bd60a24733ced4ff2aa/href">https://medium.com/media/52c533510fec1bd60a24733ced4ff2aa/href</a></iframe><blockquote>MainActivity sınıfına @AndroidEntryPoint notasyonunu eklemeyi unutmayın.</blockquote><h3>ÖZET</h3><p>Özet olarak bu yazımızda Compose kullanarak, anlaşılır, yönetimi ve bakımı kolay olan bir Android uygulamasının temellerini attık. Burada kullandığımız yapılar Google’ın örnek proje olarak yayınladığı <strong>NowInAndroid</strong> isimli uygulamadan alınmıştır.</p><p>Uygulamamızda BottomAppBar üzerinde iki ekranımız, bir tane de detay ekranımız bulunmaktadır. Temellerin işlendiği yazımızı referans alarak, kendi ihtiyaçlarınız doğrultusunda uygulamanızı genişletebilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*vfbm5ISLYGCEB5Zc4AyR5Q.gif" /><figcaption>Demo</figcaption></figure><p>Bir sonraki yazımızda, bu projeyi temel alarak screen state yönetimi hakkında denemeler yapacağız. Umarım faydalı bir yazı olmuştur. Vakit ayırdığınız için teşekkürler.</p><h4>Proje Repo uzantıları:</h4><ul><li><a href="https://github.com/android/nowinandroid.git">GitHub - android/nowinandroid: A fully functional Android app built entirely with Kotlin and Jetpack Compose</a></li><li><a href="https://github.com/iebayirli/ComposeDemo.git">GitHub - iebayirli/ComposeDemo</a></li></ul><h4>Yazı içerisindeki referanslar:</h4><ol><li>State and Jetpack Compose — <strong>Referans-1</strong>-<a href="https://developer.android.com/jetpack/compose/state"><em>buraya tıklayın</em></a></li><li>State Hoisting —<strong>Referans-2</strong>- <a href="https://developer.android.com/jetpack/compose/state-hoisting"><em>buraya tıklayın</em></a></li><li>State Holders and UI State —<strong>Referans-3</strong>-<a href="https://developer.android.com/topic/architecture/ui-layer/stateholders#ui-logic"><em>buraya tıklayın</em></a></li><li>Dependency Injection with Hilt —<strong>Referans-4</strong>- <a href="https://developer.android.com/training/dependency-injection/hilt-jetpack"><em>buraya tıklayın</em></a></li><li>NowInAndroid AppState —<strong>Referans-5</strong>-<a href="https://github.com/android/nowinandroid/blob/main/app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt"><em>buraya tıklayın</em></a></li><li>Kotlin High-order Functions and Lambdas —<strong>Referans-6</strong>-<a href="https://kotlinlang.org/docs/lambdas.html"><em>buraya tıklayın</em></a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d005107b9b68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Onboarding screens using Android Jetpack Compose]]></title>
            <link>https://medium.com/huawei-developers/making-onboarding-screens-using-android-jetpack-compose-bc3975eb212a?source=rss-a65875570486------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc3975eb212a</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[onboarding]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[İsmail Emre Bayırlı]]></dc:creator>
            <pubDate>Tue, 28 Dec 2021 14:30:28 GMT</pubDate>
            <atom:updated>2021-12-28T14:30:28.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1s3H-i0Olbge3aArxL6UA.png" /></figure><p>The onboarding screens are a very useful use to explain what the purpose of the app is, how and where it can be used. <em>“Onboarding is a virtual unboxing experience that helps users get started with an app.” </em>this is how Material Design explains onboarding screens.</p><p>Today I will be talking about how can we create Onboarding screen using Android’s new UI toolkit, Jetpack Compose. I am still learning the concepts and usage of this toolkit and wanted to demonstrate a useful use. I hope that will be useful.</p><p>What we will have at the end? You can see the final result below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*FnBAAoUpBVIAieXpiNGOIg.gif" /><figcaption>Demo</figcaption></figure><p>Let’s start. First we need a PagerSnapHelper. What is PagerSnapHelper?. PagerSnapHelper can help achieve a similar behavior to ViewPager.</p><p>It is a pager style snapping library in horizontal orientation. We provide the width used in the item in horizontally scrolling list, and it will calculate when to snap to the target view.</p><p>There is no PagerSnapHelper library that Google provide for Jetpack Compose(or I couldn’t find). There is a PagerSnapHelper library but I didn’t use this library completely. I wanted to achieve this behaviour therefore I only used the source code of this library. You can obtain more information about this library below;</p><p><a href="https://github.com/aakarshrestha/compose-pager-snap-helper.git">GitHub - aakarshrestha/compose-pager-snap-helper: ComposePagerSnapHelper library that works just like PagerSnapHelper for recyclerview.</a></p><p>First create a Kotlin file called PagerSnapHelper and paste the source code that we obtain from the library above;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca67940ee1dd717251d225072b3b50ab/href">https://medium.com/media/ca67940ee1dd717251d225072b3b50ab/href</a></iframe><p>Then create a Kotlin file again and named it OnboardingScene as below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfc69177fb07b6b75ea5630c67a8dc02/href">https://medium.com/media/cfc69177fb07b6b75ea5630c67a8dc02/href</a></iframe><p>So what are we doing here; First we are using a Box component because we want create overlapping components. Then we are using LazyRow() to display our lists.</p><p>First LazyRow() for our Onboarding images. The second LazyRow() for our indicator. As you can see on the second LazyRow()’s modifier we are placing our second row bottom of the view.</p><p><em>connection </em>instance is for catch scrolling events and then scroll the list item. This is for the ViewPager behavior I mentioned earlier.</p><p>We are observing the list state as <em>lazyListState </em>instance. This instance is about the image list. It holds list’s states in this way we can manage indicators. On second LazyRow() component we are managing the indicators with using this value.</p><p>If you examine the links below about Jetpack Compose, you will understand the usage and concepts more clearly;</p><p><a href="https://developer.android.com/jetpack/compose/layouts/basics">https://developer.android.com/jetpack/compose/layouts/basics</a></p><p><a href="https://developer.android.com/jetpack/compose/lists">https://developer.android.com/jetpack/compose/lists</a></p><h3>Conclusion</h3><p>In this article, we learned how to create onboarding screens using Jetpack Compose. I hope it was a useful article. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc3975eb212a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers/making-onboarding-screens-using-android-jetpack-compose-bc3975eb212a">Making Onboarding screens using Android Jetpack Compose</a> was originally published in <a href="https://medium.com/huawei-developers">Huawei Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using navigation component in ViewModels on Android(MVVM Architecture)]]></title>
            <link>https://medium.com/huawei-developers/using-navigation-component-in-viewmodels-on-android-mvvm-architecture-97ba93187eb1?source=rss-a65875570486------2</link>
            <guid isPermaLink="false">https://medium.com/p/97ba93187eb1</guid>
            <category><![CDATA[navigation-component]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[İsmail Emre Bayırlı]]></dc:creator>
            <pubDate>Wed, 22 Dec 2021 08:26:40 GMT</pubDate>
            <atom:updated>2021-12-22T08:26:40.008Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxBzXa1fb6QrKYTDt7jflw.png" /></figure><p>In this article, I will be talking about navigation. Nowadays in Android development, the best practice is to use single activity and multiple fragments. Using single activity and multiple fragments introduces a process that needs to be handled. That process is navigation between fragments.</p><p>When we use MVVM architecture in our development, we can manage navigation between fragments in ViewModels. Today I will be talking about how to handle navigations between fragments in ViewModels.</p><blockquote>In this article I will be use Kotlin for development language. Also I will use Hilt for dependency injection.</blockquote><p>We want to use an element in ViewModel that is stores data but only consumed once. In this way, we can use this element in the navigation process. We will use Event Wrapper for this goal. For more details about Event Wrapper please refer to the below link;</p><p><a href="https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150">LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case)</a></p><p>First of all, you need some configurations and classes before the tutorial. You need to integrate the Hilt dependency injection library into your app. Then we will create some base classes and a sealed class to use for navigation.</p><p>Let’s create a sealed class called NavigationCommand. This class has two subclasses. One of them stores NavDirections value. This is the value we will use for navigation between fragments. The other one is just an object. We will use this value to navigate back.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eedc36e08e206c86b9bcf1a19171e2b/href">https://medium.com/media/9eedc36e08e206c86b9bcf1a19171e2b/href</a></iframe><p>Next, we will create a BaseViewModel class. We will extend this class in our ViewModels and use some values ​​and functions in it for navigation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8b2aef26a999bf43fb77573c076b639/href">https://medium.com/media/d8b2aef26a999bf43fb77573c076b639/href</a></iframe><p>As you can see above we have an instance called <em>navigation</em>. This instance is a MutableLiveData and stores wrapped NavigationCommand value. These values ​​are wrapped with Event&lt;T&gt;.</p><p>Why are we using Event&lt;T&gt;. Because we want to use this value only once. Let’s say you show snack bar or toast messages using LiveData/MutableLiveData. When you rotate your screen the messages will be shown once again. Or you can use LiveData/MutableLiveData to show dialogs. When you rotate your screen dialog will be shown again. We don’t want this behavior. We want to store the value and we just want to use this value only once.</p><p>We created BaseViewModel, now we need BaseFragment class. To handle navigation operations in one place, we have to observe the navigation instance that we created in BaseViewModel. We will create BaseFragment as below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfe72030468c1b089da37658a9e27bc4/href">https://medium.com/media/dfe72030468c1b089da37658a9e27bc4/href</a></iframe><p>So what are we doing here? This class is an abstract class, we are initializing common properties and functions that we will use in our fragments. We are performing the abstraction in OOP.</p><p>Additionally, as you can see above, there are <em>observeNavigation </em>and <em>handleNavigation </em>functions in exist in BaseFragment. The ViewModel classes that we will use in our fragments will extend BaseViewModel class. In this way, we would observe the navigation process and perform the operation. We are observing <em>navigation </em>value <em>in observeNavigation </em>function and in <em>handleNavigation</em> function, we are performing operations here using <em>findNavController()</em>.</p><blockquote>You might think that what <em>observeNonNull </em>function is. It is an extension function I use for observe MutableLiveData/LiveData instances. You can just use Observe() function that generally use.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faef9f93e2753771f3b4e991c6e5fade/href">https://medium.com/media/faef9f93e2753771f3b4e991c6e5fade/href</a></iframe><p>Now everything is all set. Let’s see some usage. We will create two fragments then I will share the gif and Github repository.</p><p>First let’s create FirstSceneFragment;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/285dd1d1495a0a9cf55b6ec9bf4b1c5c/href">https://medium.com/media/285dd1d1495a0a9cf55b6ec9bf4b1c5c/href</a></iframe><p>As you can above there is FragmentFirstSceneBinding instance and FirstSceneViewModel that we need. Let’s create them too.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff605737482f448c2ab121d280fe6619/href">https://medium.com/media/ff605737482f448c2ab121d280fe6619/href</a></iframe><p>As you can see above, there are two functions we use to navigate in SecondSceneFragment. One is just navigation, not includes arguments. The other one is carrying some data while navigating. These are the two samples of this structure usage.</p><p>Now its time to create XML file;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b1ce2fc3a3d97cec3ef4d4a4cc6dee8/href">https://medium.com/media/1b1ce2fc3a3d97cec3ef4d4a4cc6dee8/href</a></iframe><p>We make root layout in our XML is <em>&lt;layout&gt;&lt;/layout&gt;. </em>It is a requirement for using DataBinding. As you can see in the XML file, we use the button click events here and trigger the functions from here. This is a DataBinding usage example.</p><p>Let’s say the user did some operations and after the operations are done you want to go back to the previous fragment. You can simply call navigateBack() function in ViewModel to do that operation like below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52dc1830f23676ccbba33c15d349585b/href">https://medium.com/media/52dc1830f23676ccbba33c15d349585b/href</a></iframe><h3>Demo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*zmqkBq7uGWZx89y0_ZI2Zw.gif" /><figcaption>Demo</figcaption></figure><h3><strong>Conclusion</strong></h3><p>In this article, we learned how to handle navigation operations from ViewModel in MVVM architecture. This Event wrapper usage can also use to show a dialog, snack bar, etc. I hope it was a useful article. You can find the related repository below. Thank you.</p><p><a href="https://github.com/iebayirli/NavigationDemo.git">GitHub - iebayirli/NavigationDemo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97ba93187eb1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers/using-navigation-component-in-viewmodels-on-android-mvvm-architecture-97ba93187eb1">Using navigation component in ViewModels on Android(MVVM Architecture)</a> was originally published in <a href="https://medium.com/huawei-developers">Huawei Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Easily Validate User Inputs on Android?]]></title>
            <link>https://medium.com/huawei-developers/how-to-easily-validate-user-inputs-on-android-80c8e5744de7?source=rss-a65875570486------2</link>
            <guid isPermaLink="false">https://medium.com/p/80c8e5744de7</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[input-validation]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[edittext]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[İsmail Emre Bayırlı]]></dc:creator>
            <pubDate>Thu, 04 Nov 2021 13:47:18 GMT</pubDate>
            <atom:updated>2021-11-04T13:47:18.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*QR68XexYfihDUfn5rI7Oag.png" /></figure><h4>Introduction</h4><p>In this article, I will talk about how user inputs can be easily validated in different situations. So what is validation user input? First, let’s talk about this.</p><p>Let’s say you have a login screen in your app. You get the user’s username, email, and password to log in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*ihUqL1jN6t01lg1KplFzxw.png" /></figure><p>These values can not be empty and you can define some extra input formats for these values also. E.g; Password input cannot be less than 6 and greater than 12 or the user must enter a suitable email address.</p><p>If the user does not comply with these input format rules we need to show warning messages to the user. If we do this job in the old way we need a lot of if-else condition. E.g; first we need to control input is empty or not then we need to control the input comply input formats such as password format, etc. Also, we should show different warning messages to the user for each condition. One downside of the old method is that we have to do the same things again if we want to check user input on other screens.</p><p>Thanks to the structure that I will explain in this article, we create user input formats, we will be able to use them in different scenarios. We will get rid of a lot of if-else conditions.</p><blockquote>In this article, I will use Kotlin for development and I will use ViewBinding to communicate with UI elements.</blockquote><p>Let’s start then. Let’s say you have a login screen as above. (You can get the source code below.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67bb723532005b66a188b6a49314e368/href">https://medium.com/media/67bb723532005b66a188b6a49314e368/href</a></iframe><p>You have three input formats;</p><p>1-) You want to control the inputs are empty or not.</p><p>2 -) You want to control the email address is suitable or not.</p><p>3-) You want to control the password by more than 6 and less than 12.</p><p>And you want to show different warning messages to the user for each condition and input area.</p><p>First, we will create a package named <strong><em>validator </em></strong>and then we will add another package named <strong><em>base </em></strong>to this package as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*HoxkdqKIGVAbzsx1ZKiM4w.png" /></figure><p>Then we will need a data class. We will create <strong><em>ValidateResult </em></strong>data class as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc7793dc1aede130c3edb35b8db6069f/href">https://medium.com/media/dc7793dc1aede130c3edb35b8db6069f/href</a></iframe><p>Using this class we will obtain validation result and warning messages. Then we will create the <strong><em>IValidator </em></strong>interface as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f84ce3d5388e130943085bed86d17fb0/href">https://medium.com/media/f84ce3d5388e130943085bed86d17fb0/href</a></iframe><p>We will implement this interface in our validator classes that we will create later. And we want to create such inheritance relation between validator classes, in this way, we will use these validators together as varags.</p><p>Then we will create the <strong><em>BaseValidator </em></strong>abstract class as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1404e03786200d33232f59f85989b18a/href">https://medium.com/media/1404e03786200d33232f59f85989b18a/href</a></iframe><p>The validator classes that we will create later will extend this class. We will also use the <strong><em>fun validate(vararg validators: Validator)</em></strong> method to check for multiple formats.</p><p>So far we created the necessary structure. Now, we will create validator classes for different formats. In this article, we will control if the input is empty, the e-mail address is suitable, and the password length is between 6 and 12. Therefore we will create three validator classes.</p><h4>EmptyValidator</h4><p>In the validator package, create a class named <strong><em>EmptyValidator </em></strong>as below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0762c2bf79df9bc1257354be2720fd6b/href">https://medium.com/media/0762c2bf79df9bc1257354be2720fd6b/href</a></iframe><p>This class will take a string value as user input and extends BaseValidator class. In <strong><em>validate() </em></strong>method we control the input is empty or not then we return<strong><em> ValidateResult </em></strong>value according to the validation result.</p><h4><strong><em>EmailValidator</em></strong></h4><p>In the validator package, create a class named <strong><em>EmailValidator </em></strong>as below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6616263d6e71ee314310b017c9efa44f/href">https://medium.com/media/6616263d6e71ee314310b017c9efa44f/href</a></iframe><p>In this class, we control the input is empty or not then we control email address is suitable.</p><h4>PasswordValidator</h4><p>In the validator package, create a class named <strong><em>PasswordValidator </em></strong>as below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79045166d6311ffe52c548af68c31fc0/href">https://medium.com/media/79045166d6311ffe52c548af68c31fc0/href</a></iframe><p>In this class, we control the input is empty or not then we control the input password is complying with our format.</p><p>After validators creation your package structure should look like this;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*-I8RuhTxmMTSTR4HrLy9Ew.png" /></figure><p>You can add more validator classes as above samples, using this package structure will make your code more organized.</p><h3>Examples of validators usages</h3><p>As I mentioned above, we can use these validators alone or together. In the login scenario, the username has no specific input format. We just need to control username input is empty or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1d272da897591d28623e6cb821e8b3a/href">https://medium.com/media/d1d272da897591d28623e6cb821e8b3a/href</a></iframe><p>As you can see above, we use to obtain user input from input edit text then we use <strong><em>EmptyValidator() </em></strong>alone to control username input is empty or not. After according to the validation result we show a warning to the user or a clear warning message from the input layout.</p><p>Let’s talk about multiple validator usage at the same time. For email validation, we will control the input value as below;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22e50df6b4b65b82dd25edf28243a71d/href">https://medium.com/media/22e50df6b4b65b82dd25edf28243a71d/href</a></iframe><p>We had created a function in the BaseValidator classes and this function was taking vararg IValidator values. We use this function to validate input values for different formats at the same time.</p><p>Thanks to this function, if the input is empty function it will return an empty input warning message or if the input is not suitable for email format, function will return a suitable warning message.</p><p>We will control password input by using multiple validator classes as above;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16d180c81ff4f1a09062a4effce3dc22/href">https://medium.com/media/16d180c81ff4f1a09062a4effce3dc22/href</a></iframe><p>If you want to see these usages together;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d07c9f5ada8e7237064c81d537acceb/href">https://medium.com/media/0d07c9f5ada8e7237064c81d537acceb/href</a></iframe><h3>Screenshots</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1Xm0XuIYm8oYh8j2YPBSA.png" /></figure><h3>Summary</h3><p>In this article, we talked about validating user inputs using different structures. We can create as many different input formats as we need and use them easily on different screens.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80c8e5744de7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers/how-to-easily-validate-user-inputs-on-android-80c8e5744de7">How to Easily Validate User Inputs on Android?</a> was originally published in <a href="https://medium.com/huawei-developers">Huawei Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use RecyclerView with DataBinding (MVVM)]]></title>
            <link>https://medium.com/huawei-developers/how-to-use-recyclerview-with-databinding-mvvm-211f6b69a81a?source=rss-a65875570486------2</link>
            <guid isPermaLink="false">https://medium.com/p/211f6b69a81a</guid>
            <category><![CDATA[bindingadapter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[mvvm-databinding]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[İsmail Emre Bayırlı]]></dc:creator>
            <pubDate>Mon, 05 Jul 2021 09:43:45 GMT</pubDate>
            <atom:updated>2021-07-05T09:43:45.663Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iTUmUGWF3AJRh-4-l2gFug.png" /></figure><p>The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. It provides convenience most of implementation including RecyclerView usage. Today, I will be talk about RecyclerView usage with DataBinding.</p><p>First we need to enable DataBinding in our application. Open the app level build.gradle file and add the following lines to the relevant fields:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55685d8c4f24e2f3a7ec8df3e8c16680/href">https://medium.com/media/55685d8c4f24e2f3a7ec8df3e8c16680/href</a></iframe><blockquote>After enabling Data Binding we ready to go! In this demo we used MVVM architecture and used Hilt dependency injection library for dependency injection process.</blockquote><p>Before XML creation we will create base structure for RecyclerView adapter. First we will create <em>ListAdapterItem </em>interface as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f54aa3317a682713f80ace3752f1c31/href">https://medium.com/media/8f54aa3317a682713f80ace3752f1c31/href</a></iframe><p>We will use this interface in our data classes and our base adapter abstract class. Why are we doing this? We want to gather our data classes under a single roof and make use of this interface while creating the base adapter. Thus, we can use base adapter for different data.</p><p>After <em>ListAdapterItem</em>, we will create <em>BaseViewHolder</em> class as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f287da4ce65c86a3cb45779523ca3207/href">https://medium.com/media/f287da4ce65c86a3cb45779523ca3207/href</a></iframe><p>Then we will create our <em>BaseAdapter</em> class as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e71bb243dcc3355e03175788ffbbdd/href">https://medium.com/media/d7e71bb243dcc3355e03175788ffbbdd/href</a></iframe><p>After <em>BaseAdapter </em>creation we are ready to create our XMLs. First, let’s create our RecyclerView item layout:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fff9e3b2d5d5c63344f4404ffa739d93/href">https://medium.com/media/fff9e3b2d5d5c63344f4404ffa739d93/href</a></iframe><p>We simply create a layout for our Movie data. We need to add &lt;<em>layout&gt; &lt;/layout&gt; </em>tags to our XML file to use DataBinding.</p><blockquote><a href="https://developer.android.com/topic/libraries/data-binding"><em>Click here to get more detailed information about Data Binding usage.</em></a></blockquote><p>What are we doing here? We are adding Movie data and Listener to our XML and bind the data to our UI components as above. Data comes directly into our XML from our ViewModels without any processing in our Activity/Fragment.</p><p>After RecyclerView item XML creation Let’s create <em>MovieAdapter</em> class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d4e22b69c8ff83f6ede1559238516bb/href">https://medium.com/media/4d4e22b69c8ff83f6ede1559238516bb/href</a></iframe><p>We implement <em>BaseAdapter </em>class while creating <em>MovieAdapter. </em>We create an interface for click listener events. In <em>bind </em>function<em>, </em>we are setting item and listener for our XML. These <em>movie </em>and<em> listener </em>variables comes from XML file that we created before.</p><p>We finished the part that related RecyclerView. Now let’s create MainViewModel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d3f998a92fb102510e7e85a01828f3b/href">https://medium.com/media/2d3f998a92fb102510e7e85a01828f3b/href</a></iframe><blockquote>As you can see above we are using some annotations in our MainViewModel. As I said I used the Hilt dependency injection library. These annoations relate to Hilt.</blockquote><p>In <em>MainViewModel </em>class, we implement <em>MovieListener </em>interface because we want to catch click events in our ViewModel.</p><p>We used LiveData for our Movie list data. In DataBinding, if we want to update UI elements in declarative way, we can use LiveData variables.</p><blockquote>We won’t making call to the real service to obtain movie data. Therefore we need to simultate this process. Other methods is about simulating the service call and retrieving the data.</blockquote><p>We created <em>MainViewModel </em>class. Now we are ready to create MainActivity XML file first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75c771cc3b79122e1c1e46a90e0aef37/href">https://medium.com/media/75c771cc3b79122e1c1e46a90e0aef37/href</a></iframe><p>We created <em>main_activity.xml </em>file as above. We are adding our ViewModel class to reach datas which comes from service. Also we are adding our adapter class to our XML file. We will use this variable to set adapter to the RecyclerView. We will use BindingAdapters for this process.</p><p>After XML creation Let’s configure MainActivity class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c1ed931437daf2a5a675b60224a1e4e/href">https://medium.com/media/9c1ed931437daf2a5a675b60224a1e4e/href</a></iframe><blockquote>Annotation is about Hilt.</blockquote><p><em>ActivityMainBinding </em>class is an auto-genarated class. DataBinding library creates this class after we add <em>&lt;layout&gt;&lt;/layout&gt;</em> tags in our XML files.</p><p>After, we are injecting our <em>ViewModel </em>using <em>viewModels&lt;MainViewModel&gt;().</em></p><p>In OnCreate function we are setting our content view. Before setting we are setting <em>viewModel</em> and <em>lifeCycleOwner </em>variables. This viewModel variable in line 12 come from our XML.</p><p>On line 17, we are setting RecyclerView adapter. This adapter variable, we added our XML file before.</p><p>We will create Binding Adapters for setting up the adapter, sending the list and some other operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c14129d94145b1cc3daf21fd82b677ec/href">https://medium.com/media/c14129d94145b1cc3daf21fd82b677ec/href</a></iframe><blockquote><a href="https://developer.android.com/topic/libraries/data-binding/binding-adapters">Click here to get more information about Binding Adapters.</a></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b14b6243bf163de093df090adcc8a1c/href">https://medium.com/media/7b14b6243bf163de093df090adcc8a1c/href</a></iframe><p>Don’t forget to add LayoutManager and orientation to RecyclerView. You can use BindingAdapters as above.</p><h3>Conclusion</h3><p>In this article we learned how to use RecyclerView using DataBinding. You can add Base configuration and Binding Adapters to your project and easily use RecyclerView with DataBinding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*uwjSf5dufFNCNMVt4IpTEQ.gif" /></figure><p>You can access the project from the link below:</p><p><a href="https://github.com/iebayirli/RecyclerViewWithDataBinding">iebayirli/RecyclerViewWithDataBinding</a></p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=211f6b69a81a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers/how-to-use-recyclerview-with-databinding-mvvm-211f6b69a81a">How to use RecyclerView with DataBinding (MVVM)</a> was originally published in <a href="https://medium.com/huawei-developers">Huawei Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Huawei Ads with MoPub mediation (React Native)]]></title>
            <link>https://medium.com/huawei-developers/how-to-use-huawei-ads-with-mopub-mediation-react-native-7381cd339098?source=rss-a65875570486------2</link>
            <guid isPermaLink="false">https://medium.com/p/7381cd339098</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[hms-core]]></category>
            <category><![CDATA[huawei-ads]]></category>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[mopub-mediation]]></category>
            <dc:creator><![CDATA[İsmail Emre Bayırlı]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 10:38:04 GMT</pubDate>
            <atom:updated>2021-06-18T06:44:20.464Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will talk about how to obtain Huawei ads in MoPub in React Native applications. Make sure you have successfully completed the <a href="https://medium.com/huawei-developers/how-to-use-huawei-ads-with-mopub-mediation-1f49adfdb2b1"><em>Huawei -MoPub mediation creation</em></a> part before starting the integration.</p><p>We will need the MoPub React Native SDK to integrate MoPub into our app. But there is no official React Native SDK for MoPub, therefore third party SDKs has been used in the article.</p><blockquote><a href="https://github.com/aliasad106/React-Native-Mopub-SDK">react-native-mopub-sdk</a> will be used for integration MoPub into React Native. You can use another SDK or create your own SDK for integration.</blockquote><p>Add MoPub React Native SDK mentioned above to your project. You can use sample codes in <a href="https://github.com/aliasad106/React-Native-Mopub-SDK/blob/master/example/App.js">here</a> to make sure integration is okay. After integration run project. Your project should look like this; (You can use <a href="https://developers.mopub.com/publishers/android/test/">test ad IDs</a> to make sure the integration is successful)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*Q5TR9j_vyki79AiN1i25CQ.png" /></figure><p>When you clicked “load ad” button interstitial ad will open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*jcS2r6q-bkqGQezmUqkK6A.png" /></figure><p>Rewarded ads will not work on either MoPub or Huawei in this SDK. But with some changes we will solve this problem. We will come to that later.</p><p>After you have successfully started the app, you must open the native android project on Android Studio.</p><p>Open your project-level gradle file and include Huawei’s maven repository;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*Q5THKkmVeZ2k78YX2qsCmg.png" /></figure><p>Then open your app-level build gradle, include Huawei Ads dependency (required by the adapter) and the Huawei mediation adapter;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9ea664f30c8133c0c83aa44b2d63a49/href">https://medium.com/media/c9ea664f30c8133c0c83aa44b2d63a49/href</a></iframe><blockquote><em>If your app can run only on Huawei mobile phones, you can integrate the Huawei Ads Lite SDK (Optional)</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40d291ab1353cf878c9376e0920fb2ef/href">https://medium.com/media/40d291ab1353cf878c9376e0920fb2ef/href</a></iframe><p>After successfully adding the Huawei Ads Kit and Huawei mediation adapter to your local project, the remaining steps are very easy.</p><p>We used test ad unit IDs at the beginning of the integration. Now replace the ad unit IDs with the ad unit ids after the Huawei-MoPub mediation.</p><p>After id changes ads will replace to Huawei ads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*EEaFxY7krlAO0p62V3L7tg.png" /><figcaption>Huawei Interstitial Ad</figcaption></figure><p><strong>Note: </strong>Since there is no official React Native MoPub SDK, some ad types will not work after adapter integration. Only <strong>interstitials </strong>will work in this React Native MoPub SDK. If you want to use another SDK for React Native MoPub integration, other ad types can run successfully after mediation adapter integration.</p><p>You can use <a href="https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides-V1/introduction-0000001050196714-V1">Huawei Ads Kit React Native SDK</a> for <strong>Banner </strong>and <strong>Native </strong>ads.</p><h4>For Rewarded Ads:</h4><p>When we try to use Rewarded ads in this SDK that we used to React Native MoPub integration, we will encounter “No reward found” error for Rewarded ads. If you look at the React Native MoPub SDK, you’ll notice that this error is not coming from MoPub Android SDK. Which means we can solve this problem with some changes.</p><p>Open your native android project in Android Studio. Go to react-native-mopub-sdk &gt; find and open RNMoPubRewardedVideo class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*v7itbX_nedlfnA4z2DqwCw.png" /></figure><p>We will change the <em>presentRewardedVideoAdForAdUnitID </em>function as above. In this function, the SDK sends an error that is not included in the official React Native Android SDK. We don’t need extra control.</p><p>After these changes, the rewarded ads will be shown on the MoPub side and on the Huawei Side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*mH5gOYGzRnLnOpVPftpE8Q.png" /><figcaption>Huawei Rewarded Ad</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*EP7rkVPArZzzAW6XUdaJnw.jpeg" /><figcaption>MoPub Rewarded Ad</figcaption></figure><h3>Summary</h3><p>In this article, we learned how to use MoPub-Huawei mediation adapter in React Native. Even if you use MoPub or other Mobile Ad Networks, you can increase your revenue by using Huawei Ads in your app. Thank you.</p><h3>References</h3><p>Huawei-MoPub mediation creation:</p><p><a href="https://medium.com/huawei-developers/how-to-use-huawei-ads-with-mopub-mediation-1f49adfdb2b1">How to use Huawei Ads with MoPub mediation</a></p><p>Huawei mediation adapter:</p><p><a href="https://github.com/clho40/Mediation">clho40/Mediation</a></p><p>Huawei Ads Kit React Native:</p><p><a href="https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides-V1/introduction-0000001050196714-V1">Document</a></p><p>react-native-mopub-sdk:</p><p><a href="https://github.com/aliasad106/React-Native-Mopub-SDK">aliasad106/React-Native-Mopub-SDK</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7381cd339098" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers/how-to-use-huawei-ads-with-mopub-mediation-react-native-7381cd339098">How to use Huawei Ads with MoPub mediation (React Native)</a> was originally published in <a href="https://medium.com/huawei-developers">Huawei Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Huawei Ads with MoPub mediation]]></title>
            <link>https://medium.com/huawei-developers/how-to-use-huawei-ads-with-mopub-mediation-1f49adfdb2b1?source=rss-a65875570486------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f49adfdb2b1</guid>
            <category><![CDATA[hms-ads-kit]]></category>
            <category><![CDATA[hms]]></category>
            <category><![CDATA[mopub-mediation]]></category>
            <category><![CDATA[huawei-ads]]></category>
            <category><![CDATA[mopub]]></category>
            <dc:creator><![CDATA[İsmail Emre Bayırlı]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 08:06:33 GMT</pubDate>
            <atom:updated>2021-09-30T08:20:16.748Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6BQJ2nmXYB9cEHlOTwS1A.jpeg" /></figure><p>The first option that comes to mind to make money from a mobile app is ads. Mobile Ad Networks can be use for this purpose. MoPub is one of the Mobile Ad Networks platforms. MoPub provides monetization solutions for mobile app publishers and developers around the globe.</p><p>As for Huawei, Huawei alone has shipped 240.6 million smartphones in the year of 2019 (<a href="https://www.statista.com/statistics/271539/worldwide-shipments-of-leading-smartphone-vendors-since-2007/">source</a>) therefore Huawei environment impresses us as a market with a large number of users and a very high potential. It is clear that publishers or developers can increase monetization by using Huawei Ads.</p><p>If MoPub is used in an app, Huawei ads can be easily obtained using the MoPub mediation feature and Huawei mediation adapter. In this article, MoPub mediation creation will be told.</p><blockquote>Test ad IDs will be used in this article. If you want to use your own ads, sign in to your <a href="https://id1.cloud.huawei.com/CAS/portal/loginAuth.html?validated=true&amp;themeName=red&amp;service=https%3A%2F%2Foauth-login1.cloud.huawei.com%2Foauth2%2Fv2%2Flogin%3Faccess_type%3Doffline%26client_id%3D6099200%26display%3Dpage%26flowID%3Df46aa851-2f73-4306-92d0-c8e05b4e6ad6%26h%3D1614857584.8520%26lang%3Den-us%26redirect_uri%3Dhttps%253A%252F%252Fdeveloper.huawei.com%252Fconsumer%252Fen%252Flogin%252Fhtml%252FhandleLogin.html%26response_type%3Dcode%26scope%3Dopenid%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fcountry%2Bhttps%253A%252F%252Fwww.huawei.com%252Fauth%252Faccount%252Fbase.profile%26state%3D2331448%26v%3D06ac951bc8566e39f8317e71e06018324e52840369fff73b512972525ab97f14&amp;loginChannel=89000060&amp;reqClientType=89&amp;lang=en-us&amp;clientID=6099200">Huawei Developer Console</a> and create an AdUnit.</blockquote><p>Agenda:</p><ol><li>Set up and configure your MoPub account.</li><li>Create a mediation group.</li><li>Summary.</li></ol><h3>Set up and configure your MoPub account.</h3><p>Head to <a href="https://app.mopub.com/login">MoPub Console</a> and login with your MoPub account. If you don’t have account you can easily create one.</p><p>Go to Apps &gt; New app, if your app haven’t published yet, select “My app is on the Kindle App Store or it’s unpublished” section. Then fill the all required parts (you can fill the recommend parts also) and click Save&amp;Continue.</p><p>After that, “New ad unit” section will open as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*s6MLr9x_3p2fk0lDlry7gQ.png" /></figure><p>In this article, Interstitial ads will be used for sample. Therefore fill the required are as below and click save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*yvWanbPZ44-Dy_qDXLqR6A.png" /></figure><p>After saving the ad unit, integration window will open as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*SFiyodqKUmRiIqdeTwT-CA.png" /></figure><p>You can note that Ad unit ID right now. We will use this id in out application.</p><p>Creating an app and adding an ad unit has been successfully completed.</p><h3>Create a mediation group.</h3><p>Go to Orders &gt; Create Order. Fill the required field and click “Save&amp;create line item”. After creating order adding new line item section will be open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*C6noCpV3BXcFbl-i4Nf0ag.png" /></figure><p>Here we will set the mediation parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*OqovKpvmkIjdgMWmGw1XZQ.png" /></figure><blockquote>Under this section, you will see the “Budget and Schedule” section. In this article, we won’t change anything here, but you can configure these parameters as you wish.</blockquote><p><strong>Line Item Name: </strong>The line item name can be customized here.</p><p><strong>Type &amp; priority: </strong>Type must be select<strong> Network line item</strong> for mediation.</p><p><strong>Network: </strong>Network must be selected<strong> Custom SDK network </strong>to use Huawei mediation adapter.</p><p><strong>Custom event class: </strong>In this article, the Interstitial ad will be used as an example therefore we provide the custom interstitial class information from the Huawei mediation adapter.</p><p><strong>Custom event data: </strong>The custom event data information must be provided also. We used Huawei Ads Kit Interstitial ad test id in this article.</p><p>For other types of ads such as Banner, Rewarded or Local, the relevant custom event class should be used. AdUnitID is required in custom event data.</p><p>For more information on custom event classes and custom event data, please refer to the <a href="https://github.com/clho40/Mediation/tree/main/mediation_adapter_mopub">Huawei mediation adapter for MoPub</a>.</p><p>After completing the section by following the guide, click next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*XKgw9oPgLz2sgERp2D9lwA.png" /></figure><p>Select your app and the previously created ad unit, then click Next. We won’t do anything special in the Audience targeting section, so click save once your configuration is complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*N1Rz9lJ-YaYh54yimcnIEw.png" /></figure><p>After completing the configuration, the mediation will be completed successfully.</p><h3>Summary</h3><p>In this article, we learned how to create Huawei-MoPub mediation using Huawei MoPub mediation adapter.</p><h3>References</h3><p>Mediation adapter:</p><p><a href="https://github.com/Explore-In-HMS/huawei.ads.mopub_mediation">GitHub - Explore-In-HMS/huawei.ads.mopub_mediation</a></p><p>Huawei Ads Kit:</p><p><a href="https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/publisher-service-introduction-0000001070671805">Document</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f49adfdb2b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers/how-to-use-huawei-ads-with-mopub-mediation-1f49adfdb2b1">How to use Huawei Ads with MoPub mediation</a> was originally published in <a href="https://medium.com/huawei-developers">Huawei Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instant Search Using Kotlin Flow in Search Kit]]></title>
            <link>https://medium.com/huawei-developers/instant-search-using-kotlin-flow-in-search-kit-a7c60233b881?source=rss-a65875570486------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7c60233b881</guid>
            <category><![CDATA[huawei]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[instant-search]]></category>
            <category><![CDATA[searchkit]]></category>
            <category><![CDATA[hms]]></category>
            <dc:creator><![CDATA[İsmail Emre Bayırlı]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 13:46:15 GMT</pubDate>
            <atom:updated>2021-01-26T13:46:15.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*danb26OJsuei3bAOyI7Icw.png" /></figure><p>In this article, we are going to learn how to implement the instant search feature using Kotlin Flow operator in Android app. We are going to use HMS Core Search Kit Web Search services while implementing this feature. First, let me introduce the HMS Core Search Kit briefly:</p><p>HUAWEI Search Kit fully opens Petal Search capabilities through the device-side SDK and cloud-side APIs, enabling ecosystem partners to quickly provide the optimal mobile app search experience.</p><pre><strong>Petal Search is a mobile search engine of Huawei powered by such cutting-edge technologies as big data, AI, and NLP.</strong></pre><h3>Preview:</h3><p>As you can see below, we will create an application with a search field and a list field in the UI. When the user starts typing something in the search field, the result in the list field will change instantly and smoothly. I will only use Web Search service in Search Kit for this demo. However, you can also use this structure with other Search Kit services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*_bfUXfEl8_Ir75Wk0MTy2A.gif" /><figcaption>Demo</figcaption></figure><h3>Preparation:</h3><ol><li>You need to create an app by referring to <a href="https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-get-started#createproject">Creating an AppGallery project</a> and need to <a href="https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-get-started#createapp">add an App to the Project</a>.</li><li>After adding the application to AppGalleryConnect, you need to<a href="https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/integrating-sdk-0000001057023645-V5"> integrate the HMS Core SDK</a>.</li><li>After adding the HMS Core SDK, make sure to enable Search Kit in AppGallery Connect Manage APIs.</li><li>We will be using some extra libraries during development. After you’ve integrated AppGallery Connect into your app, your project-level build.gradle file should look like this:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ecc0832f176b3bf931bb63afb00eb80/href">https://medium.com/media/4ecc0832f176b3bf931bb63afb00eb80/href</a></iframe><p>5. And your app level build.gradle file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/181f49f34ec1fcf1e6d9552e2ab85879/href">https://medium.com/media/181f49f34ec1fcf1e6d9552e2ab85879/href</a></iframe><p>Make sure the complete missing parts in your build.gradle files.</p><p>6. After adding all SDKs in your build.gradle file. Create a folder structure like below: (Move your main activity in ui package.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*DNStm_wNbXfrt5aesZUfvg.png" /><figcaption>Folder structure</figcaption></figure><p>We need obtain the token, which will be verified on the server, for using Search Kit. Therefore we will use <a href="https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/open-platform-oauth-0000001053629189-V5">OAuth 2.0-based Authentication</a> obtain a token. We will use <strong>Client Credentials </strong>method for it. We will build a service for obtain token and use Retrofit and Okhttp for it.</p><p>Now we finished preparation part. We can start coding!</p><h3>Implementation:</h3><p><strong>1.</strong>First let’s build our response class. Go to model package and create TokenResponse data class. Your TokenResponse class should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd4ba222ccfffcb00c9a199f4ac10bbc/href">https://medium.com/media/dd4ba222ccfffcb00c9a199f4ac10bbc/href</a></iframe><p>Our response contains three instance. We need access token for verifying on the server. <em>expires_time: </em>Remaining validity period of an access token, in seconds. <em>token_type: </em>Type of the returned access token. The value is always Bearer.</p><p><strong>2.</strong> After creating TokenResponse go to rest package and create an interface for our service. Your service interface should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6badbd9eee48cc37f4fdb09c50703028/href">https://medium.com/media/6badbd9eee48cc37f4fdb09c50703028/href</a></iframe><p><strong>Client Credentials </strong>mode requires three input in request. <em>grant_type</em>:<em> </em>we will set this parameter to client_credentials, which indicated the credential mode. <em>client_id</em>: OAuth 2.0 client ID created in <a href="https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/open-platform-oauth-0000001053629189-V5#EN-US_TOPIC_0000001053629189__section15949191714611">Integration Preparations</a>. <em>client_secret</em>: Client secret allocated to the client ID created in <a href="https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/open-platform-oauth-0000001053629189-V5#EN-US_TOPIC_0000001053629189__section15949191714611">Integration Preparations</a>. In interface, ApplicationConstants.requestToken should be “oauth2/v3/token”.</p><p><strong>3.</strong> After, go to di package and create module called NetworkModule. Your NetworkModule should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0e670a1721acbcb6811473c1d1321a6/href">https://medium.com/media/a0e670a1721acbcb6811473c1d1321a6/href</a></iframe><p>We used Koin for DI as you can see in the networkModule instance. We setup retrofit and okhttp instances, created our service also. In <em>provideRetrofit() </em>function<em>,</em> your base url should be:<em> </em>“https://oauth-login.cloud.huawei.com/&quot;</p><p><strong>4.</strong> Last thing for before start coding we need application class. Create an application class. Your application class should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d00f35cdba120dd9dd0cb82f80c70d07/href">https://medium.com/media/d00f35cdba120dd9dd0cb82f80c70d07/href</a></iframe><p>We start Koin with given module in here. Also we set androidContext for Koin. Don’t forget to add your application class to your manifest file.</p><p><strong>5.</strong> Let’s create our layout first. Your layout should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b513d113bf291bd32a8ea5e610965af/href">https://medium.com/media/9b513d113bf291bd32a8ea5e610965af/href</a></iframe><p>We have TextInputEditText for user input. We have RecyclerView for listing result and we have ProgressBar for showing while result changing. Don’t forget the add layout manager and orientation for RecyclerView. We won’t do it in our activity.</p><p><strong>6.</strong> Then go to MainActivity. We will use ViewBinding and DataBinding in this project. You might don’t know, kotlinx.android.synthetic is no longer a recommended practice. In MainActivity we will use ViewBinding, in our adapter we will use DataBinding. I won’t talk about adapter class, listener interface or progress dialog in this article. You can copy that classes into your project. Let’s fill the MainActivity step by step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5269f9853332a465fbfd2bf3fdaef85/href">https://medium.com/media/d5269f9853332a465fbfd2bf3fdaef85/href</a></iframe><p>We will create these instances first. As I told, i won’t talk about progress dialog and adapter, you can copy these classes into your project.</p><p>So why are we implementing CoroutineScope and what is SupervisorJob(). When we implement CoroutineScope interface as you can understand to the name our activity will have CoroutineScope. It saves us from writing CoroutineScope(…) .launch{} any coroutine or flow process we create. SupervisorJob() is for the manage these coroutine or flow process in this CoroutineScope. When we add SupervisorJob() to coroutineContext from the CoroutineScope interface, we guarantee that if any child process fails in this scope, it will not affect the other child process.</p><p>Than we inject our queryService with using conveniences provided by Koin. We create lateinit ActivityMainBinding instance that is provided by ViewBinding.</p><p>The last thing we create WebSearchRequest. We set language, region, page number(pn), number of search results returned on a page(ps), and website that we want to search. The only thing we haven’t set is q (search keyword). It will change based on user input, so we didn’t set it as static.</p><p><strong>7. </strong>Let’s go to onCreate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f89e80e576c542ee3143a0590580d1d/href">https://medium.com/media/8f89e80e576c542ee3143a0590580d1d/href</a></iframe><p>First we need inflate our layout with using binding instance. Than we need initialize SearchKitInstance. As you can see we give activity context and out application id to the <em>init() </em>function. With <em>enableLog() </em>function, we enable the debug log function also. Than we set adapter to our RecyclerView. I will talk about the other methods in other steps.</p><p><strong>8.</strong> Let’s create initAccessToken() function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a8ae413f386db2438ec8e0ac1bd52cf/href">https://medium.com/media/3a8ae413f386db2438ec8e0ac1bd52cf/href</a></iframe><p>We send a request to the service to obtain the required token in the first block (up to the withContext line). After the request, in the second block, we change the context to the Main because our context was the IO context we declared earlier. We can’t do UI operation in context of IO. We check that the access token is null, and if not, we set the credential for the Search Kit and close the progress dialog.</p><p><strong>9. </strong>Before creating initListener() function we need an extension function for TextInputEditText. Let’s create our extension first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/902402aaf2239739aaca1fa0a5a73921/href">https://medium.com/media/902402aaf2239739aaca1fa0a5a73921/href</a></iframe><p>In here, we will use this function to observe for the changes in the text, change the sate of the user input, and finally return the StateFlow.</p><pre>To get more information about StateFlow, you can look <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-state-flow/">here</a>.</pre><p><strong>10. </strong>Now we need one more function before creating initListener() function. We will create makeWebSearch(query: String) function for using Web Search service in Search Kit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19010cb107b7f9f9f975aeb363909a23/href">https://medium.com/media/19010cb107b7f9f9f975aeb363909a23/href</a></iframe><p>This function basically makes search with the specific WebSearchRequest and Search Kit webSearch instance and returns a Flow as cold stream.</p><p><strong>11. </strong>Now we created all required functions before create initListener() function. Let’s create initListener():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c3a0a88777477a1217ab9bba5faa349/href">https://medium.com/media/8c3a0a88777477a1217ab9bba5faa349/href</a></iframe><p>Let’s learn the operator details we used above.</p><ul><li><strong>Debounce: </strong>The dobunce operator handles the case when the user changes input in a very short time. Without timeout value that we give debounce, there will be too many network calls and we don’t want it. It will wait to make a network call in the provided time. If another input value comes in during this time, it will ignore the previous input and start waiting again at the provided time. <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/debounce.html">Click here to get more information about debounce.</a></li><li><strong>Filter: </strong>In this case, we used the filter operator to filter an empty user input. We avoid unnecessary network calls and when input is empty we clear the list.</li><li><strong>DistinctUntilChanged: </strong>The distinctUntilChanged operator is used to avoid duplicate network calls. It suppress duplicate consecutive items emitted by the source. <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/distinct-until-changed.html">Click here to get more information about distinctUntilChanged.</a></li><li><strong>FlatMapLatest: </strong>In flatMapLatest, when the original flow emits a new value, the previous flow produced by transform block is cancelled. So what does it means? Let’s say the user typed something in the search field. We start the search process, but the user changes his mind and looks for something else. So the user is not interested in the previous value. Therefore, we need to restart the search process with the last input. We get this feature with flatMapLatest, it provides the result for the last search entry and ignores the rest. <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/flat-map-latest.html">Click here to get more information about flatMapLatest.</a></li></ul><pre>We do WebSearch in FlatMapLatest and if we get any errors we pass the empty list to RecyclerView adapter.</pre><p>Implementation is finished. Now your app is ready to use!</p><h3>Conclusion</h3><p>In this article, we learned how to use Search Kit services with instant search feature. We only used WebSearch service but you can combine other Search Kit services with following this article. You can find more information about Search Kit in <a href="https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001055591730">here</a>. Thank you.</p><h3>Repository:</h3><p><a href="https://github.com/iebayirli/InstantSearchSample.git">iebayirli/InstantSearchSample</a></p><h3>Reference</h3><p><a href="https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001055591730">Document</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7c60233b881" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers/instant-search-using-kotlin-flow-in-search-kit-a7c60233b881">Instant Search Using Kotlin Flow in Search Kit</a> was originally published in <a href="https://medium.com/huawei-developers">Huawei Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharing file(s) between Huawei Phones with Share Engine | Kotlin]]></title>
            <link>https://medium.com/huawei-developers/sharing-file-s-between-huawei-phones-with-share-engine-kotlin-8d26865934df?source=rss-a65875570486------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d26865934df</guid>
            <category><![CDATA[hms-core]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[share]]></category>
            <category><![CDATA[huawei]]></category>
            <category><![CDATA[hms]]></category>
            <dc:creator><![CDATA[İsmail Emre Bayırlı]]></dc:creator>
            <pubDate>Tue, 17 Nov 2020 20:35:52 GMT</pubDate>
            <atom:updated>2020-11-17T20:35:52.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDRPXCSo9Ziy_QixQXupIQ.png" /></figure><p>As a cross-device file transfer solution, Huawei Share uses Bluetooth to discover nearby devices and authenticate connections, then sets up peer-to-peer Wi-Fi channels, so as to allow file transfers between phones, PCs, and other devices. It delivers <strong>stable file transfer speeds that can exceed 80 Mbps</strong> if the third-party device and environment allow. With Share Engine, developers can use Huawei Share abilities in their apps.</p><p>Share engines offers three SDK packages for Android, Linux, and Windows based apps and devices. But if we want to share file (s) between Huawei Phones, we don’t need any SDK package. Let’s talk about Share Engine.</p><h4>Working Principles</h4><p>Huawei Share uses Bluetooth to discover nearby devices and authenticate connections, then sets up peer-to-peer Wi-Fi channels, so as to allow file transfers between phones, PCs, and other devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*qGV5jrSbI267B0Uq" /></figure><p>To ensure user experience, Huawei Share uses reliable core technologies in each phase of file transfer. You can find more information about Share Engine in <a href="https://developer.huawei.com/consumer/en/doc/development/connectivity-Guides/share-introduction">here</a>. Let’s do some coding!</p><p>As I mentioned earlier, we don’t need any SDK but we do have some requirements for Share Engine.</p><ul><li>Android Studio development environment V3.0.1 or later is recommended.</li><li>Phone development: Huawei phones that run EMUI 9.0 or later and support Huawei Share.</li></ul><p>After you make sure you meet the requirements we can start coding.</p><p><strong>1- </strong>First we need read external storage permission for reading file(s) from storage. Let’s add permission in Manifest file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fefe21d0df21d874780cbaa0470c88b/href">https://medium.com/media/2fefe21d0df21d874780cbaa0470c88b/href</a></iframe><p><strong>2- </strong>I will use Activity Result API for starting activities or getting user permissions. Therefore you need to add Activity Result API SDK into your app level build.gradle file. Your file should look like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e167b98ae1b0ad98041fc98886d08184/href">https://medium.com/media/e167b98ae1b0ad98041fc98886d08184/href</a></iframe><p><strong>3- </strong>After adding permission and SDK initialization, let’s create layout.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2fd39945b6724f4eedfcb053a76d012/href">https://medium.com/media/f2fd39945b6724f4eedfcb053a76d012/href</a></iframe><p><strong>4- </strong>After, let’s create some functions and variables that we will use in later. First we need storage permission. As i mentioned earlier i will use Activity Result API for this. Sample code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b6ede531c804fc42f3386364caf7167/href">https://medium.com/media/4b6ede531c804fc42f3386364caf7167/href</a></iframe><p><strong>5- </strong>For getting file from storage we’ll create an instance. After getting file we’ll send selected file in here: (Sending File)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be4f83fea5feb57faa3a0c2ac9a6e44a/href">https://medium.com/media/be4f83fea5feb57faa3a0c2ac9a6e44a/href</a></iframe><p><strong>6- </strong>User can select multiple file for sending. For this purpose we will create another instance and we’ll send selected files from here: (Sending multiple files)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a26e8fff2791fc89d95afa6d9b6536d0/href">https://medium.com/media/a26e8fff2791fc89d95afa6d9b6536d0/href</a></iframe><p><strong>7- </strong>In variables that we created before, you may notice there is a method called <em>createIntent(). </em>These method gets an intent instance and returns a unit block with an intent instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0c9cc1f1b35b8625a5da36802accff8/href">https://medium.com/media/b0c9cc1f1b35b8625a5da36802accff8/href</a></iframe><p>So what are we doing in this method. As i mentioned earlier, we don’t need any SDK for using Share Engine between Huawei Phones but we need to give package name for intents. And these <em>type, packages, </em>and <em>flags</em> are common to all methods such as sharing text, file(s). We are initializing our intent’s common properties and returns the intent as ready to use.</p><p><strong>8- </strong>We can also send text between Huawei Phones: (Sending texts)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/345f511717336c9d44e94b43062b7cdc/href">https://medium.com/media/345f511717336c9d44e94b43062b7cdc/href</a></iframe><p><strong>9- </strong>We created our instances, before we start the project we need to control if phone supports Share Engine. We do this in <em>onCreate():</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/009c6b9c8d176b5ce0cee2a6365aa460/href">https://medium.com/media/009c6b9c8d176b5ce0cee2a6365aa460/href</a></iframe><p>Let’s bring them all the pieces together. Here is our MainActivity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47d76e6489e44983156ce6cea1bf6841/href">https://medium.com/media/47d76e6489e44983156ce6cea1bf6841/href</a></iframe><p>Here are the outputs;</p><p>Sharing text:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*_h_icKMYR3zuNzuuA5l1FQ.gif" /></figure><p>Sharing a file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*i0eg6RCbRHk4WxTQmlvzIw.gif" /></figure><p>Sharing files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*E-j6MQTaO9VRzsQxoTWDVA.gif" /></figure><h3>Conclusion</h3><p>In this article we learned how to share file(s) between Huawei Phones with using Share Engine. You can find more information about Share Engine in here:</p><p><a href="https://developer.huawei.com/consumer/en/doc/development/connectivity-Guides/share-introduction">Document</a></p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d26865934df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/huawei-developers/sharing-file-s-between-huawei-phones-with-share-engine-kotlin-8d26865934df">Sharing file(s) between Huawei Phones with Share Engine | Kotlin</a> was originally published in <a href="https://medium.com/huawei-developers">Huawei Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>