Android Studio | 連線MySQL取得資料

Kombayar
2 min readMay 16, 2020
若能成功連線資料庫將資料顯示於網頁上時。

1. 開啟Android Studio 建立新專案,引用套件包。

我們會使用到 Apache 的 HTTP 套件,所以要先引用套件包,打開Build.gradle 在 android 部分加入 useLibrary ‘org.apache.http.legacy’ 進行引用。

引用完畢,要重新同步這個專案,按下 sync now ,等待專案同步完成。

打開 Build.gradle
在 android 部分加入紅色區塊進行引用。

2. 開啟網路應用權限

我們要開啟專案使用網路的權限,所以要開啟網路權限的許可,打開 AndroidManifest.xml 在 <application 上方加上 <uses-permission android:name=”android.permission.INTERNET” />

打開 AndroidManifest.xml
在 application 前面加上紅色框框許可網路權限。

3. 宣告按鈕物件,與按下後呼叫方法。

完成前兩個步驟,回到 java 主程式開始選寫程式。

宣告按鈕物件。
按下後所呼叫的方法在下一步說明。

4. 建立執行緒取得網路資料。

因為 android 本身限制,和網路連線的部分必須要使用另外的執行緒,不能干涉到主程式,因為如果使用者等待連線網路結果太久,會將整個系統卡死無法往下運作,所以我們要先宣告一個執行緒。

執行緒的事件部分,要先宣告和 HTTP 有關函式庫和物件 (為下圖黃色區塊部分),接著利用這些物件連到我們的伺服器上的網頁,最後將網頁上的資料抓回來 android 應用(為下圖藍色區塊部分)

若要顯示全部的資料,可以更改[讀取JSON物件]的橘色框內程式。

下為上圖程式碼:

private Runnable mutiThread = new Runnable() {
@Override
public void run() {
try {
URL url = new URL("http://10.0.2.2/GetData.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();

int responseCode = connection.getResponseCode();

if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
String line = null;
while ((line = bufferedReader.readLine()) != null){
JSONArray dataJson = new JSONArray(line);
int i = dataJson.length()-1;
JSONObject info = dataJson.getJSONObject(i);
String time = info.getString("time");
String dB = info.getString("dB");
result1 = time.toString();
result2 = dB.toString();
}
inputStream.close();
}
} catch (Exception e){
result1 = e.toString();
result2 = e.toString();
}

runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(result1);
textView1.setText(result2);
}
});

5. 完成,執行程式。

讀取到的資料。

這裡有將讀取到的資料做整理並顯示最後一筆資料的time於result1、dB顯示於result2。

顯示最後一筆讀到的資料。

Thank all!

--

--

Kombayar

I’m a graduate student. Self-teaching coding on Internet, wanted to write some articles to make myself remember the code.