<?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 Thienphuc on Medium]]></title>
        <description><![CDATA[Stories by Thienphuc on Medium]]></description>
        <link>https://medium.com/@thienphuc1?source=rss-639a0568dd35------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2VaVnS8QusIOXmxe</url>
            <title>Stories by Thienphuc on Medium</title>
            <link>https://medium.com/@thienphuc1?source=rss-639a0568dd35------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:06:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thienphuc1/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[SHARED PREFERENCES TRONG ANDROID]]></title>
            <link>https://medium.com/@thienphuc1/shared-preferences-trong-android-67eda06eacd8?source=rss-639a0568dd35------2</link>
            <guid isPermaLink="false">https://medium.com/p/67eda06eacd8</guid>
            <dc:creator><![CDATA[Thienphuc]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 13:55:58 GMT</pubDate>
            <atom:updated>2022-03-04T06:20:57.286Z</atom:updated>
            <content:encoded><![CDATA[<p>SharedPreferences trong Android cho phép bạn lưu trữ và truy xuất dữ liệu dưới dạng cặp giá trị key — value. Trong ứng dụng Android ngoài cách sử dụng thư viện SQLite hoặc Realm để lưu trữ dữ liệu thì SharedPreferences trong Android có thể sẽ là một giải pháp thay thế.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ulJydoQgFPhBkJpZC3ujpA.png" /></figure><ol><li>Shared Preferences là gì?</li></ol><p><strong>Shared Preferences</strong> là 1 cách lưu trữ những dữ liệu dạng nguyên thủy (bool, int, float, double, String) trong Android dưới dạng file XML với những cặp key/value, ví dụ lưu trữ điểm số của game.</p><p>Trong android có nhiều cách để lưu dữ liệu ở local, ví dụ như Shared Preferences, Realm, SQLite. Tuy nhiên mỗi cách đều có ưu nhược điểm riêng.</p><p>Trong bài này mình nói về Shared Preferences để lưu dữ liệu trong Android.</p><p>Trước hết thì chúng ta nên biết về ưu và nhược điểm của Shared Preferences:</p><ul><li>Ưu điểm: Truy xuất nhanh, dễ hiểu và dễ lập trình.</li><li>Nhược điểm: Có kích thước nhỏ, bị giới hạn chỉ 8192 characters (có thể tham khảo cụ thể ở đây <a href="https://developer.android.com/reference/java/util/prefs/Preferences.html#MAX_VALUE_LENGTH">MAX_VALUE_LENGTH</a> ). Việc lưu trữ và đọc dữ liệu có cấu trúc lớn sẽ gây khó khăn khi mà lưu theo dạng key/value.</li></ul><p>Shared Preferences được lưu ở thư mục riêng tư và chỉ ứng dụng của chúng ta truy cập được. Nhưng nó không có nghĩa là dữ liệu đó sẽ an toàn khi gặp vấn đề người dùng root máy hoặc hacker xâm nhập được vào kho thư mục. Vì thế chúng ta nên cần có biện pháp bảo mật trước khi lưu vào shared preferences nếu dữ liệu đó cần độ bảo mật cao. Vấn đề này có thể tìm hiểu thêm về <a href="https://developer.android.com/training/articles/keystore.html"><strong>Android keystore system</strong></a><strong>.</strong></p><p>Và để làm việc với Shared Preferences, Android SDK có cung cấp 2 class là SharedPreferences và SharePreferences.Editor.</p><pre>SharedPreferences sharedPreferences = mContext.getSharedPreferences(<em>MY_SHARE_PREFERENCES</em>,<br>        Context.<em>MODE_PRIVATE</em>);<br>SharedPreferences.Editor editor = sharedPreferences.edit();</pre><p>Ở đây <em>MY_SHARE_PREFERENCES </em>là tên của SharedPreferences.</p><p>2. Cách lưu trữ và lấy dữ liệu với SharedPreferences</p><p>Chúng ta sẽ tạo 1 project nhỏ để demo về cách lưu và lấy dữ liệu với SharedPreferences.</p><ul><li>Tạo UI, chúng ta sẽ lưu data ở MainActivity và show data đã lưu trên Main2Activity.</li></ul><p>File xml của MainActivity</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout 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;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;20dp&quot;<br>        android:orientation=&quot;horizontal&quot;<br>        android:weightSum=&quot;10&quot;&gt;<br><br>        &lt;EditText<br>            android:id=&quot;@+id/edtUserName&quot;<br>            android:layout_width=&quot;0dp&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_weight=&quot;7&quot;<br>            android:hint=&quot;User name&quot; /&gt;<br><br>        &lt;Button<br>            android:id=&quot;@+id/btnSaveData&quot;<br>            android:layout_width=&quot;0dp&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_weight=&quot;3&quot;<br>            android:text=&quot;Save&quot; /&gt;<br><br>    &lt;/LinearLayout&gt;<br><br><br>&lt;/LinearLayout&gt;</pre><p>File xml của Main2Activity</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot;<br>    tools:context=&quot;.MainActivity2&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/tvShowData&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        android:layout_margin=&quot;50dp&quot;<br>        android:text=&quot;Data&quot;<br>        android:textSize=&quot;15dp&quot;<br>        android:textStyle=&quot;bold&quot; /&gt;<br><br>&lt;/LinearLayout&gt;</pre><ul><li>Tạo class MySharePreferences để put và get data.</li></ul><p>Class MySharePreferences</p><pre>package com.example.share_preferences;<br><br>import android.content.Context;<br>import android.content.SharedPreferences;<br><br>// put get data<br>public class MySharePreferences {<br><br>    // tên của SharedPreferences<br>    private static final String <em>MY_SHARE_PREFERENCES </em>= &quot;MY_SHARE_PREFERENCES&quot;;<br><br>    // tạo 1 biến môi trường<br>    private Context mContext;<br><br>    // tạo constructor cho SharedPreferences<br>    public MySharePreferences(Context mContext) {<br>        this.mContext = mContext;<br>    }<br><br>    // 2 hàm put và get data cho việc check lần đầu install app - kiểu boolean<br>    public void putBooleanValue(String key, boolean value) {<br>        SharedPreferences sharedPreferences = mContext.getSharedPreferences(<em>MY_SHARE_PREFERENCES</em>,<br>                Context.<em>MODE_PRIVATE</em>);<br>        SharedPreferences.Editor editor = sharedPreferences.edit();<br>        editor.putBoolean(key, value);<br>        editor.apply();<br>    }<br><br>    public boolean getBooleanValue(String key) {<br>        SharedPreferences sharedPreferences = mContext.getSharedPreferences(<em>MY_SHARE_PREFERENCES</em>,<br>                Context.<em>MODE_PRIVATE</em>);<br>        return sharedPreferences.getBoolean(key, false);<br>    }<br><br>    // 2 hàm put và get data username - kiểu string<br>    public void putStringValue(String key, String value) {<br>        SharedPreferences sharedPreferences = mContext.getSharedPreferences(<em>MY_SHARE_PREFERENCES</em>,<br>                Context.<em>MODE_PRIVATE</em>);<br>        SharedPreferences.Editor editor = sharedPreferences.edit();<br>        editor.putString(key, value);<br>        editor.apply();<br>    }<br><br>    public String getStringValue(String key) {<br>        SharedPreferences sharedPreferences = mContext.getSharedPreferences(<em>MY_SHARE_PREFERENCES</em>,<br>                Context.<em>MODE_PRIVATE</em>);<br>        return sharedPreferences.getString(key, &quot;&quot;);<br>    }<br>}</pre><ul><li>Tạo class DataLocalManager để định nghĩa và quản lý data khi lưu vào SharePreferences.</li></ul><p>Class DataLocalManager</p><pre>package com.example.share_preferences;<br><br>import android.content.Context;<br><br>// quản lý data lưu vào SharedPreferences<br>public class DataLocalManager {<br><br>    private static DataLocalManager <em>instance</em>;<br>    public static final String <em>KEY_FIRST_INSTALL </em>= &quot;KEY_FIRST_INSTALL&quot;;<br>    public static final String <em>PREF_NAME_USER </em>= &quot;PREF_NAME_USER&quot;;<br>    private MySharePreferences mySharePreferences;<br><br>    // ham khoi tao<br>    public static void init(Context context) throws Exception {<br>        <em>instance </em>= new DataLocalManager();<br>        <em>instance</em>.mySharePreferences = new MySharePreferences(context);<br>        throw new Exception(&quot;Initialize error!&quot;);<br>    }<br><br>    public static DataLocalManager getInstance() {<br>        if (<em>instance </em>== null) {<br>            <em>instance </em>= new DataLocalManager();<br>        }<br>        return <em>instance</em>;<br>    }<br><br>    // ham check lần đầu install app<br>    public static void setFirstInstalled(boolean isFirst) {<br>        DataLocalManager.<em>getInstance</em>().mySharePreferences.putBooleanValue(<em>KEY_FIRST_INSTALL</em>, isFirst);<br>    }<br><br>    public static boolean getFirstInstalled() {<br>        return DataLocalManager.<em>getInstance</em>().mySharePreferences.getBooleanValue(<em>KEY_FIRST_INSTALL</em>);<br>    }<br><br>    // hàm set và get UserName từ SharedPreferences<br>    public static void setNameUser(String nameUser) {<br>        DataLocalManager.<em>getInstance</em>().mySharePreferences.putStringValue(<em>PREF_NAME_USER</em>, nameUser);<br>    }<br><br>    public static String getNameUser() {<br>        return DataLocalManager.<em>getInstance</em>().mySharePreferences.getStringValue(<em>PREF_NAME_USER</em>);<br>    }<br>}</pre><ul><li>Tạo class MyApplication extent từ class Application để khởi tạo DataLocalMagnager và khai báo class này ở Manifest như sau:</li></ul><p>Class MyApplication</p><pre>package com.example.share_preferences;<br><br>import android.app.Application;<br><br>public class MyApplication extends Application {<br>    @Override<br>    public void onCreate() {<br>        super.onCreate();<br><br>        // khởi tạo DataLocalMananger ở đây, để có thể dùng DataLocalMananger ở nhiều activity khác nhau.<br>        try {<br>            DataLocalManager.<em>init</em>(getApplicationContext());<br>        } catch (Exception e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p>khai báo ở Manifest:</p><pre>android:name=&quot;.MyApplication&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ln_MGqQpDYyCCKSyiLiyTQ.png" /></figure><ul><li>Ở MainActivity chúng ta có 1 EditText để nhập username và 1 Button để lưu data vào SharedPreferences.</li></ul><p>MainActivity</p><pre>package com.example.share_preferences;<br><br>import android.content.Intent;<br>import android.os.Bundle;<br>import android.widget.Button;<br>import android.widget.EditText;<br>import android.widget.Toast;<br><br>import androidx.appcompat.app.AppCompatActivity;<br><br>public class MainActivity extends AppCompatActivity {<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.<em>activity_main</em>);<br>        Button btnSaveUserName = findViewById(R.id.<em>btnSaveData</em>);<br>        EditText edtUserName = findViewById(R.id.<em>edtUserName</em>);<br><br>        // check app xem có phải lần đầu tiên install<br>        if (!DataLocalManager.<em>getFirstInstalled</em>()) {<br>            Toast.<em>makeText</em>(this, &quot;First install app&quot;, Toast.<em>LENGTH_SHORT</em>).show();<br>            DataLocalManager.<em>setFirstInstalled</em>(true);<br>        }<br><br>        // save data username vào SharedPreferences và intent sang activity 2 để show data.<br>        btnSaveUserName.setOnClickListener(v -&gt; {<br>            if(edtUserName.getText().length() &gt; 0){<br>                DataLocalManager.<em>setNameUser</em>(edtUserName.getText().toString().trim());<br>                Toast.<em>makeText</em>(this, &quot;save username success&quot;, Toast.<em>LENGTH_SHORT</em>).show();<br>                Intent intent = new Intent(MainActivity.this, MainActivity2.class);<br>                startActivity(intent);<br>            }else {<br>                Toast.<em>makeText</em>(this, &quot;username null!&quot;, Toast.<em>LENGTH_SHORT</em>).show();<br>            }<br>        });<br><br>    }<br>}</pre><ul><li>Ở trên chúng ta sẽ check app install lần đầu bằng các dòng code sau:</li></ul><pre>if (!DataLocalManager.<em>getFirstInstalled</em>()) {<br>    Toast.<em>makeText</em>(this, &quot;First install app&quot;, Toast.<em>LENGTH_SHORT</em>).show();<br>    DataLocalManager.<em>setFirstInstalled</em>(true);<br>}</pre><ul><li>Show data đã lưu được ở Main2Activity</li></ul><p>Main2Activity</p><pre>package com.example.share_preferences;<br><br>import androidx.appcompat.app.AppCompatActivity;<br><br>import android.os.Bundle;<br>import android.widget.TextView;<br><br>public class MainActivity2 extends AppCompatActivity {<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.<em>activity_main2</em>);<br>        TextView tvShowData = findViewById(R.id.<em>tvShowData</em>);<br><br>        // show data vừa lưu ở activity 1<br>        tvShowData.setText(DataLocalManager.<em>getNameUser</em>());<br>    }<br>}</pre><p>Kết quả:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*Zhnf46PYamB6zp7cGDdvJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*JChCdwuxwNMi-HN0qQekzg.png" /></figure><p>Có thể tìm file data này ở mục Device File Explorer trong AndroidStudio.</p><ul><li>Device File Explorer -&gt; data -&gt; data -&gt; tên package project(ở đây của mình là com.example.share_preferences) -&gt; shared_prefs -&gt; tên SharedPreferences.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*6cWVER8D7lktd-tBbs4N6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*gHG0oLZvS3ArcG4El-6ltg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKV38Ziwa-tnhwNbXJzbfg.png" /></figure><p>Ngoại trừ việc put và get, SharedPreferences còn cung cấp các thao tác sau:</p><ul><li>Kiểm tra xem một key có tồn tại hay không</li><li>Lắng nghe việc thay đổi của shared preferences thông qua listener</li><li>Đọc toàn bộ các entries thành map</li><li>Xóa bỏ một entry</li><li>Xóa bỏ toàn bộ các entries (Clear all)</li></ul><p><strong>Tổng kết</strong>: Trên đây là kiến thức cá nhân mà mình tìm hiểu được về Shared Preferences, nếu có thiếu sót hoặc bổ sung gì thì các bạn có thể comment bên dưới. Và các bạn có thể tìm hiểu các kiến thức khác cũng như thêm về Shared Preferences và chi tiết hơn trên docs của <a href="https://developer.android.com/reference/android/content/SharedPreferences"><strong>Android Developer</strong></a>. Cảm ơn các bạn đã dành thời gian để đọc đến đây. Xin cảm ơn!</p><p><strong>Reference</strong>:</p><ul><li><a href="https://github.com/thienphuc83/share-preferences"><strong>Link source</strong></a></li><li><a href="https://developer.android.com/reference/android/content/SharedPreferences"><strong>Docs</strong></a></li><li><a href="https://developer.android.com/training/articles/keystore"><strong>Android keystore system</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67eda06eacd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DÙNG RETROFIT TRONG ANDROID]]></title>
            <link>https://medium.com/@thienphuc1/d%C3%B9ng-retrofit-trong-android-860f1bbc8f35?source=rss-639a0568dd35------2</link>
            <guid isPermaLink="false">https://medium.com/p/860f1bbc8f35</guid>
            <dc:creator><![CDATA[Thienphuc]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 13:54:56 GMT</pubDate>
            <atom:updated>2022-03-04T06:31:14.097Z</atom:updated>
            <content:encoded><![CDATA[<p>Trong quá trình phát triển một ứng dụng android. Việc sử lý dữ liệu từ server không phải lúc nào cũng dễ dàng. Vì vậy để giải quyết vấn đề phức tạp đó trong android, chúng ta thường sử dụng các thư viện ngoài để hỗ trợ. Có thể nói phổ biến nhất hiện nay có thể kể đến như Volley, Retrofit,… Hôm nay chúng ta sẽ đi tìm hiểu về Retrofit để hiểu hơn về quá trình làm việc giữa server và phía client cụ thể ở đây là ứng dụng android.</p><ol><li>Retrofit là gì?</li></ol><p><strong>Retrofit</strong> được định nghĩa là một type-safe HTTP client cho Java, Android và Kotlin do công ty Square phát triển. Retrofit hỗ trợ cho các nhà lập trình chuyển đổi API thành Java Interface để dễ dàng kết nối đến một dịch vụ REST trên web.</p><p><strong>Retrofit</strong> là một trong những thư viện Rest-Client được sử dụng phổ biến hiện nay trong việc hỗ trợ giao tiếp giữa client và server trở nên thuận tiện hơn. Thư viện này rất mạnh mẽ cho phép bạn dễ dàng xử lý dữ liệu JSON hoặc XML và sau đó sẽ phân tích cú pháp thành Plain Old Java Objects (POJOs). Tại đây, hầu hết các yêu cầu như GET, POST, PUT, PATCH, và DELETE đều có thể được thực hiện.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0Rq5ugx_FsPWs0xrSbClaA.png" /></figure><p><strong>*Retrofit</strong> không tích hợp bất kỳ một bộ chuyển đổi JSON nào để phân tích từ JSON thành các đối tượng Java. Thay vào đó nó đi kèm với các thư viện chuyển đổi JSON sau đây để xử lý điều đó:</p><ul><li>Gson: com.squareup.retrofit2:converter-gson</li><li>Jackson: com.squareup.retrofit2:converter-jackson</li><li>Moshi: com.squareup.retrofit2:converter-moshi</li><li>Protobuf: com.squareup.retrofit2:converter-protobuf</li><li>Wire: com.squareup.retrofit2:converter-wire</li><li>Simple XML: com.squareup.retrofit2:converter-simplexml</li><li>JAXB: com.squareup.retrofit2:converter-jaxb</li><li>Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars</li></ul><p>Và để dễ hình dung cũng như hiểu về retrofit thì code là cách chúng ta tiếp cận với nó nhanh nhất.</p><p>2. Demo project sử dụng retrofit.</p><p>Ở đây mình sẽ dùng retrofit kết hợp với converters là Gson.</p><p>Dưới đây là data của server, chúng ta có thể dùng tool <a href="https://jsonformatter.curiousconcept.com/">Json Formatter</a> để dễ xem hơn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJMMce3VFKAb62I10mfTyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COkCTSEeN3tYIcKef6maoA.png" /></figure><p>Và bắt đầu vào project demo thôi.</p><p>3. Demo</p><ul><li>Để dùng được retrofit trong ứng dụng, chúng ta cần phải import thư viện retrofit và gson vào project ở file grandle.app trong mục dependencies.</li></ul><pre>// import retrofit<br>implementation &quot;com.squareup.retrofit2:retrofit:2.9.0&quot;<br>// import converter - gson<br>implementation &quot;com.squareup.retrofit2:converter-gson:2.9.0&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*infX71rlhVSVti-Oxjepkg.png" /></figure><ul><li>Tiếp theo chúng ta cần phải ánh xạ cấu trúc dữ liệu từ Json về 1 đối tượng trong project của chúng ta bằng cách tạo 1 class object. Ở đây của mình là object Example (mình chỉ lấy về 1 số thứ cơ bản trong Json thôi).</li></ul><p>File model object Example</p><pre>package com.example.retrofit_demo;<br><br>public class Example {<br>    private int id;<br>    private String title;<br>    private String status;<br>    private String overview;<br>    private int budget;<br><br>    public Example(int id, String title, String status, String overview, int budget) {<br>        this.id = id;<br>        this.title = title;<br>        this.status = status;<br>        this.overview = overview;<br>        this.budget = budget;<br>    }<br><br>    public int getId() {<br>        return id;<br>    }<br><br>    public void setId(int id) {<br>        this.id = id;<br>    }<br><br>    public String getTitle() {<br>        return title;<br>    }<br><br>    public void setTitle(String title) {<br>        this.title = title;<br>    }<br><br>    public String getStatus() {<br>        return status;<br>    }<br><br>    public void setStatus(String status) {<br>        this.status = status;<br>    }<br><br>    public String getOverview() {<br>        return overview;<br>    }<br><br>    public void setOverview(String overview) {<br>        this.overview = overview;<br>    }<br><br>    public int getBudget() {<br>        return budget;<br>    }<br><br>    public void setBudget(int budget) {<br>        this.budget = budget;<br>    }<br>}</pre><ul><li>Tạo 1 file interface APIServer để cấu hình retrofit.</li></ul><p>File interface APIServer</p><pre>package com.example.retrofit_demo;<br><br>import retrofit2.Call;<br>import retrofit2.Retrofit;<br>import retrofit2.converter.gson.GsonConverterFactory;<br>import retrofit2.http.GET;<br>import retrofit2.http.Query;<br><br>// Cấu hình retrofit<br>public interface APIServer {<br><br>    APIServer <em>apiServer </em>= new Retrofit.Builder()<br>            .baseUrl(&quot;https://api.themoviedb.org/3/&quot;)<br>            .addConverterFactory(GsonConverterFactory.<em>create</em>())<br>            .build()<br>            .create(APIServer.class);<br><br>    // hàm call api - link api ở đây đang là phương thức GET<br>    @GET(&quot;movie/550&quot;)<br>    Call&lt;Example&gt; getExample(@Query(&quot;api_key&quot;) String api_key);<br>}</pre><p>Ở đây với <strong><em>baseUrl() </em></strong>chính là nơi để link api gốc, và <strong><em>.addConverterFactory(GsonConverterFactory.create()) </em></strong>để converter về Gson.</p><p>Hàm call api ở đây được dùng với phương thức <strong><em>GET</em></strong>. Dùng <strong><em>Call&lt;Example&gt;</em></strong> để trả về đối tượng Example. Trong hàm <strong><em>getExample() </em></strong>cần truyền param <strong><em>api_key</em></strong> cho api, api_key ở đây được truyền bằng kiểu String.</p><ul><li>Cuối cùng là tạo UI để show data và viết hàm call api ở file MainActivity.java</li></ul><p>File MainActivity</p><pre>package com.example.retrofit_demo;<br><br>import android.os.Bundle;<br>import android.widget.Button;<br>import android.widget.TextView;<br>import android.widget.Toast;<br><br>import androidx.appcompat.app.AppCompatActivity;<br><br>import retrofit2.Call;<br>import retrofit2.Callback;<br>import retrofit2.Response;<br><br>public class MainActivity extends AppCompatActivity implements Callback&lt;Example&gt; {<br><br>    private final String key_api = &quot;9fd4581a0377d675761b350cc9a405c1&quot;;<br><br>    TextView tvTitle, tvStatus, tvOverview, tvBudget;<br>    Button btnCallAPI;<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.<em>activity_main</em>);<br>        tvTitle = findViewById(R.id.<em>tvTitle</em>);<br>        tvStatus = findViewById(R.id.<em>tvStatus</em>);<br>        tvOverview = findViewById(R.id.<em>tvOverview</em>);<br>        tvBudget = findViewById(R.id.<em>tvBudget</em>);<br>        btnCallAPI = findViewById(R.id.<em>btnCallAPI</em>);<br><br>        // call api<br>        btnCallAPI.setOnClickListener(v -&gt; onCallAPI(key_api));<br><br>    }<br><br>    // hàm call api<br>    private void onCallAPI(String key_api) {<br>        APIServer.<em>apiServer</em>.getExample(key_api).enqueue(this);<br>    }<br><br>    // hàm trả về data khi call api thành công<br>    @Override<br>    public void onResponse(Call&lt;Example&gt; call, Response&lt;Example&gt; response) {<br>        if (response.body() == null) {<br>            Toast.<em>makeText</em>(this, &quot;Call api data null!&quot;, Toast.<em>LENGTH_SHORT</em>).show();<br>            return;<br>        }<br>        tvTitle.setText(response.body().getTitle());<br>        tvStatus.setText(response.body().getStatus());<br>        tvOverview.setText(response.body().getOverview());<br>        tvBudget.setText(String.<em>valueOf</em>(response.body().getBudget()));<br>        Toast.<em>makeText</em>(this, &quot;Call api success&quot;, Toast.<em>LENGTH_SHORT</em>).show();<br>    }<br><br>    // call api thất bại<br>    @Override<br>    public void onFailure(Call&lt;Example&gt; call, Throwable t) {<br>        Toast.<em>makeText</em>(this, &quot;Call api fail!&quot;, Toast.<em>LENGTH_SHORT</em>).show();<br>    }<br>}</pre><p>File UI xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/btnCallAPI&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        android:layout_marginTop=&quot;5dp&quot;<br>        android:text=&quot;Call API&quot; /&gt;<br><br>    &lt;TextView<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        android:layout_margin=&quot;10dp&quot;<br>        android:text=&quot;Data&quot;<br>        android:textSize=&quot;20dp&quot;<br>        android:textStyle=&quot;bold&quot; /&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:orientation=&quot;horizontal&quot;&gt;<br><br>        &lt;TextView<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;Title:&quot;<br>            android:textSize=&quot;15dp&quot;<br>            android:textStyle=&quot;bold&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/tvTitle&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_gravity=&quot;center&quot;<br>            android:layout_marginLeft=&quot;5dp&quot;<br>            android:textSize=&quot;10dp&quot; /&gt;<br>    &lt;/LinearLayout&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:orientation=&quot;horizontal&quot;&gt;<br><br>        &lt;TextView<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;Status:&quot;<br>            android:textSize=&quot;15dp&quot;<br>            android:textStyle=&quot;bold&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/tvStatus&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_gravity=&quot;center&quot;<br>            android:layout_marginLeft=&quot;5dp&quot;<br>            android:textSize=&quot;10dp&quot; /&gt;<br>    &lt;/LinearLayout&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:orientation=&quot;horizontal&quot;&gt;<br><br>        &lt;TextView<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;Overview:&quot;<br>            android:textSize=&quot;15dp&quot;<br>            android:textStyle=&quot;bold&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/tvOverview&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_gravity=&quot;center&quot;<br>            android:layout_marginLeft=&quot;5dp&quot;<br>            android:ellipsize=&quot;end&quot;<br>            android:maxLines=&quot;2&quot;<br>            android:textSize=&quot;10dp&quot; /&gt;<br>    &lt;/LinearLayout&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:orientation=&quot;horizontal&quot;&gt;<br><br>        &lt;TextView<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;Budget:&quot;<br>            android:textSize=&quot;15dp&quot;<br>            android:textStyle=&quot;bold&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/tvBudget&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_gravity=&quot;center&quot;<br>            android:layout_marginLeft=&quot;5dp&quot;<br>            android:textSize=&quot;10dp&quot; /&gt;<br>    &lt;/LinearLayout&gt;<br><br>&lt;/LinearLayout&gt;</pre><ul><li><strong>Và quan trọng nhất là chúng ta phải cấp quyền INTERNET trong file Manifest của project như sau:</strong></li></ul><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    package=&quot;com.example.retrofit_demo&quot;&gt;<br><br>    <strong>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;</strong><br>    &lt;application<br>        android:allowBackup=&quot;true&quot;<br>        android:icon=&quot;@mipmap/ic_launcher&quot;<br>        android:label=&quot;@string/app_name&quot;<br>        android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;<br>        android:supportsRtl=&quot;true&quot;<br>        android:theme=&quot;@style/Theme.Retrofitdemo&quot;&gt;<br>        &lt;activity<br>            android:name=&quot;.MainActivity&quot;<br>            android:exported=&quot;true&quot;&gt;<br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;<br><br>                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/activity&gt;<br>    &lt;/application&gt;<br><br>&lt;/manifest&gt;</pre><p>Và đây là kết quả:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*1ZbO-oI-KbLQIUSC0qOUDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*DYqvfqoPLEL_VyPWE09hwQ.png" /></figure><p><strong>Tổng kết</strong>: Trên đây là bài giới thiệu sơ lược qua việc ứng dụng Retrofit trong lập trình Android. Và nếu có thiếu sót gì mong các bạn có thể góp ý để mình có thể cải thiện bài viết tốt hơn. Xin cảm ơn!</p><p><strong>Reference:</strong></p><ul><li><a href="https://github.com/thienphuc83/retrofit-demo"><strong>Link source</strong></a></li><li><a href="https://square.github.io/retrofit/"><strong>Doc</strong></a></li><li><a href="https://github.com/google/gson"><strong>Gson</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=860f1bbc8f35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MÔ HÌNH MVP TRONG ANDROID]]></title>
            <link>https://medium.com/@thienphuc1/m%C3%B4-h%C3%ACnh-mvp-trong-android-9aad8285f778?source=rss-639a0568dd35------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aad8285f778</guid>
            <dc:creator><![CDATA[Thienphuc]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 13:53:42 GMT</pubDate>
            <atom:updated>2022-03-04T06:27:31.259Z</atom:updated>
            <content:encoded><![CDATA[<p>Mô hình MVP trong Android viết tắt của Model — View — Presenter, đây là mô hình kiến trúc hiện đang được nhiều lập trình viên lựa chọn sử dụng.</p><ol><li>Mô hình MVP là gì?</li></ol><p>Mô hình MVP trong Android (Model — View — Presenter) là một mô hình kiến trúc hướng giao diện người dùng giúp tách tầng trình diễn ra khỏi tầng dữ liệu. MVP Pattern trong Android mang lại lợi thế dễ dàng mở rộng một cách nhanh chóng, dễ dàng bảo trì và dễ dàng kiểm thử.</p><p>2. Các thành phần trong mô hình MVP</p><ul><li><strong>Model:</strong> đại diện cho một tập hợp các lớp mô tả business logic (business model and the data model). Nó cũng định nghĩa các business rules cho dữ liệu (nghĩa là cách mà dữ liệu thay đổi và được dùng)</li><li><strong>View:</strong> là thành phần tương tác trực tiếp với người dùng như XML, Activity, fragments. Nó không bao gồm bất kỳ việc xử lý logic nào.</li><li><strong>Presenter:</strong> sẽ nhận input của người dùng thông qua View, rồi xử lý dữ liệu của người dùng với sự trợ giúp của Model và trả kết quả về View. Presenter giao tiếp với View qua interface. Interface được định nghĩa trong lớp Presenter(với cái nó cần truyền dữ liệu). Activity/fragment hoặc các view component khác implement interface này và render dữ liệu.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*fgtS7zdONsY94wMBenBeLQ.jpeg" /></figure><p>Trong cấu trúc MVP, presenter thao túng model và cập nhật ở view. View và Presenter tách biệt với nhau hoàn toàn và giao tiếp với nhau qua thông qua interface.</p><p>3. Thiết kế mô hình MVP trong Android</p><p>Chúng ta sẽ làm 1 project nhỏ về call api sử dụng mô hình MVP.</p><p>Bước 1: Tạo file model Example và cấu hình retrofit để lấy data từ server.</p><p>File model Example</p><pre>package com.example.himovie.model<br><br>import com.google.gson.annotations.SerializedName<br><br>data class Example(<br>    @SerializedName(&quot;id&quot;) val id: Int,<br>    @SerializedName(&quot;original_title&quot;) val original_title: String,<br>    @SerializedName(&quot;poster_path&quot;) val poster_path: String,<br>    @SerializedName(&quot;overview&quot;) val overview: String<br>)</pre><p>Cấu hình Retrofit:</p><p>File Config</p><pre>package com.example.himovie.api<br><br>import retrofit2.Retrofit<br>import retrofit2.converter.gson.GsonConverterFactory<br><br>object Config {<br><br>    var URL_BASE = &quot;https://api.themoviedb.org/3/&quot;<br>    private var retrofit: Retrofit? = null<br><br>    val apiService: ApiService<br>        get() {<br>            if (retrofit == null) {<br>                retrofit = Retrofit.Builder()<br>                    .baseUrl(URL_BASE)<br>                    .addConverterFactory(GsonConverterFactory.create())<br>                    .build()<br>            }<br>            return retrofit!!.create(ApiService::class.<em>java</em>)<br>        }<br>}</pre><p>File APIServer</p><pre>package com.example.himovie.api<br><br>import com.example.himovie.model.Example<br>import retrofit2.Call<br>import retrofit2.http.GET<br>import retrofit2.http.Query<br><br>interface ApiService {</pre><pre>    @GET(&quot;movie/550&quot;)<br>    fun getExample(@Query(&quot;api_key&quot;) api_key: String): Call&lt;Example&gt;<br><br>}</pre><p>Bước 2: Thiết kế UI trên file xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;vertical&quot;<br>    tools:context=&quot;.activity.MainActivity&quot;&gt;<br><br>    &lt;Button<br>        android:id=&quot;@+id/btnCallApi&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        android:text=&quot;Call API&quot;<br>        android:textAllCaps=&quot;false&quot; /&gt;<br><br>    &lt;TextView<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginBottom=&quot;5dp&quot;<br>        android:text=&quot;Data from API&quot;<br>        android:textSize=&quot;15dp&quot;<br>        android:textStyle=&quot;bold&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/tvData&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:padding=&quot;5dp&quot;<br>        android:text=&quot;Data&quot;<br>        android:textSize=&quot;10dp&quot; /&gt;<br><br>&lt;/LinearLayout&gt;</pre><p>như sau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*4kB5cLdMoEYtLvtCSXOrVw.png" /></figure><p>Bước 3: Tạo file CallAPIPresenter để xử lý logic khi call api từ server.</p><p>File CallAPIPresenter</p><pre>package com.example.himovie.presenter<br><br>import com.example.himovie.api.Config<br>import com.example.himovie.model.Example<br>import retrofit2.Call<br>import retrofit2.Callback<br>import retrofit2.Response<br><br>class CallAPIPresenter : Callback&lt;Example&gt; {<br><br>    // khai báo interface<br>    private var callAPIInterface: CallAPIInterface<br><br>    constructor(callAPIInterface: CallAPIInterface) {<br>        this.callAPIInterface = callAPIInterface<br>    }<br><br>    // gọi api<br>    fun onCallAPI(key_api: String) {<br>        Config.apiService.getExample(key_api).enqueue(this)<br>    }<br><br>    override fun onResponse(call: Call&lt;Example&gt;, response: Response&lt;Example&gt;) {<br>        if (response.body() == null) {<br>            callAPIInterface.onCallAPIDataNull()<br>            return<br>        }<br>        callAPIInterface.onCallAPISuccess(response.body()!!)<br>    }<br><br>    override fun onFailure(call: Call&lt;Example&gt;, t: Throwable) {<br>        callAPIInterface.onCallAPIFail(&quot;error&quot;)<br>    }<br>}</pre><p>Bước 4: Tạo file interface CallAPIInterface để presenter giao tiếp với view.</p><p>File CallAPIInterface</p><pre>package com.example.himovie.presenter<br><br>import com.example.himovie.model.Example<br><br>interface CallAPIInterface {<br>    fun onCallAPISuccess(example: Example)<br>    fun onCallAPIFail(error: String)<br>    fun onCallAPIDataNull()<br>}</pre><p>Bước 5: Và cuối cùng gắn data được xử lý từ presenter lên view thông qua interface ở file MainActivity.</p><p>File MainActivity</p><pre>package com.example.himovie.activity<br><br>import android.os.Bundle<br>import android.widget.Toast<br>import androidx.appcompat.app.AppCompatActivity<br>import com.example.himovie.R<br>import com.example.himovie.model.Example<br>import com.example.himovie.presenter.CallAPIInterface<br>import com.example.himovie.presenter.CallAPIPresenter<br>import kotlinx.android.synthetic.main.activity_main.*<br><br>class MainActivity : AppCompatActivity(), CallAPIInterface {<br><br>    // khai báo presenter<br>    private lateinit var callAPIPresenter: CallAPIPresenter<br><br>    // truyền param để gọi data từ api<br>    private val keyAPI: String = &quot;9fd4581a0377d675761b350cc9a405c2&quot;<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.<em>activity_main</em>)<br><br>        // khởi tạo presenter<br>        callAPIPresenter = CallAPIPresenter(this)<br><br>        btnCallApi.setOnClickListener <strong>{<br>            </strong>callAPIPresenter.onCallAPI(keyAPI)<br>        <strong>}<br>    </strong>}<br><br>    // xử lý data từ presenter qua interface<br>    override fun onCallAPISuccess(example: Example) {<br>        tvData.<em>text </em>= example.original_title<br>    }<br><br>    override fun onCallAPIFail(error: String) {<br>        Toast.makeText(this, error, Toast.<em>LENGTH_SHORT</em>)<br>    }<br><br>    override fun onCallAPIDataNull() {<br>        Toast.makeText(this, &quot;data null&quot;, Toast.<em>LENGTH_SHORT</em>)<br>    }<br>}</pre><p>Cấu trúc tổ chức thư mục mô hình MVP trong Android như sau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*Xry1ZdYeXFjWirdbAPym8Q.png" /></figure><p>Và đây là kết quả:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*rDUzWK9DwxY31Dha-3gIdQ.png" /></figure><p><strong>Tổng kết</strong>: MVC, MVP, MVVM là những Architecture Pattern tốt nhất thường được các lập trình viên sử dụng khi xây dựng ứng dụng Android, còn bạn nghĩ đâu là mô hình tốt nhất?</p><p><strong>Reference:</strong></p><ul><li><a href="https://github.com/thienphuc83/himovie"><strong>Link source</strong></a></li><li><a href="https://www.geeksforgeeks.org/mvp-model-view-presenter-architecture-pattern-in-android-with-example/"><strong>Doc</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aad8285f778" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>