<?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 Suriya Wongkasum on Medium]]></title>
        <description><![CDATA[Stories by Suriya Wongkasum on Medium]]></description>
        <link>https://medium.com/@jojoekung?source=rss-c64ceb16508e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hZOv8wOWdmN7g0Bq2pUZVg.jpeg</url>
            <title>Stories by Suriya Wongkasum on Medium</title>
            <link>https://medium.com/@jojoekung?source=rss-c64ceb16508e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 02:30:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jojoekung/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[Data Binding with view model Part 4]]></title>
            <link>https://medium.com/@jojoekung/data-binding-with-view-model-part-4-7e986f9f15f3?source=rss-c64ceb16508e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e986f9f15f3</guid>
            <category><![CDATA[data-binding]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Suriya Wongkasum]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 03:31:45 GMT</pubDate>
            <atom:updated>2020-08-13T08:07:31.232Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*xSaFx4q_9JutmhorcCCvMQ.png" /></figure><p>หลังจากที่เราทำส่วนแสดงผลข้อมูลโน็ตเสร็จแล้ว ใน Part 4 นี้ก็จะเป็นส่วนการแสดงผลรายละเอียดข้อมูลโน็ต จากที่เราใส่ action เมื่อกด item view ให้เปิดไปหน้า NoteDetailFragment พร้อมทั้งส่ง noteId ผ่าน bundle ไปแล้ว</p><pre>val adapter = NoteAdapter(OnClickItemListener <strong>{<br>    </strong>val bundle = <em>bundleOf</em>(&quot;noteId&quot; <em>to </em><strong>it</strong>)<br>    this.<em>findNavController</em>()<br>        .navigate(R.id.<em>action_homeFragment_to_detailFragment</em>, bundle)<br><strong>}</strong>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*p5m29KJjMrAn2y9iO2pc-A.png" /></figure><p>ภาพรวมหลักของหน้า NoteDetailFragment หลักประกอบไปด้วย</p><ul><li>แสดง tittle: หัวข้อโน็ต</li><li>รายละเอียดโน็ต</li><li>ปุ่มลบรายการโน็ต</li><li>ปุ่มแก้ไขข้อมูลโน็ต</li><li>เริ่มจากพัฒนาสร้าง</li></ul><p>เริ่มจากสร้าง NoteDetailViewModel class ที่ใส่ Business logic ที่เกี่ยวข้องกับการแสดงรายละเอียดโน็ตทั้งหมด และ view model factory แล้วก็ทำการผูก data เข้ากับ view model ที่ NoteDetailFragment</p><pre>class NoteDetailFragment : Fragment() {<br><br>    override fun onCreateView(<br>        inflater: LayoutInflater, container: ViewGroup?,<br>        savedInstanceState: Bundle?<br>    ): View? {<br><br>        val binding: DetailFragmentBinding =<br>            DataBindingUtil.inflate(inflater, R.layout.<em>detail_fragment</em>, container, false)<br><br>        val dataSource = NoteDatabase.getInstance(requireContext()).noteDao<br>        <em>arguments</em>?.getLong(&quot;noteId&quot;)?.<em>let </em><strong>{ </strong>noteId <strong>-&gt;<br>            </strong>val factory = NoteDetailViewModelFactory(dataSource, requireContext(), noteId)<br>            val noteDetailViewModel =<br>                ViewModelProvider(this, factory).get(NoteDetailViewModel::class.<em>java</em>)<br>            binding.<em>noteViewModel </em>= noteDetailViewModel<br><br>        <strong>}<br>        </strong>binding.<em>lifecycleOwner </em>= this<br><br>        return binding.<em>root<br>    </em>}<br>}</pre><pre>class NoteDetailViewModel(<br>    private val dataSource: NoteDao,<br>    private val context: Context,<br>    private val noteId: Long<br>) :<br>    ViewModel() {<br><br>    private val viewModelJob = <em>Job</em>()<br>    private val uiScope = <em>CoroutineScope</em>(Dispatchers.Main + viewModelJob)<br><br>    private val dao = dataSource<br>    private var _note: LiveData&lt;NoteItem&gt;<br><br>    fun getNote() = _note<br><br>    private var _isBackToHome = MutableLiveData&lt;Boolean&gt;()<br>    val isBackToHome: LiveData&lt;Boolean&gt;<br>        get() = _isBackToHome<br><br>    private var _isNavigateToEdit = MutableLiveData&lt;Boolean?&gt;()<br><br>    val isNavigateToEditNote: LiveData&lt;Boolean?&gt;<br>        get() = _isNavigateToEdit<br><br>    init {<br>        _note = dao.getNoteById(noteId)<br>    }<br><br>    fun getNoteTitle(): String {<br>        val title = context.getString(R.string.<em>title</em>)<br>        return String.<em>format</em>(&quot;%s: %s&quot;, title, _note.<em>value</em>?.title)<br>    }<br><br>    fun onDeleteNote() {<br>        uiScope.<em>launch </em><strong>{<br>            </strong>deleteNoteById(noteId)<br>        <strong>}<br>        </strong>backToHome()<br>    }   <br><br>    private suspend fun deleteNoteById(id: Long) {<br>        withContext(Dispatchers.IO) <strong>{<br>            </strong>dataSource.deleteNoteById(id)<br>        <strong>}<br>        </strong>Toast.makeText(context, &quot;Delete Complete&quot;, Toast.<em>LENGTH_SHORT</em>).show()<br>    }<br><br><br>    fun gotoEditNote() {<br>        _isNavigateToEdit.postValue(true)<br>    }<br><br>    fun doneNavigateToEditNote() {<br>        _isNavigateToEdit.<em>value </em>= null<br>    }<br><br>    private fun backToHome() {<br>        _isBackToHome.postValue(true)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*uE77r9f-3R-q9wxE0orGOQ.png" /></figure><p>เริ่มจาก UI ด้านบนจะเห็นว่าในส่วนของ title จะเป็นการต่อ string ถ้าเกิดจะต้องต่อ string จาก string resource กับ data จาก view model ละจะต้องทำยังงัย ถ้าทำแบบสร้าง getNoteTitle() ที่ NoteDetailViewModel แล้วเรียกใช้ที่ tv_title ที่ใช้แสดง title</p><pre>fun getNoteTitle(): String {<br>    val title = context.getString(R.string.<em>title</em>)<br>    return String.<em>format</em>(&quot;%s: %s&quot;, title, _note.<em>value</em>?.title)<br>}</pre><p>detail_fragment.xml</p><pre>&lt;TextView<br>    android:id=&quot;@+id/tv_title&quot;   <br> ...<br>    android:text=&quot;@{noteViewModel.noteTitle}&quot;   <br> ...<br>     /&gt;</pre><p>ลอง build app ทดสอบดูพบว่า ค่าของ title เป็น null</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*m5j4t0jjLutjjb_VxBVzTQ.png" /></figure><p>สาเหตุที่ค่าของ title มีค่าเป็น null ถ้าดูจาก getNoteTitle()</p><pre>fun getNoteTitle(): String {<br>    val title = context.getString(R.string.<em>title</em>)<br>    return String.<em>format</em>(&quot;%s: %s&quot;, title, _note.<em>value</em>?.title)<br>}</pre><p>จะเห็นว่าค่าของ title ที่เป็น null ถูก set ค่าด้วย _note.<em>value</em>?.title ซึ่งตัวแปร _note มี type เป็น live data ซึ่งจะต้องอัพเดททุกครั้งที่ข้อมูลมีการเปลี่ยนแปลง แต่แล้วทำไมเมื่อ load ได้ข้อมูลมาแล้วยังมีค่าเป็น null ต้องไปดูสาเหตุจริงๆ ที่ NoteItem class</p><pre>@Entity(tableName = &quot;note_table&quot;)<br>data class NoteItem(<br><br>    @PrimaryKey(autoGenerate = true)<br>    val id: Long = 0L,<br><br>    @ColumnInfo(name = &quot;note&quot;)<br>    var note: String,<br><br>    @ColumnInfo(name = &quot;title&quot;)<br>    var title: String<br>)</pre><p>เป็นเพราะว่าค่าของ title ไม่ได้มี type เป็น LiveData&lt;String&gt; เมื่อตัวแปร _note get ค่า room database เสร็จแล้วจึงทำให้ค่าของตัว title ไม่ถูกอัพเดทไปแสดงผลใน text view</p><p>แล้วเราจะแก้ปัญหานี้ได้อย่างไร?</p><p>ถ้าแก้ type ของ title เป็น LiveData&lt;String&gt; ละ มันก็ไม่ใช่วิธีที่ควรทำอยู่ดีเพราะว่าสมมติเราจะ set ค่าแบบเดียวกับ title ในเคสนี้เยอะละเราก็ต้องไป get ค่าตัวแปร value เยอะเหมือนกันมันจะทำให้เราต้องเหนื่อยเปล่าๆ</p><p>สิ่งที่จะมาช่วยให้เรา set ค่า title ง่ายๆ โดยไม่ต้องไปตามเปลี่ยน type ก็คือ</p><p>data binding adapter ซึ่งเป็น annotation สำหรับทำ extension ที่ใช้ set เป็น attribute ใน xml layout ได้เลย ซึ่งสามารถรับค่าเป็น parameter จากแท็ค data ได้เลย</p><p><strong>วิธีทำ data binding adapter</strong></p><p>สามารถทำง่ายๆ เลย โดยการสร้าง data binding adapter class เพื่อเก็บ function ต่างๆ แยกออกตามหน้านั้นๆ</p><p>เริ่มจากใส่ annotation @BindingAdapter(value = [“attribute name”]) ให้ ที่ข้างบน function นั้นเลย โดยจำนวน attribute name ต้องใส่ตามจำนวน parameter ของ function นั้นโดยจะไม่นับ parameter ตัวแรก เพราะ parameter ตัวแรกจะรับเฉพาะ parameter ที่เป็น view เท่านั้น</p><p>ในกรณีนี้เราต้องการ set ค่า title แบบต่อ string ให้ text view ก็จะได้</p><pre>@BindingAdapter(value = [&quot;app:setNoteTitle&quot;])<br>fun setNoteTitle(textView: TextView, note:LiveData&lt;NoteItem&gt;) {<br>    val title = textView.<em>context</em>.getString(R.string.<em>title</em>)<br>    textView.<em>text </em>= String.<em>format</em>(&quot;%s: %s&quot;, title, note.<em>value</em>?.title)<br>}</pre><p>เราสามารถ set ค่าที่ text view ได้เลยผ่าน attribute app:setNoteTitle</p><pre>&lt;TextView<br>    android:id=&quot;@+id/tv_title&quot;<br>   ...<br>    app:setNoteTitle=&quot;@{noteViewModel.note}&quot; /&gt;</pre><p>เมื่อทำ data binding adapter สำหรับ set ค่า แสดงผลเสร็จแล้ว ทดสอบ run ดูผลลัพธ์ก็จะได้ดังนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*kR2pVOBM99K1wH-jTdGGIw.png" /></figure><p>เพิ่ม action ให้กับปุ่ม Delete</p><pre>&lt;Button<br>    android:id=&quot;@+id/btn_delete&quot;<br>    ...<br>    android:onClick=&quot;@{()-&gt; noteViewModel.onDeleteNote()}&quot;  <br>    /&gt;</pre><p>ใน onDeleteNote function ที่ NoteDetailViewModel เมื่อทำการลบข้อมูลเสร็จแล้วก็จะ post value ให้กับ _isBackToHome เพื่อค่าให้ subscriber ทำ action เพื่อกลับไปหน้า home fragment</p><pre>noteDetailViewModel.isBackToHome.observe(<em>viewLifecycleOwner</em>, <em>Observer </em><strong>{ </strong>isBack <strong>-&gt;<br>    </strong>if (isBack) {<br>        requireActivity().onBackPressed()<br>    }<br><strong>}</strong>)</pre><p>ลอง build app ทดสอบ เมื่อกดปุ่มลบข้อมูลโน็ตเมื่อลบเสร็จจะแสดงข้อความ Delete Complete แล้วกลับไปหน้า home fragment ข้อมูลที่ถูกลบจะไม่แสดง</p><p>และส่วนสุดท้ายปุ่มแก้ไขข้อมูลโน็ต เมื่อกดปุ่ม edit ก็จะส่งทำการ post value ให้กับ _isNavigateToEdit เพื่อเป็น trigger ให้ NoteDetailFragment เปิดไปหน้า AddNoteFragment พร้อมทั้งส่ง noteId ไปด้วย</p><pre>noteDetailViewModel.isNavigateToEditNote.observe(<br>    <em>viewLifecycleOwner</em>,<br>    <em>Observer </em><strong>{ </strong>isEdit <strong>-&gt;<br>        </strong>isEdit?.<em>let </em><strong>{<br>            </strong>val id = <em>bundleOf</em>(&quot;noteId&quot; <em>to </em>noteId)<br>            this.<em>findNavController</em>()<br>                .navigate(R.id.<em>action_detailFragment_to_addFragment</em>, id)<br>            noteDetailViewModel.doneNavigateToEditNote()<br>        <strong>}<br>    }</strong>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*08YJIPYNkes1efJHicPtLg.png" /></figure><p>ไปที่หน้า AddFragment ทำการเพิ่ม parameter noteId ที่ AddNoteFactory classและ AddNoteViewModel class สำหรับดึงค่า note จาก id ที่ส่งมาจากหน้า detail</p><pre>class AddNoteFragment : Fragment() {<br><br>    override fun onCreateView(...){</pre><pre>    //case edit note<br>    val noteId = <em>arguments</em>?.getLong(&quot;noteId&quot;)<br>    val factory =<br>    AddNoteFactory(dataSource = dataSource, context = requireContext(), noteId = noteId)</pre><p>เพิ่มตัวแปร _note ที่ AddNoteFactory class สำหรับเก็บค่า note ข้อมูลโน็ตจาก noteId และตัวแปร note สำหรับให้ class อื่น get ค่า</p><pre>class AddNoteViewModel(..){<br>...</pre><pre>     private val _note = dataSource.getNoteById(noteId)</pre><pre>     val note: LiveData&lt;NoteItem&gt;<br>         get() = _note</pre><p>เพิ่มการ subscribe ตัวแปร note ที่หน้า HomeFragment เพื่อกำหนดค่า title และ noteDetail ให้แสดงผลในค่าของข้อมูลโน็ตที่จะแก้ไข</p><pre>addNoteViewModel.note.observe(<em>viewLifecycleOwner</em>, <em>Observer </em><strong>{<br>    it</strong>?.<em>let </em><strong>{<br>        </strong>addNoteViewModel.title.postValue(<strong>it</strong>.title)<br>        addNoteViewModel.noteDetail.postValue(<strong>it</strong>.note)<br>    <strong>}<br>}</strong>)</pre><p>เพิ่มตัวแปร isEditNote type เป็น boolean เพื่อ check edit mode และเพิ่ม fun อัพเดทข้อมูลที่ AddNoteViewModel class และกำหนดค่าเป็น edit mode เมื่อ noteId มีค่าไม่เป็น null</p><pre>class AddNoteViewModel(...){</pre><pre>private val _note = dataSource.getNoteById(noteId)</pre><pre>var isEditNote = false</pre><pre>init {<br>    noteId?.<em>let </em><strong>{<br>        </strong>isEditNote = true<br>    <strong>}<br></strong>}</pre><pre>private suspend fun updateData() {<br>    val detail = this.noteDetail.<em>value </em>?: &quot;&quot;<br>    val title = this.title.<em>value </em>?: &quot;&quot;<br><br>    val isValidateNote = detail.<em>isNotEmpty</em>() &amp;&amp; title.<em>isNotEmpty</em>()<br><br>    if (isValidateNote) {<br>        withContext(Dispatchers.IO) <strong>{<br>            </strong>_note.<em>value</em>?.title = title<br>            _note.<em>value</em>?.note = detail<br>            dataSource.updateNote(noteItem = _note.<em>value</em>)<br>        <strong>}<br>        </strong>_isSaveNote.postValue(true)<br>        Toast.makeText(context, &quot;Edit is complete&quot;, Toast.<em>LENGTH_SHORT</em>).show()<br>    } else {<br>        showInvalidData()<br>    }<br>}</pre><p>แก้ไข onSaveFunction ให้ check เพื่อเช็ค edit mode ตอนกดปุ่ม save</p><pre>fun onSave() {<br>    uiScope.<em>launch </em><strong>{<br>        </strong>if (isEditNote) {<br>            updateData()<br>        } else {<br>            insertData()<br>        }<br>    <strong>}<br></strong>}</pre><p>build app ทดสอบการแก้ไขดู เมื่อแก้ไขข้อมูลโน็ตแล้วกลับมาหน้า home และเปิดดูหน้ารายละเอียดโน็ต ข้อมูลจะต้องแสดงตามที่ถูกแก้ไข</p><p>หากมีข้อสงสัยหรือมีจุดไหนผิดพลาดสามารถคอมเม้นได้นะครับ</p><p><a href="https://github.com/jojoekung/DataBidingWithViewModel.git">source code เพิ่มเติม click</a></p><p>จบแล้วววครับ…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e986f9f15f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Binding with view model Part 3]]></title>
            <link>https://medium.com/@jojoekung/data-binding-with-view-model-part-3-80ea2ae672f3?source=rss-c64ceb16508e------2</link>
            <guid isPermaLink="false">https://medium.com/p/80ea2ae672f3</guid>
            <category><![CDATA[data-binding]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Suriya Wongkasum]]></dc:creator>
            <pubDate>Tue, 11 Aug 2020 03:41:36 GMT</pubDate>
            <atom:updated>2020-08-13T08:02:03.676Z</atom:updated>
            <content:encoded><![CDATA[<p>หลังจากตอนที่แล้วได้ทำ data binding หน้า add note สำหรับเพิ่มข้อมูลโน็ตไป เพื่อให้แน่ใจว่าข้อมูลที่เราบันทึกลง room database ถูกบันทึกจริงหรือไม่ ต่อมาเราจะต้องเพิ่มการแสดงผลข้อมูลโน็ตของเราที่หน้า home fragment โดยใช้ RecyclerView ที่ทำ data binding ที่ ListAdapter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ciYwMNBpmurWqA8tRkm0Mw.png" /></figure><p>เริ่มจากการสร้าง note_item_layout.xml สำหรับแสดง item view และทำ data binding โดยการใส่ data class เข้าไปดังนี้</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;<br><br>    &lt;data&gt;<br><br>        &lt;variable<br>            name=&quot;note&quot;<br>            type=&quot;my.learing.com.recyclerviewbinding.database.NoteItem&quot; /&gt;<br>      <br>    &lt;/data&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        &gt;<br><br>        &lt;TextView<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_margin=&quot;8dp&quot;<br>            android:ellipsize=&quot;end&quot;<br>            android:maxLines=&quot;1&quot;<br>            android:text=&quot;@{note.title}&quot;<br>            android:textSize=&quot;18sp&quot;<br>            android:textStyle=&quot;bold&quot;<br>            tools:text=&quot;title&quot; /&gt;<br>    &lt;/LinearLayout&gt;<br>&lt;/layout&gt;</pre><p>การแสดงผลข้อมูลใน RecyclerView ปกติ adapter class เดิมปกติเรามักจะ RecyclerView.Adapter กัน ที่ต้องจัดการ data ที่ใช้แสดงผลเอง ไม่ว่าจะเป็น item size หรือมีข้อมูลเปลี่ยนแปลงเราต้องมาเราต้องมา manage เอง ถ้าเกิดมีการเปลี่ยนข้อมูลเยอะๆ แน่นอนว่าต้องเกิดอาการหน่วงๆ หรือว่าแอพค้างไป ทาง google เองจึงได้สร้าง adapter แบบใหม่ที่จะมาช่วยแก้ปัญหาเหล่านี้ ชึ่งก็คือ..ListAdapter</p><p>โดยโครงสร้างก็จะคล้ายๆ กันกับ adapter ของ RecyclerView.Adapter เลยคือประกอบด้วย ViewHolder class และมี DiffUtil class เพิ่มเข้ามา มีข้อดีกว่า RecyclerView.Adapter ก็คือเราไม่ต้องไป manage data เอง ทุกครั้งที่มีการเปลี่ยนแปลงข้อมูล adapter จัดจะการ data ให้หมด โดยใน data class เราจะต้องมี unique id ไว้ระบุความแตกต่างของข้อมูล ให้ DiffUtil class เป็นตัวจัดการเอง เราแค่โยนข้อมูลเข้าไป submitList ก็จบ</p><p>เรามาสร้าง NoteAdapter class กันเลยครับ</p><pre>class NoteAdapter : ListAdapter&lt;NoteItem, NoteAdapters.NoteHolder&gt;(NoteDiffCallback()) {<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteHolder {<br>       val inflater = LayoutInflater.from(parent.<em>context</em>)<br>       val binding = NoteItemLayoutBinding.inflate(inflater, parent, false)<br>return NoteHolder(binding)         <br>    }<br><br>    override fun onBindViewHolder(holder: NoteHolder, position: Int) {<br>       val item = getItem(position)<br>       holder.bind(item)<br>    }<br><br>    class NoteHolder private constructor(binding: NoteItemLayoutBinding) :<br>        RecyclerView.ViewHolder(binding.<em>root</em>) {<br><br>    }<br><br>    class NoteDiffCallback: DiffUtil.ItemCallback&lt;NoteItem&gt;() {<br>        override fun areItemsTheSame(oldItem: NoteItem, newItem: NoteItem): Boolean {<br>            return oldItem.id == newItem.id<br>        }<br><br>        override fun areContentsTheSame(oldItem: NoteItem, newItem: NoteItem): Boolean {<br>            return oldItem == newItem<br>        }<br>    }<br>}</pre><p>ไปที่ NoteHolder class ในส่วนของ constructor เดิม holder class เรา type จะเป็น view แล้วเจ้า NoteItemLayoutBinding มาจากไหนกัน?</p><p>NoteItemLayoutBinding มาการ generate ให้อัตโนมัติหลังจากที่เรา convert data binding layout หรือ เพิ่มแท็ก layout ครอบ layout เดิม เพื่ออ้างอิงไป layout ที่จะทำ data binding โดยเมื่อเราคลิกที่ NoteItemLayoutBinding จะเห็นว่ามันจะเปิดไฟล์ note_item_layout.xml ทันที</p><p>เพิ่ม function bind ที่รับค่า parameter type เป็น NoteItem ใน class NoteHolder() เพื่อทำการผูก data เข้ากับ UI โดยไม่ต้อง set view ที่ adapter</p><pre>fun bind(item: NoteItem) {<br>    noteItemLayoutBinding.<em>note </em>= item   <br>    noteItemLayoutBinding.executePendingBindings()<br>}</pre><p>ถ้าอยากทำ action เมื่อกดปุ่มละ ต้องใช้ setOnClickListener มั้ย? คำตอบคือไม่ เราสามารถใส่ action เมื่อคลิก view ของ recycler view ได้ท่าเดิมคือเพิ่ม OnClickItemListener class สำหรับดักการคลิก โดยรับ parameter ด้วย ramda</p><pre>class OnClickItemListener(val onClickListener: (noteId: Long) -&gt; Unit) {<br>    fun onClick(noteItem: NoteItem) = onClickListener(noteItem.id)<br>}</pre><p>เราสามารถนำคลาส OnClickItemListener ไปใช้ได้โดยการเพิ่ม แท็ค variable ที่ แท็ค data ใน note_item_layout.xml</p><pre>&lt;variable<br>    name=&quot;listener&quot;<br>    type=&quot;my.learing.com.recyclerviewbinding.home.OnClickItemListener&quot; /&gt;</pre><p>แล้วเรียกใช้ function onClick ที่รับ parameter เป็น NoteItem ที่ layout หลักใน note_item_layout.xml</p><pre>&lt;LinearLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:onClick=&quot;@{()-&gt; listener.onClick(note)}&quot;&gt;<br><br>   ....<br>&lt;/LinearLayout&gt;</pre><p>และส่วนสุดท้ายคือเพิ่ม OnClickItemListener ใน parameter และ function ที่เกี่ยวข้อง</p><pre>class NoteAdapter(private val onClickItemListener: OnClickItemListener): ...<br>    override fun onBindViewHolder...<br>            ...<br>            holder.bind(item, onClickItemListener = onClickItemListener)<br>    }<br><br>    class NoteHolder  ...{<br><br>        fun bind(item: NoteItem, onClickItemListener: OnClickItemListener) {<br>           ..<br>            noteItemLayoutBinding.<em>listener </em>= onClickItemListener<br>           ..<br>        }<br>    }<br>  ..<br>}</pre><p>เพื่อไม่ให้งงเมื่อเสร็จแล้ว NoteAdapter class ก็จะหน้าตาประมาณนี้</p><pre>class NoteAdapter(private val onClickItemListener: OnClickItemListener) :<br>    ListAdapter&lt;NoteItem, NoteAdapter.NoteHolder&gt;(NoteCallBack()) {<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteHolder {<br>        val inflater = LayoutInflater.from(parent.<em>context</em>)<br>        val binding = NoteItemLayoutBinding.inflate(inflater, parent, false)<br>        return NoteHolder(binding)<br>    }<br><br>    override fun onBindViewHolder(holder: NoteHolder, position: Int) {<br>            val item = getItem(position)<br>            holder.bind(item, onClickItemListener = onClickItemListener)<br>    }<br><br>    class NoteHolder(private val noteItemLayoutBinding: NoteItemLayoutBinding) :<br>        RecyclerView.ViewHolder(noteItemLayoutBinding.<em>root</em>) {<br><br>        fun bind(item: NoteItem, onClickItemListener: OnClickItemListener) {<br>            noteItemLayoutBinding.<em>note </em>= item<br>            noteItemLayoutBinding.<em>listener </em>= onClickItemListener<br>            noteItemLayoutBinding.executePendingBindings()<br>        }<br>    }<br><br>    class NoteCallBack : DiffUtil.ItemCallback&lt;NoteItem&gt;() {<br>        override fun areItemsTheSame(oldItem: NoteItem, newItem: NoteItem): Boolean {<br>            return oldItem.id == newItem.id<br>        }<br><br>        override fun areContentsTheSame(oldItem: NoteItem, newItem: NoteItem): Boolean {<br>            return oldItem == newItem<br>        }<br>    }<br>}<br><br>class OnClickItemListener(val onClickListener: (noteId: Long) -&gt; Unit) {<br>    fun onClick(noteItem: NoteItem) = onClickListener(noteItem.id)<br>}</pre><p>ส่วนสุดท้ายที่ขาดไปไม่ได้คือการใส่ adaper สำหรับแสดงข้อมูล note ให้กับ recycler view ที่ HomeFragment และใส่ action เมื่อคลิกที่ item view ให้ส่ง noteId ไปที่หน้า noteDetailFragment</p><pre>override fun onCreateView(...){<br>...<br>val adapter = NoteAdapter(OnClickItemListener <strong>{<br>    </strong>val bundle = <em>bundleOf</em>(&quot;noteId&quot; <em>to </em><strong>it</strong>)<br>    this.<em>findNavController</em>()<br>        .navigate(R.id.<em>action_homeFragment_to_detailFragment</em>, bundle)<br><strong>}</strong>)</pre><pre>binding.rcvNote.<em>layoutManager </em>=<br>    LinearLayoutManager(requireContext(), RecyclerView.<em>VERTICAL</em>, false)</pre><pre>binding.rcvNote.<em>adapter </em>= adapter</pre><pre>...</pre><p>เมื่อเราสร้าง adapter list view และกำหนดค่าต่างๆ ที่ผูกให้เป็น data binding เรียบร้อยแล้ว สิ่งยังขาดก็คือข้อมูล note ที่อยู่ใน room database ที่จะเอามาใส่ใน adapter ยังง้ย</p><p>กลับไปที่ HomeViewModel จะมีตัวแปร _note ที่ดึงข้อมูลโน็ตทั้งหมดจาก room database เราสามารถดึงค่า _note ซึ่งเป็น private ได้ผ่านตัว mNote โดยทำการ subscribe mNote ที่ function onCreateView ของ HomeFragment แล้วเพิ่มข้อมูลโน็ตเข้าไปที่ adapter ผ่าน submitList()</p><pre>override fun onCreateView(...){<br>...<br>homeViewModel.mNote.observe(<em>viewLifecycleOwner</em>, <em>Observer </em><strong>{ </strong>note <strong>-&gt;<br>    </strong>note?.<em>let </em><strong>{<br>        </strong>adapter.submitList(<strong>it</strong>)<br>    <strong>}<br>}</strong>)</pre><p>รันทดสอบดูก็จะสามารถแสดงผลข้อมูลโน็ตที่เราเพิ่มไว้ได้ดังรูป</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*xSaFx4q_9JutmhorcCCvMQ.png" /></figure><p>ตอนนี้ขอจบแค่นี้ก่อนนะครับ โปรดติดตามรับชมได้ในตอนต่อไป <a href="https://medium.com/@jojoekung/data-binding-with-view-model-part-4-7e986f9f15f3">part 4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80ea2ae672f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Binding with view model Part 1]]></title>
            <link>https://medium.com/@jojoekung/data-binding-with-view-model-part-1-4af9443aea15?source=rss-c64ceb16508e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4af9443aea15</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[data-binding]]></category>
            <dc:creator><![CDATA[Suriya Wongkasum]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 04:25:54 GMT</pubDate>
            <atom:updated>2020-08-13T09:35:05.543Z</atom:updated>
            <content:encoded><![CDATA[<p>หลังจากผมว่างเว้นโปรเจคภายในบริษัทเลยอยากลองลองทำการเขียนโปรแกรม pattern แบบใหม่ๆ หล่อๆ บ้าง หลังจากทำความเข้าใจมาประมาณหนึ่งเลยอยากจะลองสรุปสิ่งที่ตัวเองเข้าใจไว้กันลืม หากจุดไหนมีข้อผิดพลาดหรือสิ่งที่ผมเขียนบางจุดเข้าใจไม่ถูกต้อง รบกวนเพื่อนๆ ที่หลงเข้ามาอ่านช่วยชี้แนะด้วยนะครับ</p><p>work shop ที่ผมจะทำในวันนี้เป็นแอพชื่อ My memmo เป็นแอพโน็ตง่ายๆ เน้นแสดงผลโน็ต ดูรายละเอียดโน็ตที่บันทึกไว้ และเพิ่มแก้ไขโน็ต มี UI ดังนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*H1JAD1UVQRD3cJ71HJlNHA.png" /></figure><p><strong>โครงสร้างแอพ</strong></p><p>ในที่นี้เราจะใช้ Data Binding ในการอัพเดทการแสดงผลในฝั่ง UI โดยใช้ view model เป็นตัวติดต่อระหว่าง data กับ UI และเก็บข้อมูลโน้ตของเราไว้ใน room database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*Sdw3Fks21klm_V8_zvQ1YQ.png" /></figure><p>มาเริ่มเขียนกันเลยครับ</p><p>เพิ่ม lib ที่จำเป็นต้องใช้ที่ Gradle app</p><pre>//coroutines<br>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7&quot;<br>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7&quot;<br><br>//room db<br>implementation &quot;androidx.room:room-runtime:2.2.5&quot;<br>kapt &quot;androidx.room:room-compiler:2.2.5&quot;<br><br>//view model<br>implementation &quot;androidx.lifecycle:lifecycle-extensions:2.2.0&quot;<br><br>//navigation controller<br>implementation &quot;android.arch.navigation:navigation-fragment-ktx:1.0.0&quot;<br>implementation &quot;android.arch.navigation:navigation-ui-ktx:1.0.0&quot;</pre><p>เพิ่ม apply plugin ที่ Gradle app ใน scope นอกสุด</p><pre>apply plugin: &#39;com.android.application&#39;<br>apply plugin: &#39;kotlin-android&#39;<br>apply plugin: &#39;kotlin-android-extensions&#39;<br>apply plugin: &#39;kotlin-kapt&#39;</pre><h3>Database</h3><p>สร้าง class NoteItem สำหรับเป็น table ในการเก็บข้อมูล note</p><pre>@Entity(tableName = &quot;note_table&quot;)<br>data class NoteItem(<br><br>    @PrimaryKey(autoGenerate = true)<br>    val id: Long = 0L,<br><br>    @ColumnInfo(name = &quot;note&quot;)<br>    val note: String,<br><br>    @ColumnInfo(name = &quot;title&quot;)<br>    val title: String<br>)</pre><p>สร้าง Dao interface สำหรับ query ข้อมูล</p><pre>@Dao<br>interface NoteDao {<br><br>    @Insert<br>    fun insertNote(noteItem: NoteItem)<br><br>    @Update<br>    fun updateNote(noteItem: NoteItem?)<br><br>    @Query(&quot;SELECT * FROM note_table ORDER BY  id DESC&quot;)<br>    fun getAllNote(): LiveData&lt;List&lt;NoteItem&gt;&gt;<br><br>    @Query(&quot;SELECT * FROM note_table WHERE id = :id&quot;)<br>    fun getNoteById(id: Long?): LiveData&lt;NoteItem&gt;<br><br>    @Query(&quot;DELETE FROM note_table WHERE id = :id&quot;)<br>    fun deleteNoteById(id: Long)<br>}</pre><p>สร้าง class NoteDatabase สำหรับเก็บค่า instance ไว้เรียกใช้งาน Dao interface ในการ query ข้อมูลจากฐานข้อมูล</p><pre>package my.learing.com.recyclerviewbinding.database<br><br>import android.content.Context<br>import androidx.room.Database<br>import androidx.room.Room<br>import androidx.room.RoomDatabase<br><br>@Database(entities = [NoteItem::class], version = 1, exportSchema = false)<br>abstract class NoteDatabase : RoomDatabase() {<br><br>    abstract val noteDao: NoteDao<br><br>    companion object {<br><br>        @Volatile<br>        private var INSTANCE: NoteDatabase? = null<br><br>        fun getInstance(context: Context): NoteDatabase {<br>            <em>synchronized</em>(this) <strong>{<br><br>                </strong>var instance = INSTANCE<br><br>                if (instance == null) {<br>                    instance = Room.databaseBuilder(<br>                        context.<em>applicationContext</em>,<br>                        NoteDatabase::class.<em>java</em>,<br>                        &quot;note_database&quot;<br>                    )<br>                        .fallbackToDestructiveMigration()<br>                        .build()<br>                    INSTANCE = instance<br>                }<br>                return instance<br>            <strong>}<br>        </strong>}<br>    }<br>}</pre><p>View model</p><p>สร้าง HomeViewModel class ใน package ของหน้า Home สำหรับเป็นตัวติดต่อระหว่าง UI กับ data จากฐานข้อมูล และ business logic ทั้งหมด</p><pre>class HomeViewModel(<br>    dataSource: NoteDao<br>) : ViewModel() {<br><br>    private val database = dataSource<br><br>    private var _note = database.getAllNote()<br><br>    val mNote: LiveData&lt;List&lt;NoteItem&gt;&gt;<br>        get() = _note<br><br>    private var _isNavigateToAddNote = MutableLiveData&lt;Boolean?&gt;()<br><br>    val isNavigateToAddNote: LiveData&lt;Boolean?&gt;<br>        get() = _isNavigateToAddNote<br><br>    private var _navigateToNoteDetail = MutableLiveData&lt;Boolean?&gt;()<br><br>    val isNavigateToNoteDetail: LiveData&lt;Boolean?&gt;<br>        get() = _isNavigateToNoteDetail<br><br>    //reset _navigateToNoteDetail value<br>    fun doneNavigateToDetail() {<br>        _navigateToNoteDetail.<em>value </em>= null<br>    }<br><br>    fun gotoNoteDetail() {<br>        _navigateToNoteDetail.<em>value </em>= true<br>    }<br><br>    //reset _navigateToAddNote value<br>    fun doneNavigateToAddNote() {<br>        _navigateToAddNote.<em>value </em>= null<br>    }<br>    <br>    fun gotoAddNote() {<br>        _navigateToAddNote.<em>value </em>= true<br>    }<br>}</pre><p>ในกรณีนี้ view model class ที่เราสร้างขึ้นมี constructor ซึ่ง view model จะไม่ instance ค่าแบบ new object เหมือน class ทั่วไป เลยจำเป็นสร้าง HomeViewModelFactory class ที่ imprement ViewModelProvider.Factory สำหรับใช้ในการ instance ให้กับ HomeViewModel ส่วนในกรณีที่ view model ไม่มี constructor ก็ไม่จำเป็นต้องสร้าง HomeViewModelFactory class</p><pre>class HomeViewModelFactory(private val dataSource: NoteDao) :<br>    ViewModelProvider.Factory {<br>    override fun &lt;T : ViewModel?&gt; create(modelClass: Class&lt;T&gt;): T {<br>        if (modelClass.isAssignableFrom(HomeViewModel::class.<em>java</em>)) {<br>            return HomeViewModel(dataSource = dataSource, application = application) as T<br>        }<br>        throw IllegalAccessException(&quot;Unknown view model class&quot;)<br>    }<br>}</pre><p>เมื่อเตรียม view model class เสร็จแล้วก็ทำการเพิ่ม view model ของ HomeFragment ที่ fun onCreateView</p><pre>override fun onCreateView(...){<br>...<br>val dataSource = NoteDatabase.getInstance(requireContext()).noteDao<br><br>val viewModelFactory =<br>    HomeViewModelFactory(dataSource = dataSource)<br>val homeViewModel =<br>    ViewModelProvider(this, viewModelFactory).get(HomeViewModel::class.<em>java</em>)</pre><p><strong>Navigation component</strong></p><p>ในแอพนี้จะใช้ navigation component แทนการใช้คำสั่ง starIntent ในการการเปิดหน้าต่างๆ ส่วนเพื่อนที่หลงเข้ามาอ่านจะใช้ startActivity แบบเดิมก็ได้นะครับ หรือว่าใครยังไม่เคยใช้สามารถเข้าไปศึกษาวิธีการใช้งานได้ตามลิ้งด้านล่างได้นะครับ</p><p>Link: <a href="https://blog.nextzy.me/get-started-android-navigation-component-part-1-43219d0a2df9">วิธีการใช้งาน navigation component</a></p><p><strong>Data Binding</strong></p><p>มาถึงพระเอกของงานนี้คือ… ฺbinding data ซึ่งเป็น lib ของ google เองที่จะช่วยปัญหาต่างๆ เกี่ยวกับ configuration change ที่เกี่ยวกับ view หมดไปหลักการทำงานคร่าวๆ จะเป็นการผูก data เข้ากับ UI โดยอาศัยการทำงานของ LiveData เข้ามาช่วนในติดต่อระหว่าง data และ UI</p><p>เริ่ม set Gradle App ที่ android scope</p><pre>buildFeatures <strong>{<br>    </strong>dataBinding true<br><strong>}</strong></pre><p>เปิด layout home_fragment คลิกเลือกที่ layout หลัก แล้วกด alt + enter แล้วเลือก convert to data binding layout เพื่อแปลง layout เป็น data binding หรือเพิ่ม แท็ก layout ครอบที่ layout หลัก</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;<br><br>    &lt;data&gt;<br><br>    &lt;/data&gt;<br><br>    &lt;androidx.constraintlayout.widget.ConstraintLayout<br>        android:id=&quot;@+id/frameLayout&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        tools:context=&quot;.home.HomeFragment&quot;&gt;<br><br><br>        &lt;androidx.recyclerview.widget.RecyclerView<br>            android:id=&quot;@+id/recyclerView&quot;<br>            android:layout_width=&quot;0dp&quot;<br>            android:layout_height=&quot;0dp&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>            app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>            app:layout_constraintTop_toBottomOf=&quot;@+id/toolbar&quot; /&gt;<br><br>        &lt;androidx.appcompat.widget.Toolbar<br>            android:id=&quot;@+id/toolbar&quot;<br>            android:layout_width=&quot;0dp&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:background=&quot;?attr/colorPrimary&quot;<br>            android:minHeight=&quot;?attr/actionBarSize&quot;<br>            android:theme=&quot;?attr/actionBarTheme&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>            app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>            app:title=&quot;@string/app_name&quot;<br>            app:titleTextColor=&quot;@color/white_text_color&quot; /&gt;<br><br>        &lt;com.google.android.material.floatingactionbutton.FloatingActionButton<br>            android:id=&quot;@+id/btn_add_note&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_marginEnd=&quot;16dp&quot;<br>            android:layout_marginBottom=&quot;16dp&quot;<br>            android:clickable=&quot;true&quot;<br>            android:src=&quot;@drawable/ic_baseline_add_24&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>            android:focusable=&quot;true&quot; /&gt;<br>    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;<br>&lt;/layout&gt;</pre><p>เพิ่มตัวแปร เพื่อให้ HomeViewModel ผูกกับ view ของหน้า home_fragment.xml</p><pre>&lt;data&gt;<br>    &lt;variable<br>        name=&quot;home_view_model&quot;<br>        type=&quot;my.learing.com.recyclerviewbinding.home.HomeViewModel&quot; /&gt;<br>&lt;/data&gt;</pre><p>สลับไปที่ HomeFragment ที่ fun onCreateView จากที่เดิมเรา inflate view แบบ</p><pre>override fun onCreateView(....{</pre><pre>    return inflater.inflate(R.layout.<em>home_fragment</em>, container, false)</pre><pre>}</pre><p>ก็เปลี่ยนวิธี inflate view เป็นแบบ data binding ได้ดังนี้</p><pre>override fun onCreateView(....{</pre><pre>val binding: HomeFragmentBinding =<br>    DataBindingUtil.inflate(inflater, R.layout.<em>home_fragment</em>, container, false)<br><br>return binding.<em>root</em></pre><pre>}</pre><p>เมื่อเพื่ม data binding เข้าไปใน HomeFragment เสร็จแล้วทำการเชื่อมต่อ home_view_model ที่เพิ่มไว้ใน home_fragment.xml</p><pre>&lt;data&gt;<br>    &lt;variable<br>        name=&quot;home_view_model&quot;<br>        type=&quot;my.learing.com.recyclerviewbinding.home.HomeViewModel&quot; /&gt;<br>&lt;/data&gt;</pre><p>โดยเพิ่มการเชื่อมต่อข้อมูลเข้ากับ ที่ fun onCreateView</p><pre>fun onCreateView(...</pre><pre>val binding: HomeFragmentBinding =<br>    DataBindingUtil.inflate(inflater, R.layout.<em>home_fragment</em>, container, false)</pre><pre>...</pre><pre><strong>binding.<em>homeViewModel </em>= homeViewModel<br><br>binding.<em>lifecycleOwner </em>= this<br>...</strong></pre><p>เมื่อเราผูก data เข้ากับ view เสร็จแล้วก็จะทำการเพิ่ม action การทำงานให้กับ view หน้า home เริ่มจากปุ่มเพิ่มโน็ต เมื่อกดปุ่มแล้วจะไปหน้าเพิ่มข้อมูลโน็ต โดยเราจะทำการ observe ค่าจากตัวแปร isNavigateToAddNote ที่อยู่ใน HomeViewModel ถ้าค่าที่ส่งมาเป็น true จะเปิดไปหน้าเพิ่มข้อมูลโน็ต</p><pre>class HomeFragment : Fragment() {</pre><pre>...<br>homeViewModel.isNavigateToAddNote.observe(<em>viewLifecycleOwner</em>, <em>Observer </em><strong>{<br>    it</strong>?.<em>let </em><strong>{<br>        </strong>this.<em>findNavController</em>()<br>            .navigate(HomeFragmentDirections.actionHomeFragmentToAddFragment())<br>        homeViewModel.doneNavigateToAddNote() <strong>//reset ค่าเริ่มต้น</strong><br>    <strong>}<br>}</strong>)</pre><p>จากเดิมที่เรามักใช้ setOnClickListener ในการทำ action อะไรบางเมื่อคลิกปุ่มหรือ view ต่างๆ ในเมื่อใช้ data binding ให้หล่อขึ้นแล้วเราจะเชตที่ home_fragment.xml เลยโดยเพิ่ม action ให้ปุ่ม add note เพื่อกำหนดเงื่อนให้ view model ส่งค่า ไปให้ subscriber ที่ observe อยู่ที่ HomeFragment ให้เปิดหน้า AddNoteFragment</p><pre>&lt;com.google.android.material.floatingactionbutton.FloatingActionButton<br>    android:id=&quot;@+id/btn_add_note&quot;<br>    ...<br>    <strong>android:onClick=&quot;@{()-&gt; homeViewModel.gotoAddNote()}&quot;</strong><br>    ...<br>/&gt;</pre><p>เสร็จแล้วลอง build ทดสอบ เมื่อกดปุ่มเพิ่มโน็ตก็จะเปิดไปหน้าเพิ่มโน็ตได้</p><p>รอติดตามต่อไป<a href="https://medium.com/@jojoekung/data-binding-with-view-model-part-2-34e909fdaf52"> part 2</a> นะครับ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4af9443aea15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Binding with view model Part 2]]></title>
            <link>https://medium.com/@jojoekung/data-binding-with-view-model-part-2-34e909fdaf52?source=rss-c64ceb16508e------2</link>
            <guid isPermaLink="false">https://medium.com/p/34e909fdaf52</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[data-binding]]></category>
            <dc:creator><![CDATA[Suriya Wongkasum]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 04:25:20 GMT</pubDate>
            <atom:updated>2020-08-13T07:07:01.548Z</atom:updated>
            <content:encoded><![CDATA[<p>ต่อจากตอนที่แล้วหลังจากเพิ่ม view model เพื่อ subscribe ค่าตัวแปร isNavigateToAddNote แล้วเปิดไปหน้าเพิ่มโน็ต</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*uyesyYjShjUiZOhD1ulCTg.png" /></figure><p>ไปที่หน้า AddNoteFragment ทำการเพิ่ม AddNoteViewModel สำหรับใส่ business logic ที่เกี่ยวกับการเพิ่มข้อมูลโน็ต โดยเมื่อกรอกข้อมูลโน็ตครบทุก field แล้วกดปุ่ม save จะทำการบันทึกข้อมูลลงฐานข้อมูล</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*2TpsFPj5NIE3DAyivLI6hw.png" /></figure><pre>class AddNoteViewModel(<br>    val dataSource: NoteDao,<br>    private val context: Context<br>) : ViewModel() {<br><br>    var title = MutableLiveData&lt;String&gt;(&quot;&quot;)<br>    var noteDetail = MutableLiveData&lt;String&gt;(&quot;&quot;)<br><br>    private var _isSaveNote = MutableLiveData&lt;Boolean&gt;()<br>    val isSaveNote: LiveData&lt;Boolean&gt;<br>        get() = _isSaveNote<br><br>    private val viewModelJob = <em>Job</em>()<br>    private val uiScope = <em>CoroutineScope</em>(Dispatchers.Main + viewModelJob)<br><br>    fun onSave() {<br>        uiScope.<em>launch </em><strong>{<br>            </strong>insertData()<br>        <strong>}<br>    </strong>}<br><br>    private suspend fun insertData() {<br>        val detail = this.noteDetail.<em>value </em>?: &quot;&quot;<br>        val title = this.title.<em>value </em>?: &quot;&quot;<br><br>        val isValidateNote = detail.<em>isNotEmpty</em>() &amp;&amp; title.<em>isNotEmpty</em>()<br><br>        if (isValidateNote) {<br>            withContext(Dispatchers.IO) <strong>{<br>                </strong>val data = NoteItem(note = detail, title = title)<br>                dataSource.insertNote(data)<br>            <strong>}<br>            </strong>_isSaveNote.postValue(true)<br>            Toast.makeText(context, &quot;save complete&quot;, Toast.<em>LENGTH_SHORT</em>).show()<br>        } else {<br>            showInvalidData()<br>        }<br>    }<br><br>    private fun showInvalidData() {<br>        Toast.makeText(context, &quot;Please complete all information.&quot;, Toast.<em>LENGTH_SHORT</em>)<br>            .show()<br>    }<br><br>    override fun onCleared() {<br>        super.onCleared()<br>        viewModelJob.cancel()<br>    }<br>}</pre><p>สำหรับการใช้ room database แล้วมีการ insert หรือ update ข้อมูลต่างๆ จะต้องอยู่ใน IO thread แล้วครอบด้วย main thread เพื่อให้รองรับการเรียกใช้ function insert เมื่อกดปุ่ม save</p><p>ในกรณีนี้ AddNoteViewModel มี constructor อยู่จึงจำเป็นต้องทำ view model factory class เหมือนในหน้า home</p><pre>class AddNoteFactory(<br>    private val dataSource: NoteDao,<br>    private val context: Context<br>) : ViewModelProvider.Factory {<br>    override fun &lt;T : ViewModel?&gt; create(modelClass: Class&lt;T&gt;): T {<br>        if (modelClass.isAssignableFrom(AddNoteViewModel::class.<em>java</em>)) {<br>            return AddNoteViewModel(<br>                dataSource = dataSource,<br>                context = context<br>            ) as T<br>        }<br>        throw IllegalAccessException(&quot;Unknown class&quot;)<br>    }<br>}</pre><p>ไปที่ไฟล์ add_note_fragment.xml ทำการ convert layout ให้เป็น data binding layout แล้วเพิ่ม data เพื่อผูกเข้ากับ layout วิธีเดียวกับตอนที่ทำในหน้า HomeFragment</p><pre>&lt;data&gt;<br>    &lt;variable<br>        name=&quot;addNoteViewModel&quot;          type=&quot;my.learing.com.recyclerviewbinding.add.AddNoteViewModel&quot; /&gt;<br>&lt;/data&gt;</pre><p>data binding</p><p>ปกติการทำ data binding ที่ UI ยกตัวอย่างเช่นการแสดงข้อความอย่างเดียวใน text view จะต้องเช็ตเป็น</p><pre>&lt;TextView<br>   ...<br>    android:text=&quot;@{addNoteViewModel.title}&quot;<br>/&gt;</pre><p>ส่วนในกรณีหน้า addNoteFragment จะเป็นการกรอกข้อมูลซึ่งไม่ได้ใช้แค่แสดงผล อย่างเดียว เมื่อเรากรอกข้อมูลทุกครั้งข้อมูลตัวแปรที่ AddNoteViewModel จะต้องเปลี่ยนแปลงตามค่าที่กรอกเข้าไปด้วย การ set data binding แบบวิธีแรกจึงไม่เหมาะที่จะใช้กับ edit text และเราจะไม่เรียกใช้ addTextChangedListener</p><p>เราจะเช็ตแบบ two way data binding ซึ่งต่างจากวิธีแรกนิดเดียวคือเพื่มเครื่องหมาย = เข้าไป</p><pre>&lt;EditText                                              <br>    android:id=&quot;@+id/edt_title&quot;<br>    ...<br>    android:text=&quot;@={addNoteViewModel.title}&quot;<br>  /&gt;</pre><p>โดยตัวแปรที่ใช้เก็บค่า title จะต้องเป็น MutableLiveData</p><pre>class AddNoteViewModel(...</pre><pre>    var title = MutableLiveData&lt;String&gt;(&quot;&quot;)</pre><p>ทำการเพิ่ม function ตอนคลิกปุ่ม save</p><pre>&lt;com.google.android.material.floatingactionbutton.FloatingActionButton<br>    android:id=&quot;@+id/btn_save&quot;<br>   ...<br>    android:onClick=&quot;@{()-&gt;addNoteViewModel.onSave()}&quot;   <br>/&gt;</pre><p>หลังจากเพิ่ม data binding เข้ากับ view ของหน้าเพิ่มโน็ตครบแล้ว ทำการเปลี่ยนวิธี inflate view และเพิ่ม view model class ที่ AddNoteFragment class</p><pre>override fun onCreateView(...<br>    val binding: AddNoteFragmentBinding =<br>        DataBindingUtil.inflate(inflater, R.layout.<em>add_note_fragment</em>, container, false)<br><br>    val dataSource = NoteDatabase.getInstance(requireContext()).noteDao<br><br>    val factory =<br>        AddNoteFactory(dataSource = dataSource, context = requireContext())<br>    val addNoteViewModel =<br>        ViewModelProvider(this, factory).get(AddNoteViewModel::class.<em>java</em>)<br><br>    binding.<em>addNoteViewModel </em>= addNoteViewModel<br>    binding.<em>lifecycleOwner </em>= this<br><br>    return binding.<em>root<br></em>}</pre><p>ทำการเพิ่มการ subscribe ตัวแปร isSaveNote เพื่อสั่งให้ปิดหน้านี้ไปเมื่อบันทึกข้อมูลเสร็จแล้ว</p><pre>addNoteViewModel.isSaveNote.observe(<em>viewLifecycleOwner</em>, <em>Observer </em><strong>{<br>    it</strong>?.<em>let </em><strong>{<br>        </strong>if (<strong>it</strong>) {<br>            val imm =<br>                requireContext().getSystemService(Context.<em>INPUT_METHOD_SERVICE</em>) as InputMethodManager<br>            imm.hideSoftInputFromWindow(binding.<em>root</em>.<em>windowToken</em>, 0)<br><br>            requireActivity().onBackPressed()<br>        }<br>    <strong>}<br>}</strong>)</pre><p>build ทดสอบการทำงานดู เมื่อกดปุ่ม save แสดงข้อความ save complete แล้วกลับไปหน้า home</p><p>โปรดติดตามรับชมได้ในตอนต่อไป <a href="https://medium.com/@jojoekung/data-binding-with-view-model-part-3-80ea2ae672f3">part 3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34e909fdaf52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ลาก่อนเด้อ findViewById]]></title>
            <link>https://medium.com/@jojoekung/%E0%B8%A5%E0%B8%B2%E0%B8%81%E0%B9%88%E0%B8%AD%E0%B8%99%E0%B9%80%E0%B8%94%E0%B9%89%E0%B8%AD-findviewbyid-f372ae2ecc49?source=rss-c64ceb16508e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f372ae2ecc49</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Suriya Wongkasum]]></dc:creator>
            <pubDate>Sat, 17 Mar 2018 13:23:20 GMT</pubDate>
            <atom:updated>2018-03-17T14:57:28.263Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“ต้นๆ กำลังทำอะไรอ่ะ”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-acwcWTZGB4X5RHfRobKUQ.png" /><figcaption>ภาพจากโฆษณาไดเกียว</figcaption></figure><p>“กำลัง FindViewById ใน java อยู่อ่ะ”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mj9sR0ex9aPFWLKxlKPRjw.png" /><figcaption>ภาพจากโฆษณาไดเกียว</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*NGpbZVD2VTx0CXBLOcEy8Q.png" /></figure><blockquote>“ทำไมไม่เปลี่ยนมาใช้ Kotlin ละ ”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kfh9CK3YYfP1IMfF3xNM9w.png" /><figcaption>ภาพจากโฆษณาไดเกียว</figcaption></figure><p>“เพราะใช้แล้ว เรียกใช้จากชื่อ id ได้โดยตรงเลย”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DckhbsA83WTEbdzAKtRttw.png" /><figcaption>ภาพจากโฆษณาไดเกียว</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*bKHlGIfm0pL9VCKtvQXEiA.png" /></figure><p>แต่อย่าลืมเพิ่ม kotlin extension ใน build.gradle โมดูล app นะ</p><pre>apply plugin: &#39;kotlin-android&#39;<br>apply plugin: &#39;kotlin-android-extensions&#39;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f372ae2ecc49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[เด็กชายในบ้านพักก่อสร้าง]]></title>
            <link>https://medium.com/@jojoekung/%E0%B9%80%E0%B8%94%E0%B9%87%E0%B8%81%E0%B8%8A%E0%B8%B2%E0%B8%A2%E0%B9%83%E0%B8%99%E0%B8%9A%E0%B9%89%E0%B8%B2%E0%B8%99%E0%B8%9E%E0%B8%B1%E0%B8%81%E0%B8%81%E0%B9%88%E0%B8%AD%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87-e899129e17a8?source=rss-c64ceb16508e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e899129e17a8</guid>
            <dc:creator><![CDATA[Suriya Wongkasum]]></dc:creator>
            <pubDate>Sat, 06 Jan 2018 17:37:32 GMT</pubDate>
            <atom:updated>2018-01-06T17:40:59.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*Vol-TqNKWWGec2Yn." /></figure><p>Base on true story by: คนงานก่อสร้าง</p><p>เห็นบ้านพักคนงานก่อสร้าง แล้วคิดถึงตัวเองตอนเด็กๆ ครั้งหนึ่งเราก็เคยใช้ชีวิตอยู่ในนี้เหมือนกัน ภาพเด็กชายตัวเล็กๆผอมๆ วิ่งเล่นชุกชนคนเดียว จำได้ว่าตอนนั้นอายุน่าจะประมาณสัก 4 ขวบ ด้วยผมเกิดมาก็ปากแหว่งเพดานโหว่มาตั้งแต่กำเนิด ครอบครัวก็มีฐานะทางการเงินค่อนข้างที่จน ตั้งแต่ผมเกิดเนื่องจากปากของผมกับจมูกทะลุหากันหมดก็เลยกินนมแม่ไม่ได้ อาหารที่ทำให้ผมโตขึ้นได้มีแค่นมผงอย่างเดียว พ่อต้องดิ้นรณทำงานตั้งแต่ทำงานเหมืองแบกหินเพื่อหาเงินมาซื้อนม</p><p>พอผมโตขึ้นมาสักหน่อยพ่อกับแม่ก็ไปทำงานก่อสร้างเพื่อที่จะหาเงินไปรักษาปากที่ผมเพื่อให้ลูกใช้ชีวิตได้แบบปกติ ภาพที่จำได้ผมคือชีวิตผมโตมาในบ้านพักคนงานก่อสร้าง แถมยังบ่านพักคนงานก่อสร้างในเรือนจำอีกต่างหาก (โตมาในเรือนจำ 55+) ชีวิตในนั้นรู้สึกตอนกลางวันจะร้อนมากเพราะไม่มีไฟฟ้าใช้แถมที่พักยังเป็นไม้อัดกับสังกะสี เวลาฝนตกน้ำก็ท่วมอีก ทุกครั้งที่นั่งรถผ่านเรือนจำอำเภอสว่างแดนดิน จ.สกลนคร ผมจะยิ้มอยู่ในใจทุกครั้งพร้อมคิดในใจ “เรือนจำนี้พ่อกูมาสร้างไว้นะโว้ย” ถึงแม้ว่าพ่อจะโดนโกงค่าจ้างก็ตาม…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e899129e17a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The first post]]></title>
            <link>https://medium.com/@jojoekung/the-first-post-dcf99b6bdac2?source=rss-c64ceb16508e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcf99b6bdac2</guid>
            <dc:creator><![CDATA[Suriya Wongkasum]]></dc:creator>
            <pubDate>Tue, 12 Apr 2016 03:27:23 GMT</pubDate>
            <atom:updated>2016-04-12T03:31:34.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O_ZAELVDxlL2_l2S2nnRrg.png" /><figcaption>My logo 9 Hoi game Studio</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcf99b6bdac2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>