在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中。你可以根据自己的需求和数据库表结构来修改代码。