在Android中使用TableLayout連接數(shù)據(jù)庫(kù)的一般步驟如下:
下面是一個(gè)簡(jiǎn)單的示例代碼:
// 創(chuàng)建一個(gè)SQLiteOpenHelper類
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY, name TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
public void insertData(String name) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
db.insert("mytable", null, values);
db.close();
}
public Cursor getAllData() {
SQLiteDatabase db = getReadableDatabase();
return db.query("mytable", null, null, null, null, null, null);
}
}
// 在Activity中連接數(shù)據(jù)庫(kù)并顯示數(shù)據(jù)到TableLayout中
public class MainActivity extends AppCompatActivity {
private TableLayout tableLayout;
private MyDatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableLayout = findViewById(R.id.tableLayout);
dbHelper = new MyDatabaseHelper(this);
Cursor cursor = dbHelper.getAllData();
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
TableRow row = new TableRow(this);
TextView textView = new TextView(this);
textView.setText(name);
row.addView(textView);
tableLayout.addView(row);
} while (cursor.moveToNext());
}
cursor.close();
}
}
在這個(gè)示例中,我們創(chuàng)建了一個(gè)包含一個(gè)表和兩個(gè)字段(id和name)的數(shù)據(jù)庫(kù),并在MainActivity中將查詢到的name數(shù)據(jù)顯示到TableLayout中。你可以根據(jù)自己的需求和數(shù)據(jù)庫(kù)表結(jié)構(gòu)來(lái)修改代碼。