編輯:關於 Android 程式設計
本篇彙集了多個 Android 開發中常見且實用的小案例,涵蓋 SQLite 資料庫操作、ListView 與各種 Adapter 的使用,以及網路請求、圖片下載與快取等主題,適合初學者動手練習。
先自訂一個 OpenHelper 類,負責資料庫的建立與版本升級:
public class MyOpenHelper extends SQLiteOpenHelper {
public MyOpenHelper(Context context) {
// 原本有四個參數,此處固定其餘參數只保留 context
// arg1:資料庫檔名
// arg2:游標工廠,游標等同結果集,傳 null 使用預設工廠
// arg3:版本號,不能小於 1,用於升級
super(context, "people.db", null, 1);
}
// 建立資料庫時呼叫
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table person(_id integer primary key autoincrement, name char(10), phone char(20), salary integer(10))");
}
// 升級資料庫時呼叫
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("資料庫升級");
}
}
在測試類中即可進行增刪改查與事務操作:
public class Test extends AndroidTestCase {
private MyOpenHelper oh;
private SQLiteDatabase db;
// 測試方法執行前呼叫
@Override
protected void setUp() throws Exception {
super.setUp();
oh = new MyOpenHelper(getContext());
db = oh.getWritableDatabase();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
db.close();
}
public void insert() {
db.execSQL("insert into person(name, phone, salary) values (?, ?, ?)", new Object[]{"一", "138438", 13000});
db.execSQL("insert into person(name, phone, salary) values (?, ?, ?)", new Object[]{"二", "138438", 13000});
}
public void delete() {
db.execSQL("delete from person where name = ?", new Object[]{"一"});
}
public void update() {
db.execSQL("update person set salary = ? where name = ?", new Object[]{13200, "一"});
}
public void select() {
Cursor cursor = db.rawQuery("select * from person", null);
// 把指標移動至下一行
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
String phone = cursor.getString(cursor.getColumnIndex("phone"));
int salary = cursor.getInt(cursor.getColumnIndex("salary"));
System.out.println(name + ";" + phone + ";" + salary);
}
}
public void insertApi() {
ContentValues values = new ContentValues();
values.put("name", "楊松");
values.put("phone", "1388888");
values.put("salary", "13201");
// 回傳值為 -1 代表插入失敗
long l = db.insert("person", null, values);
System.out.println(l);
}
public void transaction() {
try {
// 開啟事務
db.beginTransaction();
ContentValues values = new ContentValues();
values.put("salary", 13199);
db.update("person", values, "name = ?", new String[]{"二二"});
values.clear();
values.put("salary", 13202);
db.update("person", values, "name = ?", new String[]{"一"});
// 設定事務成功,若中途拋出例外則會回滾
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 關閉事務並提交
db.endTransaction();
}
}
}
從資料庫取出資料後,透過自訂 BaseAdapter 綁定到 ListView:
personList = new ArrayList(); MyOpenHelper oh = new MyOpenHelper(this); SQLiteDatabase db = oh.getWritableDatabase(); Cursor cursor = db.query("person", null, null, null, null, null, null, null); while (cursor.moveToNext()) { String name = cursor.getString(1); String phone = cursor.getString(2); int salary = cursor.getInt(3); personList.add(new Person(name, phone, salary)); } ListView lv = (ListView) findViewById(R.id.lv); lv.setAdapter(new MyAdapter()); class MyAdapter extends BaseAdapter { // 系統呼叫,用來得知模型層有多少筆資料 @Override public int getCount() { return personList.size(); } // 系統呼叫,回傳的 View 會作為 ListView 的一個條目 // convertView:系統先前快取的條目 @Override public View getView(int position, View convertView, ViewGroup parent) { Person p = personList.get(position); View view; if (convertView == null) { view = View.inflate(MainActivity.this, R.layout.item_listview, null); } else { view = convertView; } // 必須使用 view.findViewById TextView tv_name = (TextView) view.findViewById(R.id.tv_name); tv_name.setText(p.getName()); return view; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } }
對於簡單的資料展示,可直接使用系統提供的 Adapter:
String[] objects = new String[]{ "一", "二", "三" };
ListView lv = (ListView) findViewById(R.id.lv);
// lv.setAdapter(new ArrayAdapter(this, R.layout.item_listview, R.id.tv, objects));
// 把每個條目需要的所有資料封裝至 map,再把 map 裝入 list
List
使用 HttpURLConnection 發送 GET 請求並解碼為圖片:
public void click(View v) {
String path = "https://169.254.244.136:8080/dd.jpg";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.connect();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bm);
} else {
Toast.makeText(this, "請求失敗", 0).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
由於網路請求必須在子執行緒中進行,而 UI 更新又必須回到主執行緒,因此需借助 Handler:
Handler handler = new Handler() {
// 只要消息佇列有消息,此方法便會在主執行緒執行
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap((Bitmap) msg.obj);
break;
case 2:
Toast.makeText(MainActivity.this, "請求失敗", 0).show();
break;
}
}
};
public void click(View v) {
Thread t = new Thread() {
@Override
public void run() {
String path = "https://169.254.244.136:8080/dd.jpg";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.connect();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);
// 子執行緒需要刷新 UI 時,只需發送一條消息至佇列
Message msg = new Message();
msg.obj = bm;
msg.what = 1;
handler.sendMessage(msg);
} else {
handler.sendEmptyMessage(2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
先檢查本地快取是否存在,命中則直接讀取,否則再從網路下載並寫入快取:
public void click(View v) {
final String path = "https://169.254.244.136:8080/dd.jpg";
final File file = new File(getCacheDir(), getNameFromPath(path));
if (file.exists()) {
System.out.println("從快取獲取");
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg = new Message();
msg.obj = bm;
msg.what = 1;
handler.sendMessage(msg);
} else {
Thread t = new Thread() {
@Override
public void run() {
System.out.println("從網路獲取");
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
// 讀一段就寫一段到本地檔案
byte[] b = new byte[1024];
int len;
FileOutputStream fos = new FileOutputStream(file);
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
}
fos.close();
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
Message msg = new Message();
msg.obj = bm;
msg.what = 1;
handler.sendMessage(msg);
} else {
handler.sendEmptyMessage(2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}
public String getNameFromPath(String path) {
int index = path.lastIndexOf("/");
return path.substring(index + 1);
}
若引入 SmartImageView,一行即可載入網路圖片:
public void click(View v) {
SmartImageView siv = (SmartImageView) findViewById(R.id.siv);
siv.setImageUrl("https://169.254.244.136:8080/dd.jpg");
}
先準備一個讀流的工具類:
public class Tools {
public static String getTextFromStream(InputStream is) {
byte[] b = new byte[1024];
int len;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while ((len = is.read(b)) != -1) {
bos.write(b, 0, len);
}
return new String(bos.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
再於子執行緒請求網頁內容,透過 Handler 回主執行緒顯示:
public void click(View v) {
final String path = "https://169.254.244.136:8080/baidu.html";
Thread t = new Thread() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
String text = Tools.getTextFromStream(is);
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
伺服器以 XML 形式提供新聞資料,透過 XmlPullParser 解析後更新 ListView,並以 ViewHolder 模式優化效能:
private void getNewsFromStream(InputStream is) {
XmlPullParser xp = Xml.newPullParser();
try {
xp.setInput(is, "utf-8");
int type = xp.getEventType();
News news = null;
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
if ("newslist".equals(xp.getName())) {
newsList = new ArrayList();
} else if ("news".equals(xp.getName())) {
news = new News();
} else if ("title".equals(xp.getName())) {
news.setTitle(xp.nextText());
} else if ("detail".equals(xp.getName())) {
news.setDetail(xp.nextText());
} else if ("comment".equals(xp.getName())) {
news.setComment(xp.nextText());
} else if ("image".equals(xp.getName())) {
news.setImageUrl(xp.nextText());
}
break;
case XmlPullParser.END_TAG:
if ("news".equals(xp.getName())) {
newsList.add(news);
}
break;
}
type = xp.next();
}
// 通知主執行緒刷新 ListView
handler.sendEmptyMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
}
GET 提交時將參數附加在網址後並進行 URL 編碼:
String path = "https://169.254.244.136/Web2/servlet/Login?name="
+ URLEncoder.encode(name) + "&pass=" + pass;
// 之後以 HttpURLConnection 發送 GET 請求即可
POST 提交則需將資料寫入連線的輸出流:
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String content = "name=" + URLEncoder.encode(name) + "&pass=" + pass;
conn.setRequestProperty("Content-Length", content.length() + "");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(content.getBytes());
GET 請求可透過 DefaultHttpClient 搭配 HttpGet;POST 則用 HttpPost 並以 UrlEncodedFormEntity 封裝參數:
HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(path); Listparameters = new ArrayList (); parameters.add(new BasicNameValuePair("name", name)); parameters.add(new BasicNameValuePair("pass", pass)); post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { InputStream is = response.getEntity().getContent(); String text = Tools.getTextFromStream(is); // 透過 Handler 回傳主執行緒顯示 }
使用 loopj 的 AsyncHttpClient,只需實作回呼即可處理成功與失敗:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("name", name);
rp.put("pass", pass);
client.get(path, rp, new MyHandler());
class MyHandler extends AsyncHttpResponseHandler {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Toast.makeText(MainActivity.this, new String(responseBody), 0).show();
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, "請求失敗", 0).show();
}
}
以上案例串起了 Android 資料持久化、列表展示與網路通訊的關鍵環節,動手實作一遍,能對日常開發有更深入的體會。
Android設計模式之組合模式解析
模式意圖組合模式用於將對象組合成樹形結構,以表示部分與整體的層次關係。它讓客戶端可以一致性地處理單個對象與組合對象。在Android UI體系中,View與ViewGro
Android 如何判斷 App 處於前台還是後台(運行狀態)
本文將以圖文並茂的方式,帶大家一起了解在 Android 中如何判斷 App 的運行狀態,具體內容如下。 要理解這塊知識,先得弄清楚幾個概念:app、process、ta
Win10 UWP 自定義 Marquez 進度條:文字與進度同步移動
在 Win10 UWP 應用中,若想要一個不只是單純長條的進度條,而是搭配文字並讓文字隨進度移動,可以自定義控制項來完成。這種效果常用於遊戲掛機、任務進度或載入提示。
Android 開發筆記:統計分析 SDK 集成指南
用戶畫像 對程序員來說,用戶畫像就是用戶的屬性和行為;通俗地說,用戶畫像包括了個人信息、興趣愛好、日常行為等有血有肉的客戶實體。用戶畫像是精準營銷的產物,企業透過收集用戶