<?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 YH Lin on Medium]]></title>
        <description><![CDATA[Stories by YH Lin on Medium]]></description>
        <link>https://medium.com/@yhlin7301?source=rss-3e6f6441f20d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_3MkUo7Y3jSP4mQgAC8CLA.jpeg</url>
            <title>Stories by YH Lin on Medium</title>
            <link>https://medium.com/@yhlin7301?source=rss-3e6f6441f20d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 12:45:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yhlin7301/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[左右符號對稱問題]]></title>
            <link>https://yhlin7301.medium.com/%E5%B7%A6%E5%8F%B3%E7%AC%A6%E8%99%9F%E5%B0%8D%E7%A8%B1%E5%95%8F%E9%A1%8C-e937693f646a?source=rss-3e6f6441f20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e937693f646a</guid>
            <category><![CDATA[java-stack]]></category>
            <dc:creator><![CDATA[YH Lin]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 15:58:40 GMT</pubDate>
            <atom:updated>2023-10-16T15:58:40.817Z</atom:updated>
            <content:encoded><![CDATA[<p>左右符號對稱問題</p><p>寫一個介面</p><pre>package stack;<br><br>public interface Stack&lt;E&gt; {<br>    int size();<br>    boolean isEmpty();<br>    void push(E e);<br><br>    E top();<br>    E pop();<br>}</pre><p>實作Stack Push Pop 方法</p><pre>package stack;<br><br>public class ArrayStack&lt;E&gt; implements Stack&lt;E&gt;{<br>    public static int CAPACITY = 100;<br>    private E[] data;<br>    private int t = -1;<br>    public  ArrayStack(){ this(CAPACITY);}<br><br>    public ArrayStack(int capacity) {<br>        data = (E[]) new Object[capacity];<br>    }<br><br>    @Override<br>    public int size() {<br>        return t+1;<br>    }<br><br>    @Override<br>    public boolean isEmpty() {<br>        return t==-1;<br>    }<br><br>    @Override<br>    public void push(E e) {<br>        if(size()==data.length)  throw  new IllegalStateException(&quot;Stack is full&quot;);<br>        data[++t] = e;<br>    }<br><br>    @Override<br>    public E top() {<br>        if(isEmpty()) return null;<br>        return data[t];<br>    }<br><br>    @Override<br>    public E pop() {<br>        if (isEmpty()) return null;<br>        E answer = data[t];<br>        data[t] = null;<br>        t--;<br>        return answer;<br>    }<br>}</pre><p>寫一個Delimiter 物件</p><pre>public class Delimiter {<br>    char c;<br>    int pos;<br>    public Delimiter(char c, int pos){<br>        this.c = c;<br>        this.pos = pos;<br>    }<br>}</pre><pre>package stack;<br><br>import java.util.Scanner;<br><br>public class MatchDelimiter {<br>    static String str ;<br><br>    public static void main(String[] args) {<br>        Scanner sc = new Scanner(System.in);<br>        Delimiter d;<br>//        str = &quot;((a+b)*(c+d))&quot;;<br>//        str =&quot;((a+b)*(c+d()&quot;;<br>//        str = &quot;(4*5+6*(7+8)/2-(4*3)-2)*3&quot;;<br>        str = &quot;((a+b)-c*e)+(e*(f-g)&quot;;<br>        Stack&lt;Delimiter&gt; buf = new ArrayStack&lt;&gt;();<br>        for (int i = 0; i &lt; str.length(); i++) {<br>            char ch = str.charAt(i);<br>            switch (ch){<br>                case &#39;(&#39;: buf.push(new Delimiter(&#39;(&#39;,i)); break;<br>                case &#39;)&#39;:<br>                    if (!buf.isEmpty()){<br>                        d = buf.pop();<br>                        if (d.c==&#39;(&#39;){<br>                            System.out.println(d.pos+&quot;,&quot;+i);<br>                        }<br>                    }<br>                    break;<br>            }<br>        }<br>        while (!buf.isEmpty()){<br>            d = buf.pop();<br>            System.out.println(d.pos+&quot;,-1&quot;);<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e937693f646a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Listview]]></title>
            <link>https://yhlin7301.medium.com/android-listview-de29b92b88dd?source=rss-3e6f6441f20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/de29b92b88dd</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[YH Lin]]></dc:creator>
            <pubDate>Tue, 24 May 2022 06:18:07 GMT</pubDate>
            <atom:updated>2022-05-24T06:18:07.924Z</atom:updated>
            <content:encoded><![CDATA[<p>今天要呈現的畫面如下，應用的是ListView</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*d-WVkRgg0p8JC_42z1nV4g.png" /></figure><p>首先先準備幾個小圖示，放在drawable 中。</p><p>再來設計UI 的部分，主要的UI 很簡單，單純一個Listview 即可，items 的部分是一個LinearLayout，水平排列。左邊是一個ImageView ，右邊為一個TextView。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05d4c38c0eafb3628ff75fac3740c870/href">https://medium.com/media/05d4c38c0eafb3628ff75fac3740c870/href</a></iframe><p>在MainActivity 的部分資料會以List&lt;HashMap&gt;() 的結構來存放，考量在這個App 中的HashMap 的Value 有String 與int 兩種情況，因此我們先宣告為HashMap&lt;String,Object&gt;的型別，後續在BaseAdapter取出時在做轉型。25–27行中，放了name 為多拉A夢，icon 為R.id.dora 的資料，並存入list中。重複這個步驟三次。</p><p>36行中撰寫了一個自訂的adapter，並在37行的setAdapter中將資料放入。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/154f884b1892a5d9de2e1b1ec76dc291/href">https://medium.com/media/154f884b1892a5d9de2e1b1ec76dc291/href</a></iframe><p>撰寫一個自訂的adaper,23行撰寫一個建構函數。第45 行取得view 。第50行將drawable 的圖檔轉為Bitmap</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b222c29d3a743bfe5478d0bec07dae35/href">https://medium.com/media/b222c29d3a743bfe5478d0bec07dae35/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de29b92b88dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pytorch gpu 時間比較]]></title>
            <link>https://yhlin7301.medium.com/pytorch-gpu-%E6%99%82%E9%96%93%E6%AF%94%E8%BC%83-c24b88c5f514?source=rss-3e6f6441f20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c24b88c5f514</guid>
            <dc:creator><![CDATA[YH Lin]]></dc:creator>
            <pubDate>Sun, 13 Feb 2022 22:04:09 GMT</pubDate>
            <atom:updated>2022-02-13T22:04:09.030Z</atom:updated>
            <content:encoded><![CDATA[<pre>import datetime<br><br>import torch<br>import torch as torch<br><br>is_gpu = torch.cuda.is_available()<br>print(is_gpu)<br>device = torch.device(&quot;cuda:0&quot; if is_gpu else &quot;cpu&quot;)<br>print(device)<br>print(torch.cuda.get_device_name(0))<br>a = torch.randn(1000, 1000)<br>b = torch.randn(1000, 200)<br>t0 = datetime.datetime.now()<br>c = torch.matmul(a, b)<br>t1 = datetime.datetime.now()<br>print(&quot;%6s %s %f&quot; % (a.device, str((t1 - t0) * 24 * 60), c.norm(2)))<br><br>a = a.to(device)<br>b = b.to(device)<br>t0 = datetime.datetime.now()<br>c = torch.matmul(a, b)<br>t1 = datetime.datetime.now()<br>print(&quot;%6s %s %f&quot; % (a.device, str((t1 - t0) * 24 * 60), c.norm(2)))</pre><p>True<br>cuda:0<br>NVIDIA GeForce RTX 3090<br> cpu 0:00:01.726560 14140.868164<br>cuda:0 0:00:00.898560 14140.895508</p><p>Process finished with exit code 0</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c24b88c5f514" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 觀察者模式]]></title>
            <link>https://yhlin7301.medium.com/java-%E8%A7%80%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F-f039c8b64263?source=rss-3e6f6441f20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f039c8b64263</guid>
            <dc:creator><![CDATA[YH Lin]]></dc:creator>
            <pubDate>Wed, 09 Feb 2022 16:33:17 GMT</pubDate>
            <atom:updated>2022-02-09T16:33:17.785Z</atom:updated>
            <content:encoded><![CDATA[<p>UML 模型如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CMmXKE9TG5ElrcciG37AXg.png" /></figure><p>撰寫一個抽象類別Observer 有其抽象方法update.</p><pre>package observer_pattern;<br><br>public abstract class Observer {<br>    public abstract void update(Subject subject);<br>}</pre><p>撰寫一個Subject類別 , 有加上觀察者跟移除觀察者的方法，還有一個notity 更新的方法</p><pre>package observer_pattern;<br><br>import java.util.ArrayList;import java.util.List;<br><br>public class Subject {<br>    List&lt;Observer&gt; observers;<br>    public Subject(){<br>        observers = new ArrayList&lt;&gt;();<br><br>    }<br><br>    public void add_observer(Observer observer){<br>        observers.add(observer);<br>    }<br>    public void remove_observer(Observer observer){<br>        observers.remove(observer);<br>    }<br><br>    public void notify_all(){<br>        for (Observer o:observers ) {<br>            o.update(this);<br>        }<br>    }<br>}</pre><p>建立一個工廠模式FactoryMode繼承Subject，製程透過setPoint更新目前的品質，並呼叫notify_all 更新</p><pre>public class FactoryMode extends Subject{<br>    float point;<br>    public FactoryMode(float point){<br>        super();<br>        this.point = point;<br>    }<br><br>    public float getPoint(){return this.point;}<br><br>    public void  setPoint(float point){<br>        this.point = point;<br>        this.notify_all();<br>    }<br>}</pre><p>CheckPoitnt類別繼承抽象類別Observer<strong>，</strong>並實做update方法，產品品質介於上下管制界線時，呈現in spec</p><pre>public class CheckPoint extends Observer{<br>    float ucl;<br>    float lcl;<br><br>    public CheckPoint(float ucl, float lcl){<br>        this.ucl = ucl;<br>        this.lcl = lcl;<br>    }<br><br>    @Override<br>    public void update(Subject subject) {<br>            FactoryMode fm =  (FactoryMode) subject;<br>            if (ucl&gt;fm.getPoint() &amp;&amp; lcl&lt;fm.getPoint())<br>                System.<em>out</em>.printf(&quot;%.2f %.2f %.2f in spec\n&quot;,ucl,fm.point,lcl);<br>            else<br>                System.<em>out</em>.printf(&quot;%.2f %.2f %.2f out spec\n&quot;,ucl,fm.point,lcl);<br>    }<br>}</pre><p>執行時，另用FactoryMode產生現在的點<strong>，</strong>並加上checkpoint。FactoryMode 透過setPoint 不斷生成製程。同時也更新</p><pre>package observer_pattern;<br><br>public class Script {<br>    public static void main(String[] args) {<br>        FactoryMode fm = new FactoryMode(6.0f);<br>        CheckPoint checkPoint = new CheckPoint(8.7f,3.3f);<br>        fm.add_observer(checkPoint);<br>        fm.setPoint(6.0f);<br>        fm.setPoint(2.0f);<br>        fm.setPoint(9.0f);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f039c8b64263" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MediaStore]]></title>
            <link>https://yhlin7301.medium.com/mediastore-5e2c4121661e?source=rss-3e6f6441f20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e2c4121661e</guid>
            <dc:creator><![CDATA[YH Lin]]></dc:creator>
            <pubDate>Sun, 30 Jan 2022 13:22:47 GMT</pubDate>
            <atom:updated>2022-01-30T13:22:47.038Z</atom:updated>
            <content:encoded><![CDATA[<p>在Android 10 之後的資料夾的檔案會用MediaStore 來控管，官方文件是說為了提供更好的使用者經驗，許多應用程式允許使用者訪問外部媒體。框架提供一個媒體庫。</p><p>在manifests檔中先加上外部管理權限。</p><pre>&lt;uses-permission android:name=&quot;android.permission.MANAGE_EXTERNAL_STORAGE&quot;/&gt;</pre><p>調整一下UI ，練習用constract layout ，在textview 下加上一個button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyVjX2qc1VeF5Kn-qvvScg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b447519ab4d4b5ce78cebd3365c7df1/href">https://medium.com/media/1b447519ab4d4b5ce78cebd3365c7df1/href</a></iframe><p>接下來在OnSearch 的Button 中加上</p><pre>public void search(View view) {<br>    Intent it = new Intent(Intent.<em>ACTION_PICK</em>,<br>            MediaStore.Images.Media.<em>EXTERNAL_CONTENT_URI</em>);<br>    activityResultLauncher.launch(it);<br>}</pre><p>因onActivityResult方法已經棄用了，所以改用registerForActivityResult</p><pre>ActivityResultLauncher&lt;Intent&gt; activityResultLauncher = registerForActivityResult(<br>        new ActivityResultContracts.StartActivityForResult(),<br>        new ActivityResultCallback&lt;ActivityResult&gt;() {<br>            @Override<br>            public void onActivityResult(ActivityResult result) {<br>                Intent it = result.getData();<br>                Uri uri = it.getData();<br>                getImage(uri);<br><br>            }<br>        }<br>);</pre><p>撰寫一個getImage的方法</p><pre>public void getImage(Uri uri){<br>        cursor = cr.query(uri,mProjection,null,null,null);<br>//        int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);<br>        int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.<em>DISPLAY_NAME</em>);<br><br>        if (cursor != null &amp;&amp; cursor.moveToFirst()) {<br>//            long id = cursor.getLong(idColumn);<br>            @SuppressLint(&quot;Range&quot;) String imgPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.<em>DATA</em>));<br>            String fileName = cursor.getString(nameColumn);<br>            Log.<em>d</em>(TAG, fileName);<br>            Log.<em>d</em>(TAG, imgPath);<br>        }<br>    }</pre><p>整個Activity 就會像這樣</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06189668e4e894879b56e9fa693eadd5/href">https://medium.com/media/06189668e4e894879b56e9fa693eadd5/href</a></iframe><p>在Android 10 的結果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PPItEWErZMDY2WhRxSPSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fey9NyZfTCsHxvW8healAA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e2c4121661e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android onActivityResult deprecated]]></title>
            <link>https://yhlin7301.medium.com/android-onactivityresult-deprecated-f0de27738635?source=rss-3e6f6441f20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0de27738635</guid>
            <dc:creator><![CDATA[YH Lin]]></dc:creator>
            <pubDate>Sat, 29 Jan 2022 17:23:19 GMT</pubDate>
            <atom:updated>2022-01-29T17:23:19.609Z</atom:updated>
            <content:encoded><![CDATA[<p>改用registerForActivityResult</p><p>寫一個ActivityResultLauncher&lt;Intent&gt; askforResult物件</p><pre>ActivityResultLauncher&lt;Intent&gt; askforResult = registerForActivityResult(<br>        new ActivityResultContracts.StartActivityForResult(),<br>        new ActivityResultCallback&lt;ActivityResult&gt;(){<br><br>            @Override<br>            public void onActivityResult(ActivityResult result) {<br>                if (result.getResultCode() == Activity.<em>RESULT_OK</em>){<br>                    Intent it = result.getData();<br>                    Uri uri = it.getData();<br>                    Log.<em>d</em>(TAG, uri.toString());<br>                }<br>            }<br>        }<br>);</pre><p>呼叫時改用</p><pre>Intent it = new Intent(Intent.<em>ACTION_PICK</em>, MediaStore.Images.Media.<em>EXTERNAL_CONTENT_URI</em>);<br>askforResult.launch(it);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0de27738635" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ＵＳＲ 整合]]></title>
            <link>https://yhlin7301.medium.com/%EF%BD%95%EF%BD%93%EF%BD%92-%E6%95%B4%E5%90%88-aff759000f4c?source=rss-3e6f6441f20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/aff759000f4c</guid>
            <dc:creator><![CDATA[YH Lin]]></dc:creator>
            <pubDate>Thu, 18 Feb 2021 14:12:57 GMT</pubDate>
            <atom:updated>2021-02-18T14:12:57.578Z</atom:updated>
            <content:encoded><![CDATA[<p>ＵＳＲ 整合</p><p>先劇透一下這次要做的例子</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*8xgu7zYTwA0pWOyuRHttmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Lju8yCgvkbeG1Ofbm-ZY6A.png" /></figure><p>前製作業：</p><p>1.先準備好圖檔，放在res/drawable 目錄下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*uFZdsM0QDxNWUa4OCsEMSQ.png" /></figure><p>撰寫公用Application,裡面紀錄要連線的url,並儲存使用者資訊</p><p>在gradle 中加上</p><pre>implementation &#39;com.google.code.gson:gson:2.8.6&#39;<br>implementation &#39;com.auth0.android:jwtdecode:2.0.0&#39;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/101b08f1e92a4cbff45fe92136f39c70/href">https://medium.com/media/101b08f1e92a4cbff45fe92136f39c70/href</a></iframe><p>設定manifest檔案</p><p>先加網路權限,調整application</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><pre>&lt;application<br>    android:name=&quot;.MainApp&quot;<br>    android:allowBackup=&quot;true&quot;<br>    android:icon=&quot;@mipmap/ic_launcher&quot;<br>    android:label=&quot;@string/app_name&quot;<br>    android:networkSecurityConfig=&quot;@xml/network_security_config&quot;<br>    android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;<br>    android:supportsRtl=&quot;true&quot;<br>    android:theme=&quot;@style/Theme.UsrApp&quot;&gt;<br>    &lt;activity android:name=&quot;.CheckActivity&quot;&gt;&lt;/activity&gt;<br>    &lt;activity android:name=&quot;.Menu&quot; /&gt;<br>    &lt;activity android:name=&quot;.MainActivity&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;</pre><p>在res/xml 下撰寫network_security_config.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;network-security-config&gt;<br>    &lt;base-config cleartextTrafficPermitted=&quot;true&quot; /&gt;<br>&lt;/network-security-config&gt;</pre><p>撰寫網路連線類別</p><p>因為這個專案會很常用到HttpUrlConnection 的post 跟get 方法,所以先把它們抽出來寫成一個類別</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2199a9874ccbfce54407d45602985ae8/href">https://medium.com/media/2199a9874ccbfce54407d45602985ae8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/415aa7259a7b792b1c6140cc36a3e65c/href">https://medium.com/media/415aa7259a7b792b1c6140cc36a3e65c/href</a></iframe><p>開始撰寫主頁的UI,用RelativeLayout 配置,LinearLayout 向下對齊,ImageView 沿著LinearLayout 上方對齊. 利用ImageView 的src 帶出預設背景圖</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cf4a07420648a90f6df1e3e74c4c5da/href">https://medium.com/media/4cf4a07420648a90f6df1e3e74c4c5da/href</a></iframe><p>在MainActivity中,輸入帳號密碼認證後,利用UsrPost 取得物件,利用帳號密碼的物件取得token後將token 存起來,並將token轉成user_id,如果順利取得token 後就可以切換下一頁</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5308edc28a5c9776304e1e041a7e92c/href">https://medium.com/media/c5308edc28a5c9776304e1e041a7e92c/href</a></iframe><p>第2頁產生一個MENU的Activity,Layout 一樣用RelativeLayout</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ac057e75416e64de4db5530c1903e20/href">https://medium.com/media/4ac057e75416e64de4db5530c1903e20/href</a></iframe><p>在第三顆按鈕按下去後執行</p><pre>public void doCheck(View view) {<br>    Intent it = new Intent(this,CheckActivity.class);<br>    startActivity(it);<br>}</pre><p>再開一個checkActivity,Layout 配置以Layout 為主,內含一個RecyclerView</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>    tools:context=&quot;.CheckActivity&quot;&gt;<br>    &lt;androidx.recyclerview.widget.RecyclerView<br>        android:id=&quot;@+id/checkview&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;/&gt;<br><br>&lt;/LinearLayout&gt;</pre><p>待會的adapter 要搭的check_item.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.cardview.widget.CardView<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    app:cardCornerRadius=&quot;10dp&quot;&gt;<br>    &lt;LinearLayout android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/tv_activity_title&quot;<br>        android:textSize=&quot;36dp&quot;<br>        android:gravity=&quot;center&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;100dp&quot;/&gt;<br>    &lt;/LinearLayout&gt;<br><br>&lt;/androidx.cardview.widget.CardView&gt;</pre><p>在checkActivity中OnCreate方法</p><pre>LinearLayoutManager manager = new LinearLayoutManager(this);<br>manager.setOrientation(RecyclerView.<em>VERTICAL</em>);<br>view.setLayoutManager(manager);<br>view.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.<em>VERTICAL</em>));<br>app = (MainApp) getApplication();</pre><p>然後搭配一個執行緒取得後端Activity的活動名稱跟點數,</p><pre>new Thread(new Runnable() {<br>    @Override<br>    public void run() {<br>        try {<br>            UsrGet&lt;Check&gt; usrGet = new UsrGet&lt;&gt;(app.activity_url);<br>            usrGet.setToken(app.getToken());<br>            String response = usrGet.doGet();<br>            Type type = new TypeToken&lt;List&lt;Check&gt;&gt;(){}.getType();<br>            List&lt;Check&gt; checks = usrGet.parseJsonList(response, type);<br>            handler.setData(checks);<br>            handler.sendEmptyMessage(0);<br><br>        } catch (IOException e) {<br>            for (StackTraceElement se:e.getStackTrace())<br>            {app.Log(se.toString());}<br>        }<br><br>    }<br>}).start();</pre><p>透過handler 來處理RecyclerView的UI，在處理handleMessage中會使用到recycleview.setAdapter()來綁訂UI 界面</p><pre>class MyHandler extends Handler{<br>        List&lt;Check&gt; datas;<br>        public void setData(List&lt;Check&gt; datas)<br>        {<br>            this.datas = datas;<br>        }<br>        @Override<br>        public void handleMessage(@NonNull Message msg) {<br>            super.handleMessage(msg);<br>            view.setAdapter(new CheckAdapter(CheckActivity.this,datas));<br>//            view.notifyAll();<br>        }<br>    }</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0401244d61daef855ec3e347cd543de3/href">https://medium.com/media/0401244d61daef855ec3e347cd543de3/href</a></iframe><p>在Adapter中繼承RecyclerView.Adapter 預設建構子傳入一個context ,與List&lt;Check&gt; datas</p><pre>public CheckAdapter(Context context,List&lt;Check&gt; datas)<br>{<br>    this.datas = datas;<br>    this.context = context;<br>    app = (MainApp) ((CheckActivity)context).getApplication();<br>}</pre><p>撰寫ViewHolder</p><pre>class ViewHolder extends RecyclerView.ViewHolder{<br>    TextView tv_activity_title;<br>    public ViewHolder(@NonNull View itemView) {<br>        super(itemView);<br>        tv_activity_title= itemView.findViewById(R.id.<em>tv_activity_title</em>);<br><br>    }<br>}</pre><p>在onCreateViewHolder中綁定checkitem</p><pre>@NonNull<br>@Override<br>public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {<br>    Context c = parent.getContext();<br>    View v = LayoutInflater.<em>from</em>(c).inflate(R.layout.<em>checkitem</em>, parent,false);<br>    ViewHolder vh = new ViewHolder(v);<br>    return vh;<br>}</pre><p>撰寫getItemCount</p><pre>@Override<br>public int getItemCount() {<br>    return datas.size();<br>}</pre><p>撰寫onBindViewHolder,利用setText 秀出值</p><pre>holder.tv_activity_title.setText(datas.get(position).getTitle());</pre><p>因為這邊要做的是按下按鈕後將資料送到後端,因此會有一個run 方法待完成</p><pre>public void run() {<br>                            try {<br>                                UsrPost usrPost = new UsrPost(app.getMy_activity_url());<br>                                usrPost.setToken(app.getToken());<br>                                String response = usrPost.doPost(json);<br>                                Looper.<em>prepare</em>();<br>                                Snackbar.<em>make</em>(holder.itemView, datas.get(position).getTitle()+&quot;已上傳&quot;, Snackbar.<em>LENGTH_LONG</em>).show();<br>                                Looper.<em>loop</em>();<br><br><br>//                                Toast.makeText(context,&quot;檔案已上傳&quot;,Toast.LENGTH_LONG).show();<br>                            } catch (IOException e) {<br>                                e.printStackTrace();<br>                            }<br>                        }</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04370e521ff921457fff8707fee295ac/href">https://medium.com/media/04370e521ff921457fff8707fee295ac/href</a></iframe><p>完整程式</p><p><a href="https://github.com/JackyCafe/UsrApp.git">JackyCafe/UsrApp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aff759000f4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android 的檔案環境]]></title>
            <link>https://yhlin7301.medium.com/android-%E7%9A%84%E6%AA%94%E6%A1%88%E7%92%B0%E5%A2%83-dfe576cdf6c9?source=rss-3e6f6441f20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfe576cdf6c9</guid>
            <dc:creator><![CDATA[YH Lin]]></dc:creator>
            <pubDate>Thu, 18 Feb 2021 11:46:02 GMT</pubDate>
            <atom:updated>2021-02-18T11:46:02.813Z</atom:updated>
            <content:encoded><![CDATA[<p>在Android 的環境中，預設的專案會存放在/data/data/&lt;Package-Name&gt;/</p><p>下，因此當我們寫了一個小的Acticity，系統會生成一個檔案my.log，</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc5abdcf19c6324f90bd9e9c631417c0/href">https://medium.com/media/dc5abdcf19c6324f90bd9e9c631417c0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*OKu07p3Y62Z7zoVI1GDxyQ.png" /></figure><p>openFileOutput 有兩個參數，第2個參數</p><p>MODE_PRIVATE:每次寫出會刪除原來內容</p><p>MODE_APPEND:每次會保留原內容，從檔案尾端寫出site</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfe576cdf6c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django JWT]]></title>
            <link>https://yhlin7301.medium.com/django-jwt-d2d053af957f?source=rss-3e6f6441f20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2d053af957f</guid>
            <dc:creator><![CDATA[YH Lin]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 08:41:11 GMT</pubDate>
            <atom:updated>2021-02-07T08:41:11.228Z</atom:updated>
            <content:encoded><![CDATA[<p>JWT代表JSON Web Token，它是客戶端/服務器應用程序使用的身份驗證策略。通過將用戶名+密碼交換為訪問令牌和刷新令牌來獲取JWT</p><p>開始之前,先安裝</p><pre>pip install djangorestframework<br>pip install djangorestframework-simplejwt</pre><p>接著在settings.py 中</p><pre>INSTALLED_APPS = [<br>   ...<br>    &#39;rest_framework&#39;,<br>    &#39;rest_framework_simplejwt&#39;,<br>]</pre><p>同樣在settings.py中</p><pre>REST_FRAMEWORK = {<br>    &#39;DEFAULTRMISSION_CLASSES&#39;:(&#39;rest_framework.permissions.IsAuthenticated&#39;),<br>    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (<br>        &#39;rest_framework_simplejwt.authentication.JWTAuthentication&#39;,<br>    ),<br>}<br><br>SIMPLE_JWT = {<br>    &#39;REFRESH_TOKEN_LIFETIME&#39;: timedelta(days=15),<br>    &#39;ROTATE_REFRESH_TOKENS&#39;: True,<br>}</pre><p>關於setting 中還有一些設定可參考<a href="https://django-rest-framework-simplejwt.readthedocs.io/en/latest/settings.html">這裡</a></p><p>例如,這是指我的token 可維持的有效期是一天</p><pre>‘ACCESS_TOKEN_LIFETIME’: timedelta(days=1),</pre><p>在urls.py 中加入</p><pre>from rest_framework_simplejwt.views import (<br>    TokenObtainPairView,<br>    TokenRefreshView,<br>)<br>...<br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),<br>    path(&#39;api/token/&#39;, TokenObtainPairView.as_view(), name=&#39;token_obtain_pair&#39;),<br>    path(&#39;api/token/refresh/&#39;, TokenRefreshView.as_view(), name=&#39;token_refresh&#39;),<br>   <br>]</pre><p>這樣我們可以利用</p><pre><a href="https://usr-test-304018.df.r.appspot.com/api/token/">https://127.0.0.1:8000/api/token/</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FOBjOlqNIvj8qHPooji4Ig.png" /></figure><p>在其他的API 想要或得保護時,可以在views.py中加上</p><pre>class ReadingViewSet(viewsets.ModelViewSet):<br>    authentication_classes = [SessionAuthentication, BasicAuthentication]<br>    permission_classes = [IsAuthenticated]<br>    # permission_classes = (AllowAny,)<br>    queryset = Reading.objects.all()<br>    serializer_class = ReadingSerializers<br>    # http_method_names = (&quot;post&quot;, &quot;patch&quot;)<br>    authentication_classes = (JWTAuthentication,)</pre><p>這樣一來,在API 要使用前就會先需要你提供token的資訊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRsjRmZpCdTSQNDVwW9FRg.png" /></figure><p>在postman中可在Authentication 中的type 選擇BearerToken</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wrs82xC-UleJgWQ187Dk8Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2d053af957f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android JWT Example]]></title>
            <link>https://yhlin7301.medium.com/android-jwt-example-a6e287869aa7?source=rss-3e6f6441f20d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6e287869aa7</guid>
            <dc:creator><![CDATA[YH Lin]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 06:40:49 GMT</pubDate>
            <atom:updated>2021-02-22T03:13:28.785Z</atom:updated>
            <content:encoded><![CDATA[<p>Android JWT Example</p><p>這個例子主要要透過Restful Api 在後台登入後,取得token.經由驗證後將資料POST 至後台</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*7cW9x5Dr8Pm2jpNTVmYsNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*oaGDlxzuBMWL3CMhONAsow.png" /></figure><p>POST 至後台的結果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87VNasEd5d8G-qKUqC1uXg.png" /></figure><p>首先在POSTMAN 中先驗證一下API,這是未經驗證的Token,無法post 文章</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UlKqcToTzBSstWMkyTJZCQ.png" /></figure><p>接下來要在Android 中執行</p><p>我們將SharePreference 的讀取程式設定在Application</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38902bf84a37736ced252f7f31f093e9/href">https://medium.com/media/38902bf84a37736ced252f7f31f093e9/href</a></iframe><p>在mainfest 中 application 要加上</p><pre>&lt;application<br>    android:name=&quot;.MainApp&quot;<br>    ....<br>/&gt;</pre><p>在主頁面的Layout 設定為</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e272f34473e18fd298f7d294cc293ffc/href">https://medium.com/media/e272f34473e18fd298f7d294cc293ffc/href</a></iframe><p>在MainActivity中的OnCreate中先檢查,是否有取得之前存在sharepreference 的資料</p><pre>protected void onCreate(Bundle savedInstanceState) {<br><br>    super.onCreate(savedInstanceState);<br>    setContentView(R.layout.<em>activity_main</em>);<br>    ed_user = findViewById(R.id.<em>user</em>);<br>    ed_pwd = findViewById(R.id.<em>pwd</em>);<br>    app = (MainApp) getApplication();<br>    if (!app.getUserName().equals(&quot;&quot;))    {<br>        ed_user.setText(app.getUserName());<br>    }<br>    if (!app.getPwdName().equals(&quot;&quot;))    {<br>        ed_pwd.setText(app.getPwdName());<br>    }<br><br><br>}</pre><p>主要的精髓在利用setRequestProperty 設定header 的訊息,再將須上傳的資料以json 包覆,以output 串流將資料送到後台.</p><p>如果正確取回資料時,conn.getResponseCode 會傳回200,這時再接InputStream 將token 取回來.透過gson 解析後,可以取得&quot;access&quot;</p><p>最後在透過MainApp 中的SetToken 方法,將Token 存回SharePreference</p><pre>private void doAuthentication() {<br>    new Thread(new Runnable() {<br>        @Override<br>        public void run() {<br>            try{<br>                URL url = new URL(app.getTokenURL());<br>                HttpURLConnection conn = (HttpURLConnection) url.openConnection();<br>                conn.setReadTimeout(3000);<br>                conn.setDoInput(true);<br>                conn.setDoOutput(true);<br>                conn.setRequestMethod(&quot;POST&quot;);<br>                conn.setRequestProperty(&quot;Content-Type&quot;, &quot;application/json;charset=UTF-8&quot;);//設定訊息的型別<br>                conn.setRequestProperty(&quot;Accept-Charset&quot;, &quot;UTF-8&quot;);<br>                JSONObject json = new JSONObject();//建立json物件<br>                json.put(&quot;username&quot;, usr);<br>                json.put(&quot;password&quot;,pwd);<br><br>                conn.connect();<br>                Log.<em>v</em>(&quot;Jacky&quot;,&quot;json:&quot;+json.toString());<br><br>                OutputStream out = conn.getOutputStream();<br>                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));<br>                out.write(json.toString().getBytes());//把json字串寫入緩衝區中<br>                out.flush();//重新整理緩衝區，把資料傳送出去，這步很重要<br>                out.close();<br>                bw.close();//使用完關閉<br>                int responseCode = conn.getResponseCode();<br>                Log.<em>v</em>(&quot;Jacky&quot;,&quot;responseCode:&quot;+responseCode);<br>                InputStream in =  conn.getInputStream();<br>                InputStreamReader reader = new InputStreamReader(in);<br>                BufferedReader br = new BufferedReader(reader);<br>                String line = br.readLine();<br>                Gson gson = new Gson();<br>                Token token = gson.fromJson(line, new TypeToken&lt;Token&gt;(){}.getType());<br>                app.setToken(token.getAccess());<br><br><br>            }catch (Exception e){<br>                for (StackTraceElement se: e.getStackTrace())<br>                    Log.<em>v</em>(&quot;Jacky&quot;,se.toString());<br>                Log.<em>v</em>(&quot;Jacky&quot;,e.toString());<br>            }<br><br>        }<br>    }).start();</pre><p>最後透過Intent 將資料送到ReadingActivity</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0566ddc4c742ffca58396f35738eac9b/href">https://medium.com/media/0566ddc4c742ffca58396f35738eac9b/href</a></iframe><p>在ReadingActivity 的Layout 配置,三個EditText,一個Button</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46e4b07fc5be0cfb3db11a97f1384dcc/href">https://medium.com/media/46e4b07fc5be0cfb3db11a97f1384dcc/href</a></iframe><p>在ReadingActivity 的OnCreate 事件中利用JWT 類別來解析token,取得jwt.getClaim(“user_id”) 並轉成字串</p><pre>token = app.getToken();<br>JWT jwt = new JWT(token);<br>Map&lt;String, Claim&gt; allClaims = jwt.getClaims();<br>id = jwt.getClaim(&quot;user_id&quot;).asString();<br>Log.<em>v</em>(&quot;Jacky&quot;,  id);</pre><p>使用JWT 需先於gradle 中載入</p><pre>implementation &#39;com.auth0.android:jwtdecode:2.0.0&#39;</pre><p>在button 中為了將資料Post 到後台需要以執行緒來處理</p><p>在Api 中需要將token 的資訊傳到後台,以setRequestProperty 來處理</p><pre>conn.setRequestProperty(&quot;Authorization&quot;,&quot;Bearer &quot; + token);</pre><pre>public void doPost(View view) {<br><br>       title = ed_title.getText().toString();<br>       category = ed_category.getText().toString();<br>       content = ed_content.getText().toString();<br><br>       new Thread(<br>            new Runnable() {<br>            @Override<br>            public void run() {<br>                try {<br>                    URL url = new URL(app.getUrl());<br>                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();<br>                    conn.setReadTimeout(3000);<br>                    conn.setDoInput(true);<br>                    conn.setDoOutput(true);<br>                    conn.setRequestMethod(&quot;POST&quot;);<br>                    conn.setRequestProperty(&quot;Content-Type&quot;, &quot;application/json;charset=UTF-8&quot;);//設定訊息的型別<br>                    conn.setRequestProperty(&quot;Accept-Charset&quot;, &quot;UTF-8&quot;);<br>                    conn.setRequestProperty(&quot;Authorization&quot;,&quot;Bearer &quot; + token);<br>                    JSONObject json = new JSONObject();//建立json物件<br><br>                    json.put(&quot;title&quot;, title);//使用URLEncoder.encode對特殊和不可見字元進行編碼<br>                    json.put(&quot;category&quot;,category);<br>                    json.put(&quot;content&quot;,content);<br>                    json.put(&quot;user&quot;, id);<br>                    conn.connect();<br><br>                    OutputStream out = conn.getOutputStream();//輸出流，用來發送請求，http請求實際上直到這個函式裡面才正式傳送出去<br>                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));//建立字元流物件並用高效緩衝流包裝它，便獲得最高的效率,傳送的是字串推薦用字元流，其它資料就用位元組流<br>                    out.write(json.toString().getBytes());//把json字串寫入緩衝區中<br>                    out.flush();//重新整理緩衝區，把資料傳送出去，這步很重要<br>                    out.close();<br>                    bw.close();//使用完關閉<br><br>                    int responseCode = conn.getResponseCode();<br>                    Log.<em>v</em>(&quot;Jacky&quot;,&quot;responseCode:&quot;+responseCode);<br>                    if (responseCode &gt;= 400 ) {<br>                        InputStream in =  conn.getErrorStream();<br>                        InputStreamReader reader = new InputStreamReader(in);<br>                        BufferedReader br = new BufferedReader(reader);<br>                        Log.<em>v</em>(&quot;Jacky&quot;,&quot;&quot;+br.readLine());<br><br>                    }else{<br>                        InputStream in =  conn.getInputStream();<br>                        InputStreamReader reader = new InputStreamReader(in);<br>                        BufferedReader br = new BufferedReader(reader);<br>                        Log.<em>v</em>(&quot;Jacky&quot;,&quot;&quot;+br.readLine());<br>                    }<br><br>                }catch (Exception e){<br>                    for (StackTraceElement st :e.getStackTrace())<br>                        Log.<em>v</em>(&quot;Jacky&quot;,&quot;&quot;+st.toString());<br>                }<br>            }<br>        }<br>).start();<br><br><br>   }</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c48d0e4a055f4e0bf46b39a6403c63f/href">https://medium.com/media/9c48d0e4a055f4e0bf46b39a6403c63f/href</a></iframe><p>完整的程式請參考</p><p><a href="https://github.com/JackyCafe/HttpPost.git">JackyCafe/HttpPost</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6e287869aa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>