数据库的内容显示在listview 数据库的内容分别是title 和 body的代码
时间: 2024-10-21 08:04:46 浏览: 21
NotesApp:学习使用 SQLite 数据库和 CursorAdapters 制作笔记应用程序
在Android开发中,使用ListView展示数据库内容通常涉及两个步骤:首先从数据库获取数据,然后适配到ListView。这里是一个简单的示例,假设我们使用SQLite数据库存储文章标题(title)和正文(body),并且有一个`Article`模型类:
1. 首先,我们需要连接到数据库并执行查询:
```java
// 创建DatabaseHelper类,继承SQLiteOpenHelper
public class DatabaseHelper extends SQLiteOpenHelper {
// ...
public Cursor getArticles() {
String[] projection = { ArticleContract.ArticleEntry._ID,
ArticleContract.ArticleEntry.TITLE,
ArticleContract.ArticleEntry.BODY };
return getWritableDatabase().query(ArticleContract.Entry.TABLE_NAME, projection, null, null, null, null, null);
}
}
// 使用时
DatabaseHelper dbHelper = new DatabaseHelper(context);
Cursor cursor = dbHelper.getArticles();
```
2. 然后遍历查询结果并将数据绑定到Adapter:
```java
// 假设你已经创建了ArticleAdapter,继承自BaseAdapter
class ArticleAdapter extends ArrayAdapter<Article> {
private Context context;
private List<Article> articles;
public ArticleAdapter(Context context, List<Article> articles) {
super(context, R.layout.list_item_article, articles);
this.context = context;
this.articles = articles;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_article, parent, false);
}
Article article = getItem(position);
TextView titleTextView = convertView.findViewById(R.id.title_text_view);
titleTextView.setText(article.getTitle());
TextView bodyTextView = convertView.findViewById(R.id.body_text_view);
bodyTextView.setText(article.getBody());
return convertView;
}
}
// 获取所有数据,并设置适配器
List<Article> fetchedArticles = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Article article = new Article(cursor.getInt(0), cursor.getString(1), cursor.getString(2));
fetchedArticles.add(article);
cursor.moveToNext();
}
ArticleAdapter adapter = new ArticleAdapter(context, fetchedArticles);
listView.setAdapter(adapter);
```
阅读全文