[Android] Adapter

Adapter 將資料轉換為元件可以接受的格式,例如我們可以將資料庫的資料顯示在ListView類型的元件或者是下拉式選單Spinner這種類型的元件。

Adapter分為底下幾種類型,用於連接不同形式的資料來源。
ArrayAdapter<T>A concrete BaseAdapter that is backed by an array of arbitrary objects. 
BaseAdapterCommon base class of common implementation for an Adapter that can be used in both ListView (by implementing the specialized ListAdapter interface) and Spinner (by implementing the specialized SpinnerAdapter interface). 
CursorAdapterStatic library support version of the framework's CursorAdapter
HeaderViewListAdapterListAdapter used when a ListView has header views. 
ListAdapterExtended Adapter that is the bridge between a ListView and the data that backs the list. 
ResourceCursorAdapterStatic library support version of the framework's ResourceCursorAdapter
SimpleAdapterAn easy adapter to map static data to views defined in an XML file. 
SimpleCursorAdapterStatic library support version of the framework's SimpleCursorAdapter
SpinnerAdapterExtended Adapter that is the bridge between a Spinner and its data. 
WrapperListAdapterList adapter that wraps another list adapter. 


使用範例:

ArrayAdapter<String> Adapter_note = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, note_array);

setListAdapter(Adapter_note); //Bind to Adapter

要先New一個ArrayAdapter物件,輸入三個參數
1. this 表示目前的Activity
2. android.R.layout.simple_list_item_1 要轉換成的格式
3. note_array 資料來源


透過 getListView().setEmptyView(findViewById(R.id.empty)); 可以顯示當List為空時要顯示的內容。

[Android] setContentView

為了與使用者互動,我們會提供各種畫面。如何顯示我們想要顯示的畫面?此時透過setContentView這個方法來實現。setContentView可以帶Resource id

例如:
 setContentView(R.layout.activity_main);

就會將activity_main 這個原本在/layout/activity_main.xml 設計好的UI與元件顯示在使用者螢幕上。


[Android] 介面元件

介面元件有許多類型,例如:TextView, EditView, Button 等。

要使用介面元件前,需要先定義好它們,定義在layout目錄下的xxx.xml

例如
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world"
/>

介面元件又可分為需要在程式中做後續處理以及不需要在程式中做後續處理兩類。
若需要在程式中做後續處理需要定義 android:id。

例如
<TextView android:id="@+id/empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:text="No Notes!"/>

上例的android:id 為empty,程式運行時,依條件判斷,當需要顯示這個TextView時,就可以利用R.id.empty來存取這個介面元件。


說明 @+id/empty
@:表示其後面為識別符號
+:表示要新建一個識別符號
id/:表示識別符號會被歸類為
empty:表示元件的android:id


[Android] adb shell 顯示 access data folder permission denied

使用adb shell指令後,想要存取手機data資料夾,會遇到權限不足,無法存取的情形(Permission denied)。
 

此時只要使用run-as指令,後面接 package_name 就可以存取package下的資料夾。

例如:
shell@android:/ $ run-as org.myapp.test



C語言筆記 結構Struct

struct建立方式

struct student{
char name[20];
int id;
char phone[10];
};

宣告一個具有student結構的變數john
struct student john;

存取
john.phone

結構的初始化
struct student john = {"John", 931001, "0999123123"};

記憶體位址必須為4的倍數,因此,結構中若有field宣告不是4的倍數(Ex: 宣告char phone[10]),他的下一個filed會被配置在4的倍數的記憶體位置(alignment)。

struct student{

char name[20];
int id;
char phone[10];

};

以上結構size為36,非34。


指定struct中的欄位值
strcpy(john.name, "Jonh");
john.id  = 930001;

結構指標
struct student john;
struct student *ptr = &john;  //結構指標宣告方式
ptr->id = 930001;

參數傳遞
結構可當函式的參數或是當回傳值,當結構被定義了之後,就可以當作一種資料類別來使用。

使用傳遞結構指標會比傳遞整個結構來得有效率,結構指標只佔4bytes記憶體空間。

typedef 可將struct 語法簡化,Ex:
typedef struct complex Complex;
後續在程式中使用Complex就代表struct complex
由於可能跨檔案都會需要Complex這個sturct,可以將此定義在標頭檔,Ex: complex.h,只要引入comple.h就能用到此typedef

struct complex{
int real;
int imag;
};
typedef struct complex Complex;

可以簡化為

typedef struct complex{
int real;
int imag;
} Complex;


一個結構也可以使用在另一個結構當欄位

C 語言 檔案處理 File IO

二進制檔案與文字模式的差異在於 二進制直接以位元組作輸出入,而文字模式將位元組轉為ASCII碼,再作輸出入。


使用fread/fwrite進行讀寫
函式原型
int fread(void *buf, int size, int n, FILE *fp);
將n筆fp資料,以每筆size大小,讀入buf緩衝區

int fwrite(const void *buf, int size, int n, FILE *fp);
將buf中的n筆資料,以每筆size大小,寫入fp


二進制輸出入最常見的用途就是將結構陣列整個寫入檔案


透過fseek可以隨機存取想要存取的位置
函式原型
int fseek(FILE *fp, long int offset, int base);
offset以位元組為單位,可以為負數。
base可以為  SEEK_SET檔案起點、SEEK_CUR目前位置、SEEK_END檔案終點


使用rewind可以將讀寫位置移到檔案起點。
函式原型
void rewind(FILE *fp);


EOF是一種狀態,不是一種字元
判斷是否處於EOF狀態可以使用feof
函式原型 int feof(FILE *fp);
如果已經EOF傳回1,否則傳回0



C語言 資料結構DataStructure

以struct作為存資料的節點,以指標作為資料的連結

由於無法預期資料數,因此需透過malloc向系統要求記憶體空間。不用之後可透過free返還記憶體。使用malloc/free需引用 <stdlib.h>

函式原型
void *malloc(size_t size);
void free(void *ptr);

malloc 參數size代表要求的記憶體大小,回傳值為要到的記憶體位址,如果無法得到的記憶體會回傳NULL。

每次呼叫malloc後應該檢查回傳值是否為NULL

