在Android中,可以使用SQLite數據庫來存儲數據并在應用中獲取數據。以下是一個簡單的示例代碼來獲取數據庫數據:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 創建數據庫表
db.execSQL("CREATE TABLE 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 class DataAccess {
private DatabaseHelper dbHelper;
public DataAccess(Context context) {
dbHelper = new DatabaseHelper(context);
}
public List<String> getData() {
List<String> data = new ArrayList<>();
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM mytable", null);
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
data.add(name);
}
cursor.close();
db.close();
return data;
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataAccess dataAccess = new DataAccess(this);
List<String> data = dataAccess.getData();
for (String name : data) {
Log.d("Database Data", name);
}
}
}
以上代碼演示了如何在Android應用中獲取數據庫數據。首先創建一個SQLiteOpenHelper類來管理數據庫的創建和升級,然后創建一個數據訪問類來操作數據庫,最后在Activity中使用數據訪問類來獲取數據庫數據并展示。