Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

安卓實用案例精選(二):SQLite、ListView 與網路請求

編輯:關於 Android 程式設計

本篇彙集了多個 Android 開發中常見且實用的小案例,涵蓋 SQLite 資料庫操作、ListView 與各種 Adapter 的使用,以及網路請求、圖片下載與快取等主題,適合初學者動手練習。

SQLite 資料庫

先自訂一個 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();
        }
    }
}

ListView 的使用

從資料庫取出資料後,透過自訂 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; }
}

ArrayAdapter 與 SimpleAdapter

對於簡單的資料展示,可直接使用系統提供的 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> data = new ArrayList>();
Map map1 = new HashMap();
map1.put("name", "周杰倫");
map1.put("photo", R.drawable.photo1);
data.add(map1);

lv.setAdapter(new SimpleAdapter(this, data, R.layout.item_listview,
        new String[]{"name", "photo"},   // 存放鍵的陣列
        new int[]{R.id.tv, R.id.iv}));   // 存放資源 id 的陣列,兩者以索引對應

網路請求下載圖片

使用 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();
    }
}

子執行緒刷新介面:Handler 的使用

由於網路請求必須在子執行緒中進行,而 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(loopj 工具包)

若引入 SmartImageView,一行即可載入網路圖片:

public void click(View v) {
    SmartImageView siv = (SmartImageView) findViewById(R.id.siv);
    siv.setImageUrl("https://169.254.244.136:8080/dd.jpg");
}

請求 HTML 頁面並顯示其代碼

先準備一個讀流的工具類:

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 與 POST 方式提交表單

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());

使用 HttpClient 提交表單

GET 請求可透過 DefaultHttpClient 搭配 HttpGet;POST 則用 HttpPost 並以 UrlEncodedFormEntity 封裝參數:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(path);
List parameters = 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 回傳主執行緒顯示
}

非同步 HttpClient

使用 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 資料持久化、列表展示與網路通訊的關鍵環節,動手實作一遍,能對日常開發有更深入的體會。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved