Android:使用 SimpleCursorAdapter 从数据库获取数据到 ListView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12077955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: Using SimpleCursorAdapter to get Data from Database to ListView
提问by NiPfi
I am programming an android app that should use a database to store data and read from it. Using this tutorial (on archive.org)I got the app to create a database and I'm able to create new entries, however, I don't know, how to read the database to get the stored data in a ListView. I know there are many similar questions on this website but it seems none of them apply to the way, the database from the tutorial works.
我正在编写一个 android 应用程序,它应该使用数据库来存储数据并从中读取数据。使用本教程(在archive.org 上),我使用该应用程序创建了一个数据库,并且能够创建新条目,但是,我不知道如何读取数据库以获取 ListView 中存储的数据。我知道这个网站上有很多类似的问题,但似乎没有一个适用于教程中的数据库工作方式。
Code:
代码:
import java.util.Calendar;
import maturarbeit.nicola_pfister.studenttools.database.DBAdapter;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
public class Marks extends ListActivity {
DBAdapter db = new DBAdapter(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marks);
}
@Override
protected void onPause() {
super.onPause();
db.close();
}
@Override
protected void onResume() {
super.onResume();
db.open();
getData();
}
@SuppressWarnings("deprecation")
private void getData() {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
db.getAllMarks(),
new String[] { "value" },
new int[] { android.R.id.text1 });
ListView listView = (ListView) findViewById(R.id.marks_list);
listView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.marks, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
final String date = day + "." + month;
Builder builder = new Builder(this);
builder
.setTitle(R.string.dialog_addmarks)
.setItems(R.array.markslist, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
@SuppressWarnings("unused")
long id;
String selection = getResources().getStringArray(R.array.markslist)[which];
id = db.insertMark(date, "Default", selection);
}
})
.show();
getData();
break;
case R.id.menu_delete:
//Deleting function yet to be implemented.
break;
}
return super.onOptionsItemSelected(item);
}
}
Edit: The ListView ID was wrong since it had to be android:list.
编辑:ListView ID 是错误的,因为它必须是 android:list。
回答by Sam
Using the database format in the tutorial that you linked to, every row has an _id
, isbn
, title
, and publisher
. Now let's assume that you want to display every title in a ListView:
在本教程中使用的数据库格式,您链接到,每一行有_id
,isbn
,title
,和publisher
。现在让我们假设您想在 ListView 中显示每个标题:
db = new DBAdapter(this);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
db.getAllTitles(),
new String[] { "title" },
new int[] { android.R.id.text1 });
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
(You don't need to loop through the Cursor yourself, an adapter does this work for you!)
(您不需要自己遍历 Cursor,适配器会为您完成这项工作!)
The last two parameters in your SimpleCursorAdapter constructor are what you are missing. They are the "from" and "to" parameters:
您缺少 SimpleCursorAdapter 构造函数中的最后两个参数。它们是“from”和“to”参数:
- We want to get the name of each book which is stored in the column name
title
, this is where we get the information "from". - Next we need to tell it where "to" go:
android.R.id.text1
is a TextView in theandroid.R.layout.simple_list_item_1
layout. (You can dig through your SDK and see the simple_list_item_1.xml file yourself or just trust me for the moment.)
- 我们想要获取存储在列 name 中的每本书的名称
title
,这是我们“从”获取信息的地方。 - 接下来我们需要告诉它“去”哪里:
android.R.id.text1
是android.R.layout.simple_list_item_1
布局中的 TextView 。(您可以深入研究您的 SDK 并自己查看 simple_list_item_1.xml 文件,或者暂时相信我。)
Now both the "from" and "to" parameters are arrays because we can pass more than one column of information, try this adapter as well:
现在“from”和“to”参数都是数组,因为我们可以传递不止一列信息,也试试这个适配器:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
db.getAllTitles(),
new String[] { "title", "publisher" },
new int[] { android.R.id.text1, android.R.id.text2 });
With this adapter the books in their database will displayed by title, then publisher. All we had to do is use a layout android.R.layout.simple_list_item_2
that takes two fields and define which columns go to which TextViews.
使用此适配器,他们数据库中的书籍将按书名显示,然后是出版商。我们所要做的就是使用一个带有android.R.layout.simple_list_item_2
两个字段的布局,并定义哪些列转到哪些 TextView。
I hope that helps a little. There's plenty more to learn but maybe this will give you some basics.
我希望这会有所帮助。还有很多东西要学,但也许这会给你一些基础知识。
Last Comment
最后评论
Off the top of my head, to refresh the ListView after adding new data try this:
在我头顶上,在添加新数据后刷新 ListView 试试这个:
public void onClick(DialogInterface dialog, int which) {
String selection = getResources().getStringArray(R.array.markslist)[which];
db.insertMark(date, "Default", selection);
cursor.requery();
adapter.notifyDataSetChanged();
}
You'll have to define adapter
and create a variable for cursor
but that's simple:
您必须定义adapter
并创建一个变量,cursor
但这很简单:
public class Marks extends ListActivity {
SimpleCursorAdapter adapter;
Cursor cursor;
DBAdapter db = new DBAdapter(this);
...
And change getData() accordingly:
并相应地更改 getData():
private void getData() {
cursor = db.getAllMarks();
adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[] { "value" },
new int[] { android.R.id.text1 });
...
}
Good luck!
祝你好运!