在Android中使用TableLayout連接數據庫的一般步驟如下:
下面是一個簡單的示例代碼:
// 創建一個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中連接數據庫并顯示數據到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();
}
}
在這個示例中,我們創建了一個包含一個表和兩個字段(id和name)的數據庫,并在MainActivity中將查詢到的name數據顯示到TableLayout中。你可以根據自己的需求和數據庫表結構來修改代碼。