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

Android 入門:查詢 SQLite 並把資料顯示到畫面上

編輯:關於 Android 程式設計

這是資料庫部分最基礎的一道練習:把 SQLite 裡的內容撈出來,逐條顯示在手機螢幕上。整個流程可以拆成三步——寫版面、準備資料類與資料庫 Helper、最後在 Activity 中查詢並渲染。

一、版面配置

布局非常樸素:外層一個可捲動的 ScrollView,內層放一個空的線性版面,稍後用程式動態塞入子 View。

<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity" />
</ScrollView>

二、定義資料模型

為了取值方便,先宣告一個 Person 類,把要查詢的四個欄位(id、姓名、薪水、電話)包起來,並重寫 toString(),這樣稍後直接交給 TextView 顯示即可。

package com.neusoft.show.domal;

public class Person {
    private String _id;
    private String name;
    private String salary;
    private String phone;

    public Person(String _id, String name, String salary, String phone) {
        super();
        this._id = _id;
        this.name = name;
        this.salary = salary;
        this.phone = phone;
    }

    // 各欄位的 getter / setter 略

    @Override
    public String toString() {
        return _id + "," + name + ", " + salary + ", " + phone;
    }
}

三、建立資料庫 Helper

接著寫一個繼承 SQLiteOpenHelper 的類,負責建庫與建表。資料庫取名 people.db,版本號 1,並在 onCreate() 中建立 person 表。

package com.neusoft.show;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyOpenHelper extends SQLiteOpenHelper {

    public MyOpenHelper(Context context) {
        super(context, "people.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table person(_id integer primary key autoincrement,"
                 + "name char(20),salary char(20),phone char(20))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        System.out.print("數據庫升級了!!!");
    }
}

四、查詢並顯示

最後一步是主流程:取得可寫資料庫、執行 query() 拿到 Cursor,逐列取出欄位並封裝成 Person 放進 List;然後遍歷這個集合,每筆資料 new 一個 TextView,設定文字與字級後掛到線性版面上。

這裡刻意用最原始的 TextView 而非 ListView,先把資料流動的觀念跑通,後續再換成列表控件會更清楚。

package com.neusoft.show;

import java.util.ArrayList;
import java.util.List;

import com.neusoft.show.domal.Person;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

    List<Person> personList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        personList = new ArrayList<Person>();

        // 1. 從資料庫把資料取出來
        MyOpenHelper oh = new MyOpenHelper(this);
        SQLiteDatabase db = oh.getWritableDatabase();
        Cursor cursor = db.query("person", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            String _id     = cursor.getString(cursor.getColumnIndex("_id"));
            String name    = cursor.getString(cursor.getColumnIndex("name"));
            String salary  = cursor.getString(cursor.getColumnIndex("salary"));
            String phone   = cursor.getString(cursor.getColumnIndex("phone"));
            personList.add(new Person(_id, name, salary, phone));
        }

        // 2. 把資料逐條顯示到螢幕上
        LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
        for (Person p : personList) {
            TextView tv = new TextView(this);
            tv.setText(p.toString());
            tv.setTextSize(18);
            ll.addView(tv);
        }
    }
}

整體觀念並不複雜:建表 → 查詢 → 封裝 → 渲染。把這條主線吃透,之後換成 ListView、RecyclerView 或任何適配器,都只是替換最後的呈現方式而已。

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