在自定义布局中显示来自BaseAdapter中的所有SQLite数据,可以按照以下步骤进行:
下面是一个示例代码,演示如何在自定义布局中显示来自BaseAdapter中的所有SQLite数据:
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String dropTableQuery = "DROP TABLE IF EXISTS mytable";
db.execSQL(dropTableQuery);
onCreate(db);
}
}
public class MyAdapter extends BaseAdapter {
private Context context;
private List<MyData> dataList;
public MyAdapter(Context context) {
this.context = context;
this.dataList = getDataFromDatabase();
}
private List<MyData> getDataFromDatabase() {
List<MyData> dataList = new ArrayList<>();
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM mytable", null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
MyData data = new MyData(id, name, age);
dataList.add(data);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return dataList;
}
// 实现其他必要的方法...
}
<!-- ListView示例 -->
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- RecyclerView示例 -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
public class MainActivity extends AppCompatActivity {
private ListView listView;
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
recyclerView = findViewById(R.id.recycler_view);
// 使用ListView
MyAdapter adapter = new MyAdapter(this);
listView.setAdapter(adapter);
// 使用RecyclerView
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
}
这样,就可以在自定义布局中显示来自BaseAdapter中的所有SQLite数据了。根据实际需求,可以进一步优化布局和Adapter的设计,以满足不同的显示需求。
领取专属 10元无门槛券
手把手带您无忧上云