一個結構節點如何取得記憶體
struct node *ptr;
ptr = (struct node *)malloc(sizeof(struct node)); //取一塊與struct相同size的記憶體,將其由void*,轉型為struct node *,透過ptr指標來操作節點。

17.2 assert
assert是一個函式,後面接一個條件,若條件不為真,程式就會停止執行。使用assert需要include <assert.h>

17.3 鏈結序列
利用struct宣告鏈結序列中的節點,節點包含兩部分,一個欄位儲存資料,一個欄位儲存鏈結序列中的下一個節點位置。方法如下,
struct listnode{
int data; //節點資料
struct listnode *next; //指向下一個節點
};

連結的第一個節點稱為head,鏈結最後一個節點的next指向NULL,表示鏈結序列的結束。


逐一檢視鏈結序列的節點(遍歷 traverse)
ptr = head;
while(ptr != NULL){
process *ptr;
ptr = ptr->next;
}

or


for(ptr = head; ptr != NULL; ptr = ptr->next)
process *ptr;


保留上一個節點作法
ptr = head;
while(ptr != NULL){
process *ptr;
previous = ptr; //先利用previous紀錄節點位置
ptr = ptr->next; //將節點指向下一個

}


把新節點加到兩個舊節點的方法
current->next = last->next;
last->next= current;


17.3.2 遞迴處理

鏈結序列可用遞迴定義
NULL是鏈結序列
一個節點加上該節點指向的鏈結序列,也是鏈結序列



17.4 二元樹
一個節點有兩個指標,分別指向兩個節點
NULL是二元樹
一個節點加上該節點指向的左二元樹及右二元樹,也是一個二元樹

17.4.1 節點
如何宣告一個二元樹中的節點?
struct treenode{
int data;
struct treenode *left;
struct treenode *right;
};

typedef struct treenode Treenode;

17.4.2 二元搜尋樹
定義
NULL是一個二元樹
一個節點如果
左右子樹都是二元搜尋樹
所有左子樹節點的資料都不大於該節點的資料
所有右子樹節點的資料都不小於該節點的資料
那麼這個節點加上左右子樹也是一個二元搜尋樹


17.4.3 二元樹遍歷
前序 preoder  根, 左子樹, 右子樹
中序 inorder 左子樹, 根, 右子樹
後序 postorder 左子樹, 右子樹, 根




C 語言 物件Object

一個物件把相關的資料和操作包裝起來
以堆疊stack來說明物件

18.2.1堆疊結構

第一個物件元素 - 結構
struct stack{
int top;
char elements[100];
};
typedef struct stack Stack;


18.2.2 堆疊函式宣告

第二個物件元素 - 函式
void init_stack(Stack *s)
int stack_empty(Stack *s)
int stack_full(Stack *s)
void push_stack(Stack *s, char c)
int pop_stack(Stack *s);


標頭檔<xxx.h> 與 "xxx.h"的差異
以<>標示者,編譯器會到系統標頭檔目錄尋找
以""標示者,編譯會到引入""的程式的目錄尋找

18,2.3 堆疊函式實作

C 語言 Chapter19 前置處理Preprocessor

前置處理是編譯器開始編譯程式碼之前所做的處理。可透過前置處理將程式碼動態調整成我們想要的形式,前置處理指令有#include, #define, #if #ifdef #ifndef,  #, __LINE__, __FILE__, ##

19.1 #include

直接將標頭檔引入要編譯的程式碼。
標頭檔詳細定義資料結構,以及操作資料結構所需使用的函式名稱、參數及回傳值。
系統標頭檔由 <> 括起
使用者標頭檔由 "" 括起來


19.2 #define

將程式碼中所定義的字串換成另一字串。
一般習慣用 #define定義常數
用typedef定義資料類別,但也可用#define定義資料類別 Ex: #define Data int

透過#defien也可以定義巨集函式,Ex:  #define marco(x)  x * x
巨集函式非一個完整函式,只是進行字串的代換。

透過 gcc -E 指令可以將前置處理的結果送到螢幕。

例如程式碼

#define square(x) x * x

int main(void){

int i,j;
scanf("%d", &i);
scanf("%d", &j);
printf("%d\n", square(i+j));

執行gcc -E xxx.c 後得到的結果為

int main(void){

int i,j;
scanf("%d", &i);
scanf("%d", &j);
printf("%d\n", i+j * i+j);
return 0;
}

透過此方法可以驗證,巨集的使用是否得到預期的結果,以上的算式 i+j * i + j顯然不是我們想要的。

因此,可將巨集修正為 #define square(x) ((x) * (x))


int main(void){

int i,j;
scanf("%d", &i);
scanf("%d", &j);
printf("%d\n", ((i+j) * (i+j)));
return 0;

}

若傳進巨集的為一個函式,而且會有回傳值,使用巨集不是一個好方法。


19.3 條件編譯 #if, #ifdef, #ifndef
依據前置處理指令#if來決定程式碼要不要編譯Ex:
#if condition
source code
#endif

只有condition為true時,上述的source code才會執行,常用於是否列印除錯資訊,例如:

#define DEBUG 0
...
#if DEBUG == 1
printf("This is debug message. \n");
#endif

透過控制DEBUG定義值,決定是否印出除錯資訊。

在編譯時使用-DSYMBOL=VALUE語法可以動態改變#define值,而不需要修改程式。Ex:
gcc -DDEBUG_LEVEL=8 program.c
如此在編譯時會將DEBUG_LEVEL 的值給定為8,但編譯器define,程式碼也define造成重複定義(redefine)。此時要透過#ifndef來處理。如果#ifndef後面的符號未被定義,則#ifndef到#endif中間的程式碼會被編譯,如果已經有定義,就不會被編譯。

透過#ifndef,我們使用下面的程式碼,來避免透過-D造成的重複定義問題,當編譯時未使用-D則DEBUG_LEVEL預設為4
#ifndef DEBUG_LEVEL
#define DEBUG_LEVEL 4
#endif

若程式中只是要單純的開關,透過前置處理指令#ifdef可以達成。
#ifdef DEBUG
source code
#endif

在編譯器中可以透過 gcc -DDEBUG program.c 來開關
在程式中可以透過 #define DEBUG來開關
使用#undef則可以將某符號取消定義。#undef DEBUG


19.4 __LINE__, __FILE__
__LINE__ 知道前置處理目前的行數
__FILE__ 知道前置處理目前的檔名

printf("file %s, line %d", __FILE__, __LINE__);


19.5 ##
##可以將前後的名字連在一起,例如: S_IR ## USR 會成為S_IRUSR

安裝Android APP 開發環境

Android開發者資源可以在 http://developer.android.com/index.html 找到,有豐富的開發文件。

若我們要以Windows作業系統為開發Android APP,需要安裝JDKEclipse IDE with built-in ADT with the Android SDK for Windows,以下分別進行說明。

1. JDK ( http://www.oracle.com/technetwork/java/javase/downloads/index.html)
JDK(Java SE Development Kit)是提供給Java程式開發者的工具,Android APP是以JAVA程式語言進行開發,JDK包含了JRE(Java Runtime Environment)Java執行時需要的環境以及開發、除錯、監控Java應用程式的工具。

根據作業系統下載相對應的JDK

下載完畢後,執行安裝 jdk-8u25-windows-x64.exe (不同版本有不同檔名)




設定系統變數PATH,將路徑設定完畢後,有助於方便執行程式JAVAC

系統 > 進階系統設定


點選環境變數


選擇系統變數的Path


點選編輯,並將變數值以分號區隔加入C:\Program Files\Java\jdk1.8.0_25\bin

若沒有維護系統變數,在C:\下將找不到JAVAC這個程式

必須將路徑切換到C:\Program Files\Java\jdk1.8.0_25\bin才可以執行相關程式,很不便利。
設定好後,需要重開機,環境變數設定值才會生效,可在command window下執行path,確認目前的path值

測試Java程式是否能編譯成功
使用javac 編譯 filename.java 會產生 filename.class
再透過 java filename 執行 filename這支程式。


2. Eclipse IDE with built-in ADT with the Android SDK for Windows ( http://developer.android.com/sdk/index.html Download)
這個套件包含了三個主要工具,也可分開下載安裝。
Eclipse: IDE開發平台,可以部署專案,檔案,並在此開發環境編寫Java程式,編譯程式。
ADT: Android開發工具擴充套件(Android Development Tools plugin)
Android SDK: Android 程式開發套件 (Android Software Development Kit),我們主要的開發平台,提供了各式Lib、API,並提供Emulator模擬手機。



使用Eclipse建立Android Project [草稿]

點選 File > New > Android Application Project,就會出現精靈協助產生Android Project需要的檔案,在Application Name填入Application的名稱,其餘可以都先按Next,直到最後一步點選Finish,便產生一個預設的、什麼也不做Application。






產生Project





[Android] 加入對話框Dialog

要使用對話框Dialog需要先import android.app.AlertDialog

然後new一個AlertDialog實體,透過setTitle設定Title,透過setMessage設定內容,然後透過show這個方法顯示內容。



可參考 https://developer.android.com/reference/android/app/AlertDialog.Builder.html


要在Dialog加入按鈕,需要import android.content.DialogInterface;

想要加入一個確認按件,程式碼如下,因為onClick內容為空,表示不做任何事就跳出Dialog。






[Android] 使用Toast 提示訊息

Toast 可以短暫顯示訊息,然後自動消失在畫面上,方便用於提示使用者。

使用Toast需import android.widget.Toast;

使用方式很簡單,只要以下程式碼就可以顯示

private void openToast(){
Toast.makeText(this, R.string.about_msg, Toast.LENGTH_SHORT).show();
}



[Android] 使用try catch處理使用者輸入錯誤

try catch 可以針對例外事件做處理,因此若使用者輸入有誤的格式造成exception,就可以利用try{
主流程
}
catch(Exception obj){
例外處理
}

程式碼如下,若輸入不是數字,抓到exception後提示輸入Number。
try{
         ...
     double height = Double.parseDouble(edit_text_height.getText().toString())/100;
     double weight = Double.parseDouble(edit_text_weight.getText().toString());
        ....
}catch(Exception obj){
Toast.makeText(MainActivity.this, "Please input Number", Toast.LENGTH_SHORT).show();
}

[Android] 認識AndroidManifest.xml

APP是跑在Android系統上,既然要跑在其上,就必須提供資訊給Android System。這些資訊就存在AndroidManifest中。

AndroidManifest 存放在 app/src/main/ 目錄下

它的功能如下:
1. 命名Java package,這個命名提供了唯一的名稱,
2. 描述application的組成元件,再透過類別來啟動這些組成元件,例如運用 Intent 這個class
-activities
-services
-broadcast receivers
-content providers
3. 決定哪些processes主持application
4. 宣告這個App有哪些權限
5. 也宣告其他App要存取application components需要哪些權限
6. 列出Instrumentation這個class來分析application執行時的情形
7. 需告要執行此Application最低的API版本
8. 列出application需要link的library


Manifest架構

允許的Element,藍字是預設常見的Element,其中的<manifest>與<application>是必要且只能出現一次。每個Element有各自的屬性,屬性數量不一定,每個屬性有其預設值,可視需求進行設定。

<action>
<activity> 
<activity-alias>
<application> 
<category>
<data>
<grant-uri-permission>
<instrumentation>
<intent-filter> 
<manifest> 
<meta-data>
<permission>
<permission-group>
<permission-tree>
<provider>
<receiver>
<service>
<supports-screens>
<uses-configuration>
<uses-feature>
<uses-library>
<uses-permission>
<uses-sdk>


預設的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bmi" 名稱空間
    android:versionCode="1"   開發者使用流水版號
    android:versionName="1.0" >  供使用者看的版本號

    <uses-sdk
        android:minSdkVersion="8" 最低相容SDK版本
        android:targetSdkVersion="21" /> 目標版本,若沒設定預設為最低minSdkVersion

    <application
        android:allowBackup="true" 是否允許備份
        android:icon="@drawable/ic_launcher" App Icon
        android:label="@string/app_name" App名稱
        android:theme="@style/AppTheme" > App風格
        <activity activity, service, receiver, provider是組成application的4個主要項目
            android:name=".MainActivity" activity名稱,可和manifest package串在一起
            android:label="@string/app_name" > APP開啟後,顯示在畫面上方的名稱
            <intent-filter> activity操作方式
                <action android:name="android.intent.action.MAIN" /> .MAIN表示activity是APP進入點

                <category android:name="android.intent.category.LAUNCHER" /> 顯示在應用程式列表
            </intent-filter>
        </activity>
    </application>

</manifest>

完整的架構
<?xml version="1.0" encoding="utf-8"?>
<manifest>

    <uses-permission />
    <permission />
    <permission-tree />
    <permission-group />
    <instrumentation />
    <uses-sdk />
    <uses-configuration />  
    <uses-feature />  
    <supports-screens />  
    <compatible-screens />  
    <supports-gl-texture />  

    <application>

        <activity>
            <intent-filter>
                <action />
                <category />
                <data />
            </intent-filter>
            <meta-data />
        </activity>

        <activity-alias>
            <intent-filter> . . . </intent-filter>
            <meta-data />
        </activity-alias>

        <service>
            <intent-filter> . . . </intent-filter>
            <meta-data/>
        </service>

        <receiver>
            <intent-filter> . . . </intent-filter>
            <meta-data />
        </receiver>

        <provider>
            <grant-uri-permission />
            <meta-data />
            <path-permission />
        </provider>

        <uses-library />

    </application>
</manifest>

[Android] 新增Activity

一個Activity代表一個頁面。要新增一個頁面就要新增一個Activity。我們可以透過Intent和startActivity來啟動另一個Activity。

要新增一個Activity需要以下的動作
1. 新增一個class file
2. 在manifest.xml新增<Activity>
3. 在原本的Activity加入startActivity啟用另一個Activity

新增一個class file

在Eclipse Package Explorer畫面按右鍵 > New > Class
Name填入class名稱
Superclass選擇android.app.Activity
完成後點選Finish
產生了Report.java


因為要顯示介面,所以要在res/layout目錄下新增一個xml來描述Report這個Activity。
然後要在AndroidManifest.xml新增<activity>
如何新增?在Application頁籤>Application Note點選Add,選Activity完成新增。


Application Note右側出現Attribute for Activity,在Name點選Browser會出現目前專案中的Activity,選擇要的Activity,OK完成新增。

 



比較AndroidManifest前後發現新增了   <activity android:name="Report"></activity>
當然也可以透過手動修改AndroidManifest.xml進行Activity新增。






最後一個步驟,在原本的Activity中使用startActivity啟動另一個Activity,寫法如下。
先import android.content.Intent;
然後在OnClickListener的onClick,加入以下程式碼,即可啟動Report.class。
Intent intent = new Intent();
intent.setClass(MainActivity.this, Report.class);  //setClass(來源, 目的地)
startActivity(intent);

[Android] 使用Intent 在不同的Activity傳遞資料

要將在Activity A輸入的資料送到Activity B進行運算,我們可以透過Intent來實現。
資料的傳送分為傳送端與接收端

傳送端程式碼
說明: new一個intent實體,setClass(A,B)由A傳到B,new一個Bundle把要傳的資料透過putString存放在KEY中,intent.putExtras(bundle)把bundle放在intent準備一起傳送,startActivity傳送。

     public void onClick(View v){

     Intent intent = new Intent();
intent.setClass(MainActivity.this, Report.class);
Bundle bundle = new Bundle();
bundle.putString("KEY_HEIGHT", edit_text_height.getText().toString());
bundle.putString("KEY_WEIGHT", edit_text_weight.getText().toString());
intent.putExtras(bundle);
startActivity(intent);
     }

接收端程式碼
說明:getIntent().getExtras()取得bundle內容,budle.getString(KEY)取得KEY存放的內容。

Bundle bundle = this.getIntent().getExtras();
double height = Double.parseDouble(bundle.getString("KEY_HEIGHT"))/100;


double weight = Double.parseDouble(bundle.getString("KEY_WEIGHT"));

[Android] 在Diaglog按鈕連到外部網站

我們在設計Android APP 時,可能會在about頁面中提供我們公司或個人網址,以下要說明如何透過按鈕按一下,就開啟瀏覽器,前往我們設定的網站。

透過Dialog setPositiveButton與setNegativeButton,我們可以註冊不同的行為。例如,一個按鈕可能是確認confirm,另一個按鈕則是前往首頁Home。

aboutDialog.setPositiveButton(R.string.confirm, aboutConfirm);
aboutDialog.setNegativeButton(R.string.home, aboutHome);

aboutHome是我們註冊的function,它的內容如下,當onClick發生時,就依uri這個實體的內容,連到指定的網址。

使用Uri需要import  android.net.Uri
再使用startActivity,與其他Activity互動。
intent.ACTION_VIEW依據所提供的內容不同,開啟對應的程式檢視內容。

private DialogInterface.OnClickListener aboutHome = new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse("http://lupin33roundtheworld.blogspot.tw/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
};

在Google Chrome 安裝模擬器 ARchon runtime environment

Step1. 下載ARchon runtime environment
下載點 https://github.com/vladikoff/chromeos-apk/blob/master/archon.md#instructions
依據作業系統選擇32bits或64bits (點擊 BitBucket 或 Mirror)

作業系統判斷方式: 開始 > 電腦 (按右鍵) > 內容 > 在系統類型 這欄會顯示32/64位元作業系統

下載回來的檔名可能類似  ARChon-v1.2-x86_64.zip

Step2. 解壓縮,預設解完壓縮的資料夾名稱類似 vladikoff-archon-6ad1d59d5f1a

Step3. 載入ARchon
開啟Google Chrome,點選右上角的管理按鈕,然後選擇設定(S)

進入設定頁面後,點選"擴充功能",並勾選"開發人員模式",才會出現"載入無封裝擴充功能",接著點選"載入無封裝擴充功能"


選擇先前解壓縮的資料夾vladikoff-archon-6ad1d59d5f1a,點選"確定"。


出現下面的圖樣就大功告成了

如果你對旅行有興趣,歡迎來我們FB的旅遊粉絲頁看看吧
https://www.facebook.com/Lupin33RoundTheWorld

[Android]使用SharedPreferences儲存使用者設定資料

運用SharedPreferences可以儲存使用者輸入的資料,然後可於下次啟動APP時,讀取上次儲存的值,避免使用者重複輸入的困擾。

那何時讀取資料?何時儲存資料?我們要瞭解Activity的生命週期。一個Activity就是APP的一個畫面,當畫面切換時,表示切換到另一個Activity。
因此,我們要在Activity被產生時,載入先前儲存的資料,即在 onCreate() 中載入。
而我們要在切換到另一個畫面時儲存資料,即在 onPause() Funtion中進行儲存。

接著看程式碼如何撰寫。

載入說明:
在onCreate function加入載入的程式碼restorePrefs()這個function,然後運用SharedPreferences類別,取得手機中的設定檔PREF,再利用getString方法取得特定的設定值,然後將值給予指定的欄位,例如:edit_text_height.setText();

public static final String PREF = "BMI_PREF";
public static final String PREF_HEIGHT = "BMI_Height";

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        restorePrefs();
        setListeners();
}

//Restore preferences
private void restorePrefs(){
SharedPreferences settings = getSharedPreferences(PREF,0);
String pref_height = settings.getString(PREF_HEIGHT, "");
if(! "".equals(pref_height)){
edit_text_height.setText(pref_height);
edit_text_weight.requestFocus();
}
}


儲存說明:
在onPause function加入儲存的程式碼,產生SharedPreferences類別,將值存到手機中的設定檔PREF,利用edit().putString將值寫到指定的欄位PREF_HEIGHT,然後再透過.commit()完成儲存。

@Override
protected void onPause() {
super.onPause();
//save user preferences
SharedPreferences settings = getSharedPreferences(PREF, 0);
settings.edit()
.putString(PREF_HEIGHT, edit_text_height.getText().toString())
.commit();
}
如果你對旅行有興趣,歡迎來我們FB的旅遊粉絲頁看看吧
https://www.facebook.com/Lupin33RoundTheWorld

清華大學 計算機網路 第5週課程 IEEE 802.1Q VLAN

VLAN-1 https://www.youtube.com/watch?v=nD27wJNVICI

5.1. Which of the following statements are correct for a layer 2 network that consists of stations connected by switches/bridges ?
(a) A layer 2 network is a broadcast domain which means that when a station sends a broadcast frame, the frame will be forwarded to all stations.
(b) A multicast frame will also be forwarded to all stations.
(c) A multicast frame will only be forwarded to all the members of the multicast group.
(d) A unicast frame will only be forwarded to its destination station.

5.2. What are the correct ways for a switch/bridge to handle received frames ?
(a) A switch/bridge only receives frames detinated to the switch/bridge.
(b) A switch/bridge receives and handles all frames coming into its ports.
(c) A switch/bridge handles a received frame by store-and-forward mechanism.
(d) A switch/bridge forwards a received frame by looking up the destination MAC address of the frame.

(e) A switch/bridge forwards a received frame by looking up the source MAC address of the frame.


VLAN-2 https://www.youtube.com/watch?v=0z9ORPXS7LE

5.3. Which of the following statements are correct for the VLAN ?
(a) A VLAN is a logical group of stations within a bridged LAN (BLAN).
(b) The members of a VLAN can be added, removed, or changed dynamically.
(c) The VLAN function is supported over shared and point-to-point media.
(d) Each VLAN has a unique identification (VID).
(e) All the bridges/switches must be VLAN aware devices.


5.4. We said that traffic between VLANs is firewalled. This means that
(a) The stations belong to different VLANs can not transmit packets to each other directly.
(b) The traffic between VLANs must be forwarded by a router.
(c) A physical firewall is built between VLANs.
(d) Only the broadcast traffic between VLANs are limited. Unicast traffic can still be exchanged directly between VLANs.
(e) Only the broadcast and multicast traffic between VLANs are limited.


5.5. Without VLAN configuration setting, what happens when a station sends a broadcast or multicast frame in a bridged LAN (BLAN) ?
(a) The frame will be forwarded by the routers connected to the bridged LAN.
(b) The frame will be filtered by the routers connected to the bridged LAN.
(c) A broadcast frame will be forwarded to all the stations in the bridged LAN.
(d) A multicast frame will only be forwarded to all the members of the multicast group.
(e) A multicast frame will be forwarded to all the stations in the bridged LAN.


5.6. What happens when a member of a VLAN x sends a broadcast frame ?
(a) The frame will be forwarded to all the stations in the bridged LAN.
(b) The frame will be forwarded to all the stations in the VLAN x.
(c) The frame will be forwarded by the routers connected to the bridged LAN.
(d) The frame will be filtered by the routers connected to the bridged LAN.
(e) The frame will be forwarded to all the stations in the VLAN x and VLAN y, where VLAN y and VLAN x are in the same switch.



VLAN-3 https://www.youtube.com/watch?v=JrkBuGvPzW0

VLAN可分為
Port Based
Mac Based
IP-Subnet Based
Layer-3 Protocol Based


VLAN-4 https://www.youtube.com/watch?v=xdnRMmZCCzM

5.7. Which of the following statements are correct for a port-based VLAN configuration ? Assume the port VID (PVID) of port x is 10 and a frame is received from port x.
(a) If the frame is untagged, then the VID of the frame will be 10.
(b) If the frame is already tagged with a VID = 20, then the VID of the frame will be 20.
(c) If the frame is already tagged with a VID = 20, then the VID of the frame will be changed to 10.
(d) Any station directly connects to port x will belong to VLAN 10.
(e) If a “hub” is connected to port x, then all the stations connected to this hub will belong to VLAN 10.

5.8. Consider the following port-based VLAN configuration with 3 bridges/switches. Which of the following statements are correct ?



(a) Both the links connecting (bridge 1, bridge 2) and (bridge 1, bridge 3) are trunk link.
(b) When a station of VLAN 3 sends a broadcast frame, the frame will be processed by all the three bridges.
(c) When a station of VLAN 3 sends a broadcast frame, the frame will be processed by bridge 1 and bridge 3.
(d) When a station of VLAN 1 sends a broadcast frame, the frame will also be processed by all the three bridges.
(e) When a station of VLAN 2 sends a broadcast frame, the frame will also be processed by bridge 1 and bridge 3.

5.9. Which of the following statements are correct for a MAC-based VLAN configuration ? Assume the port VID (PVID) of port x is 10 and a frame with source MAC address (SRC) and destination MAC address (DST) is received from port x.
(a) The VID of the frame will be 10.
(b) The VID of the frame is the VLAN where the SRC belongs to.
(c) The VID of the frame is the VLAN where the DST belongs to.
(d) In a MAC-based VLAN environment, all frames are actually untagged with a VLAN ID.
(e) A station always belongs to the same VLAN even the connected port of the station is changed dynamically.



VLAN-5 https://www.youtube.com/watch?v=7D3Q3XrWK5Q

5.10. Which of the following tagging rules for an “access link” are correct ?
(a) All frames traversing an access link must be tagged.
(b) All frames traversing an access link must be untagged.
(c) There can be a mix of implicitly and explicit tagged frames in access link but they must be for different VLANs.
(d) For each VLAN, all frames traversing an access link must be tagged the same way: all implicitly tagged or all carrying the same explicit tag.
(e) If a hub is connected to an access link, then the frames sent from all the stations connected to the hub must be untagged

5.11. Which of the following tagging rules for a “trunk link” are correct ?
(a) All frames traversing a trunk link must be tagged.
(b) All frames traversing a trunk link must be untagged.
(c) There can be a mix of implicitly and explicit tagged frames in a trunk link but they must be for different VLANs.
(d) For each VLAN, all frames traversing a trunk link must be tagged the same way: all implicitly tagged or all carrying the same explicit tag.
(e) A frame traversing a trunk link will be tagged or untagged depends on which VLAN the frame came from.

5.12. Which of the following tagging rules for a “hybrid link” are correct ?
(a) For each VLAN, all frames traversing a particular hybrid link can be tagged in different ways.
(b) For each VLAN, all frames traversing a particular hybrid link must be tagged the same way: all implicitly tagged or all carrying the same explicit tag.
(c) There can be a mix of implicitly and explicit tagged frames but they must be for different VLANs.
(d) All the frames must be tagged explicitly.
(e) A frame traversing a particular hybrid will be tagged or untagged depends on which VLAN the frame came from.


VLAN-6 https://www.youtube.com/watch?v=9cOOd5OtpMA

5.13 Consider the following VLAN configuration. Assume that all stations are VLAN unaware. Which of the following statements are correct ?

(a) All frames of VLAN A and VLAN B will be tagged when traversing the hybrid link.
(b) All frames of VLAN A, VLAN B and VLAN C will be tagged when traversing the hybrid link.
(c) All frames of VLAN C will be untagged when traversing the hybrid link.
(d) All frames of VLAN B and VLAN C will be untagged when traversing the hybrid link.
(e) All frames of VLAN C will be tagged when traversing the hybrid link.



5.14 Which of the following statements about the relationship between VLAN and spanning tree are correct ?
(a) The set of paths to connect the members of a VLAN is a subset of the spanning tree of the bridged LAN.
(b) The set of paths to connect the members a VLAN always is identical to the spanning tree of the bridged LAN.
(c) The set of paths to connect the members of a VLAN is fixed.
(d) The set of paths to connect the members of a VLAN is dynamic.
(e) The set of paths to connect the members of different VLANs may be different.

VLAN-7 https://www.youtube.com/watch?v=EyJw9a5AlDk

5.15 Which of the following statements about the bridge operation of VLAN are correct ?
(a) A bridge filters frames to ensure that traffic destined for a given VLAN is forwarded only on ports that form a path to members of that VLAN.
(b) A bridge will forward frames to all the ports to ensure that traffic destined for a given VLAN will be forwarded successfully.
(c) A frame will be forwarded along the spanning tree to all bridges to ensure that traffic destined for a given VLAN will be forwarded successfully.


5.16 Consider the following VLAN configuration. For switch 1, what are the “member set” and “untagged set” of each VLAN ? please answer the port “number” for each of the following questions



SVL: Share VLAN Learning
IVL: Independent VLAN Learning


5.17 What is the meaning of Shared VLAN Learning (SVL) ?
(a) Some of the VLANs construct a common filtering database and the learned MAC addresses are shared.
(b) Each VLAN constructs an individual filtering database and the learned MAC addresses are not shared
(c) All the VLANs construct a common filtering database and the learned MAC addresses are shared.
(d) Only one VLAN constructs a filtering database and the learned MAC addresses are shared to all other VLANs.
(e) All the VLANs construct a common filtering database but the learned MAC addresses are only shared to some VLANs.

5.18 What is the meaning of Independent VLAN Learning (IVL) ?
(a) Some of the VLANs construct a common filtering database and the learned MAC addresses are shared.
(b) Each VLAN constructs an individual filtering database and the learned MAC addresses are not shared
(c) Each VLAN constructs an individual filtering database but the learned MAC addresses are only shared to some VLANs
(d) All the VLANs construct a common filtering database and the learned MAC addresses are shared.
(e) Only one VLAN constructs a filtering database and the learned MAC addresses are shared to all other VLANs.


VLAN-9 https://www.youtube.com/watch?v=kJOXTDlR67A

VLAN Database的種類:Static and Dynamic

VLAN-10 https://www.youtube.com/watch?v=Ns6QBppslDI
VLAN Tag Structure
SNAP-encoded TPID(8 bytes) and TCI (2 bytes)
Ethernet-encoded TPID(2 bytes) and TCI (2 bytes)

5.19 Which of the following fields are included in a VLAN tag structure ?
(a) Tag Protocol Identifier (TPID)
(b) Tag Control Information (TCI)
(c) Tag Flag
(d) Tag Checksum
(e) Tag Encryption
5.20 Which of the following value is correct for Ethernet-encoded Tag Protocol Identifier (TPID) ?
(a) 80-00
(b) 81-00
(c) 82-00
(d) 83-00
(e) 84-00
5.21 How long is the SNAP-encoded Tag Protocol Identifier (TPID) ?
(a) 2 bytes
(b) 4 bytes
(c) 6 bytes
(d) 8 bytes
(e) 10 bytes
5.22 Which of the following fields are included in the Tag Control Information (TCI) of a VLAN tag ?
(a) User-Priority (3 bits)
(b) User-priority (4 bits)
(c) Canonical Format Indicator (1 bit)
(d) VLAN ID (12 bits)
(e) VLAN ID (10 bits)
5.23 What is the maximum number of VLANs allowed in a bridged LAN ?
(a) 512
(b) 1024
(c) 2048
(d) 4096
(e) 8192

清華大學 計算機網路 第6週課程 Reliable Transmission

Reliable Transmission1 https://www.youtube.com/watch?v=Hru_HipCnnU


6.1. Which of the following mechanisms are usually used to provide reliable transmission ?
(a) Acknowledgements
(b) Beacon
(c) Timeouts
(d) Polling
(e) Fragmentation


6.2. Which of the following statements are correct about the “Acknowledgement” in the reliable transmission ?
(a) The receipt of an acknowledgement indicates to the sender that its frame was not successfully delivered
(b) The receipt of an acknowledgement indicates to the sender that its frame was successfully delivered
(c) When the sender receives an acknowledgement of its frame, it will transmit the frame again to make sure the frame is delivered successfully.
(d) If a sender does not receive an acknowledgment after a reasonable amount of time, then the sender retransmits the original frame
(e) The receiver sends an acknowledgement back to the sender when a frame is received correctly


6.3. The general strategy of using acknowledgements and timeouts to implement reliable delivery is sometimes called
(a) Address Resolution Protocol (ARP).
(b) Automatic Repeat reQuest (ARQ)
(c) Automatic Acknowledgement Repeat Protocol
(d) Sliding Window Protocol
(e) Native Acknowledgement Protocol (NAK)

Reliable Transmission2 https://www.youtube.com/watch?v=QiTntfLER8I

6.4. Which of the following statements are correct for “stop-and-wait” protocol ?
(a) After transmitting one frame, the sender waits for an acknowledgement before transmitting the next frame.
(b) After transmitting one frame, the sender can still transmit one more frame before an acknowledgement is received.
(c) If the acknowledgement does not arrive after a certain period of time, the sender times out and retransmits the original frame
(d) The only reason the sender times out is that the acknowledgement is lost.
(e) The receiver may receive duplicate copies of a frame.


6.5. Which of the following cases may cause a sender to “timeout” in the “stop-and-wait” protocol ?
(a) The transmitted frame is lost.
(b) The transmitted frame is delayed.
(c) The acknowledgement is delayed
(d) The acknowledgement is lost.
(e) The transmitted frame is received with error.


6.6. Which of the following statements are correct for using “stop-and-wait” protocol” with 1-bit sequence number of “0” and “1”?
(a) When a sender transmits frame 0, before receiving the ACK 0, the sender can transmit frame 1 to speedup the transmission.
(b) When a sender transmits frame 0, it will transmit frame 1 after the ACK 0 received.
(c) When the sender retransmits frame 0, the receiver can determine that this is a second copy of frame 0 and therefore can ignore it.
(d) When the sender retransmits frame 1, the receiver can determine that this is a second copy of frame 1 and therefore can ignore it.
(e) When a second copy of frame is received, the receiver will discard the duplicated frame and therefore no need to send back an acknowledgement for this frame.


6.7. In the “stop-and-wait” protocol, at most how many frames can be transmitted simultaneously on the link by the sender ?
(a) 1
(b) 2
(c) 3
(d) 4
(e) 5


6.8. Consider a link of 2 Mbps with an RTT of 40 ms. Assume that the frame size is of 1 KBytes. What is the maximum sending rate (kbps) of the sender if the “stop-and-wait” protocol is used ?
____200____(kbps)


6.9. Consider a link of 4 Mbps with an RTT of 20 ms. Assume that the frame size is of 2 KBytes. What is the maximum sending rate (kbps) of the sender if the “stop-and-wait” protocol is used ?
____800___(kbps)
送出檢查 顯示答案


6.10. Consider a link of 2 Mbps with an RTT of 40 ms. Assume that the frame size is of 2 KBytes. To fully use the link, the sender should transmit up to _____?_____ frames before having to wait for an ACK ?
_____5_____ frames
送出檢查 顯示答案

Reliable Transmission3 https://www.youtube.com/watch?v=JtUPY6a0FfE




6.11. In the sliding window protocol, the sender assigns a sequence number (denoted as SeqNum) to each frame and also maintains three variables: Sending Window Size (SWS): Upper bound on the number of outstanding (unacknowledged) frames that the sender can transmit; Last Acknowledgement Received (LAR): Sequence number of the last acknowledgement received, and Last Frame Sent (LFS): Sequence number of the last frame sent.
Which of the following relationship is correct for these three variables ?

(a) LFS – LAR ≤ SWS
(b) LFS – LAR > SWS
(c) LFS – SWS ≤ LAR
(d) LAR + SWS ≤ LFS
(e) LFS – SWS > LAR

6.12. Consider the three variables defined in question 6.11. Which of the following conditions are right timing for the sender to slide its window ?
(a) When the acknowledgement of any frame within the sliding window is received
(b) When the acknowledgement of LAR+1 is received
(c) When the acknowledgement of LAR+SWS is received
(d) When the acknowledgement of LAR+2 is received
(e) When the acknowledgement of LAR+SWS-1 is received

6.13. Consider the three variables defined in question 6.11. When the sender sliding its window, at most how many sequence numbers can be shifted by the window ?
(a) 1
(b) 2
(c) SWS
(d) SWS-1
(e) SWS+1

Reliable Transmission4-5 https://www.youtube.com/watch?v=AE17ze4Tlo8

6.14. In the sliding window protocol, the receiver maintains three variables: Receiving Window Size (RWS): Upper bound on the number of out-of-order frames that the receiver is willing to accept; Largest Acceptable Frame (LAF): Sequence number of the largest acceptable frame, and Last Frame Received (LFR): Sequence number of the last frame received.
Which of the following relationship is correct for these three variables ?


(a) LAF –LFR > RWS
(b) LAF – LFR ≤ RWS
(c) LAF – RWS ≤ LFR
(d) LFR + RWS ≤ LAF
(e) LAF – RWS > LFR


6.15. Consider the three variables defined in question 6.14. Which of the following conditions are right timing for the receiver to slide its window ?
(a) When a frame with sequence number within the sliding window is received
(b) When a frame with sequence number of LFR+1 is received
(c) When a frame with sequence number of LFR +RWS - 1 is received
(d) When a frame with sequence number of LFR +RWS is received
(e) When a frame with sequence number LFR +RWS +1 is received

6.16. Consider the three variables defined in question 6.14. When the receiver sliding its window, at most how many sequence numbers can be shifted by the window ?
(a) 1
(b) 2
(c) RWS-1
(d) RWS
(e) RWS+1


6.17. Consider the three variables defined in question 6.14. Which of the following statements are correct when the receiver receives a frame with sequence number N ?
(a) The receiver will discard the frame if N ≤ LFR.
(b) The receiver will discard the frame if or N > LAF.
(c) The receiver will accept the frame if N = LAF + 1
(d) The receiver will accept the frame if N = LFR
(e) The receiver will accept the frame if LFR < N ≤ LAF

Reliable Transmission6 https://www.youtube.com/watch?v=4GBeC0G-83w

6.18 Let SeqNumToAck denote the largest sequence number not yet acknowledged, such that all frames with sequence number less than SeqNumToAck have been received. Which of the following statements are correct for the “cumulative acknowledgement” ?
(a) The receiver acknowledges SeqNumToAck to sender if a frame with sequence number of SeqNumToAck + k, k > 0, is received.
(b) The receiver acknowledges SeqNumToAck+k to sender if a frame with sequence number of SeqNumToAck + k, k > 0, is received.
(c) The receiver then sets LFR = SeqNumToAck - 1 and LAF = LFR + RWS.
(d) The receiver then sets LFR = SeqNumToAck and LAF = LFR + RWS.
(e) The receiver then sets LFR = SeqNumToAck + 1 and LAF = LFR + RWS-1.


6.19 Consider the following communication sequence between sender and receiver. Assume the “cumulative acknowledgement” scheme is used and the frame with sequence number of 2 is lost. The lost frame is retransmitted again when the timer timeouts. Then what is the sequence number to acknowledge for the following ACKs ?



a = 2
b = 2
c = 2
d = 2
e = 7


6.20 Which of the following statements are correct for determining the “window size” of a sliding window protocol ?
(a) The SWS is usually determined based on the bandwidth x delay between the sender and the receiver.
(b) The SWS is usually determined based on the RTT between the sender and the receiver.
(c) RWS = 1 is not allowed.
(d) RWS = SWS is allowed
(e) RWS = SWS/2 is the best selection.


Reliable Transmission8 https://www.youtube.com/watch?v=SpQnWVJWoY8


6.21 In order to distinguish between different frames of the same sequence number, the number of possible sequence numbers must be larger than the number of allowed outstanding frames. Let MaxSeqNum be the number of total available sequence numbers. In case of SWS + 1 ≤ MaxSeqNum, which of the following statements are correct ?
(a) It is sufficient to distinguish between different frames of the same sequence number.
(b) It is NOT sufficient to distinguish between different frames of the same sequence number.
(c) If RWS = 1 then it is sufficient to distinguish between different frames of the same sequence number.
(d) If RWS = SWS then it is NOT sufficient to distinguish between different frames of the same sequence number.
(e) If RWS = SWS then it is sufficient to distinguish between different frames of the same sequence number.

Reliable Transmission9-10 https://www.youtube.com/watch?v=Rd_FztzSap8


6.22 Consider an example that we have eight available sequence numbers: 0, 1, 2, 3, 4, 5, 6, and 7. Assume that RWS = SWS = 7. Now, we have the following steps:
Step 1. Sender sends frames 0, 1, …, 6
Step 2. Receiver receives frames 0, 1, … ,6, and acknowledges 0, 1, …, 6.
Step 3. All ACKs (0, 1, …, 6) are lost
Step 4. Sender finally timeouts and retransmits frames 0, 1, …, 6
Then, how many frames retransmitted in Step 4 will be accepted by receiver ? 6
How many frames retransmitted in Step 4 will be discarded by receiver ?  1


6.23 Consider an example that we have eight available sequence numbers: 0, 1, 2, 3, 4, 5, 6, and 7. Assume that RWS = SWS = 5. Now, we have the following steps:
Step 1. Sender sends frames 0, 1, …, 4
Step 2. Receiver receives frames 0, 1, … ,4, and acknowledges 0, 1, …, 4.
Step 3. All ACKs (0, 1, …, 4) are lost
Step 4. Sender finally timeouts and retransmits frames 0, 1, …,4
Then, how many frames retransmitted in Step 4 will be accepted by receiver ? 2
How many frames retransmitted in Step 4 will be discarded by receiver ?  3


6.24 Consider an example that we have eight available sequence numbers: 0, 1, 2, 3, 4, 5, 6, and 7. Assume that RWS = SWS = 4. Now, we have the following steps:
Step 1. Sender sends frames 0, 1, 2,3
Step 2. Receiver receives frames 0, 1, 2, 3 and acknowledges 0, 1, 2,3.
Step 3. All ACKs (0, 1, 2, 3) are lost
Step 4. Sender finally timeouts and retransmits frames 0, 1, 2, 3
Then, how many frames retransmitted in Step 4 will be accepted by receiver ? 
How many frames retransmitted in Step 4 will be discarded by receiver ?  4


6.25 Let MaxSeqNum be the total number of available sequence numbers. Assume RWS = SWS, then which of the following relationship is sufficient to distinguish between different frames of the same sequence number ?
(a) TSWS + 1 ≤ MaxSeqNum
(b) SWS ≤ (MaxSeqNum+1)/2
(c) SWS < (MaxSeqNum+1)/2
(d) SWS < MaxSeqNum x 2
(e) SWS = (MaxSeqNum+1)/2


6.26 Consider an example that we have seven available sequence numbers: 0, 1, 2, 3, 4, 5, and 6. Assume that RWS = SWS = 4. Now, we have the following steps:
Step 1. Sender sends frames 0, 1, 2, 3
Step 2. Receiver receives frames 0, 1, 2, 3 and acknowledges 0, 1, 2, 3.
Step 3. All ACKs (0, 1, 2, 3) are lost
Step 4. Sender finally timeouts and retransmits frames 0, 1, 2, 3
Then, how many frames retransmitted in Step 4 will be accepted by receiver ? 1
How many frames retransmitted in Step 4 will be discarded by receiver ?  3


6.27 Which of the following are the major features of the sliding window protocol ?
(a) unreliable transmission
(b) reliable transmission
(c) The frame order can be preserved.
(d) The frame order can not be preserved
(e) The receiver can do flow control by setting the value of RWS