从 SQLite 数据库中检索数据并将其显示到 ListView -android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23192217/
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
Retrieving data from SQLite database and display it into ListView -android
提问by danish
I created a database(mydb) with a table(student) in the onCreate function and then entered values dynamically using a button click.Now I want to retrieve all the data from the table student on a button click and display it into listview.
我在 onCreate 函数中创建了一个带有表(student)的数据库(mydb),然后使用按钮单击动态输入值。现在我想通过单击按钮从表 student 中检索所有数据并将其显示到listview 中。
public class MainActivity extends Activity
{
String name, phone;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(dbname VARCHAR, dbphone VARCHAR);");
}
public void btnaddtodb(View v)
{
EditText edtxtname = (EditText)findViewById(R.id.edtxtname);
EditText edtxtphone = (EditText)findViewById(R.id.edtxtphone);
name=edtxtname.getText().toString();
phone=edtxtphone.getText().toString();
db.execSQL("INSERT INTO student values('"+name+"','"+phone+"');");
edtxtname.setText("");
edtxtphone.setText("");
}
}
回答by Lal
Try doing this...It shows all the values in table in a LinearLayout as a list
尝试这样做...它将 LinearLayout 中表格中的所有值显示为列表
try{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
Cursor allrows = mydb.rawQuery("SELECT * FROM "+ TABLE, null);
System.out.println("COUNT : " + allrows.getCount());
Integer cindex = allrows.getColumnIndex("BOOK_DATE");
Integer cindex1 = allrows.getColumnIndex("TRIP_DATE");
Integer cindex2 = allrows.getColumnIndex("LOCATION");
TextView t = new TextView(MybookingsActivity.this);
t.setText("========================================");
//Linear.removeAllViews();
Linear.addView(t);
if(allrows.moveToFirst()){
do{
LinearLayout id_row = new LinearLayout(MybookingsActivity.this);
LinearLayout book_date_row = new LinearLayout(MybookingsActivity.this);
LinearLayout trip_date_row= new LinearLayout(MybookingsActivity.this);
LinearLayout location_row= new LinearLayout(MybookingsActivity.this);
LinearLayout feedback_row= new LinearLayout(MybookingsActivity.this);
final TextView id_ = new TextView(MybookingsActivity.this);
final TextView book_date = new TextView(MybookingsActivity.this);
final TextView trip_date = new TextView(MybookingsActivity.this);
final TextView location = new TextView(MybookingsActivity.this);
final TextView sep = new TextView(MybookingsActivity.this);
final Button feedback = new Button(MybookingsActivity.this);
final String ID = allrows.getString(0);
String BOOK_DATE= allrows.getString(1);
String TRIP_DATE= allrows.getString(2);
String LOCATION= allrows.getString(3);
id_.setTextColor(Color.RED);
id_.setPadding(20, 5, 0, 5);
book_date.setTextColor(Color.RED);
book_date.setPadding(20, 5, 0, 5);
trip_date.setTextColor(Color.RED);
trip_date.setPadding(20, 5, 0, 5);
location.setTextColor(Color.RED);
location.setPadding(20, 5, 0, 5);
System.out.println("BOOK_DATE " + allrows.getString(cindex) + " TRIP_DATE : "+ allrows.getString(cindex1)+ " LOCATION : "+ allrows.getString(cindex2));
System.out.println("ID : "+ ID + " || BOOK_DATE " + BOOK_DATE + "|| TRIP_DATE : "+ TRIP_DATE+ "|| LOCATION : "+LOCATION);
id_.setText("ID : " + ID);
id_row.addView(id_);
Linear.addView(id_row);
book_date.setText("BOOK_DATE : "+BOOK_DATE);
book_date_row.addView(book_date);
Linear.addView(book_date_row);
trip_date.setText("TRIP_DATE : " + TRIP_DATE);
trip_date_row.addView(trip_date);
Linear.addView(trip_date_row);
location.setText("LOCATION : " + LOCATION);
location_row.addView(location);
Linear.addView(location_row);
feedback.setText("Feedback");
feedback.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent(MybookingsActivity.this,FeedbackActivity.class);
intent.putExtra("id", ID);
startActivity(intent);
}
});
feedback_row.addView(feedback);
Linear.addView(feedback_row);
sep.setText("---------------------------------------------------------------");
Linear.addView(sep);
}
while(allrows.moveToNext());
}
mydb.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error encountered."+e.toString(), Toast.LENGTH_LONG).show();
}
Try it..Dont forget to change the dbname,tablename and fielnames..
试试吧..不要忘记更改 dbname、tablename 和 fielnames..
回答by J Jiang
Usually, you can always use the ArrayAdapter
to show something in listview. (there is a good tutorialabout it and many other ones you can find on Internet)
通常,您始终可以使用ArrayAdapter
来在列表视图中显示某些内容。(有一个关于它的很好的教程,您可以在互联网上找到许多其他教程)
For something in db, besides the basic ArrayAdapter
, you can also use CursorAdapter
which has some extra benefits such as dynamic loading and auto refresh.
对于 db 中的某些内容,除了 basic 之外ArrayAdapter
,您还可以使用CursorAdapter
which 具有一些额外的好处,例如动态加载和自动刷新。
To use CursorAdapter
, Let your Activity
implements LoaderCallback<Cursor>
and its required callbacks.
要使用CursorAdapter
,让您的Activity
实现LoaderCallback<Cursor>
及其所需的回调。
Init a CursorAdapter
and set it to the ListView
.
初始化 aCursorAdapter
并将其设置为ListView
.
In the CreateLoader(...)
method, query whatever you need.
在CreateLoader(...)
方法中,查询您需要的任何内容。
Remember to implement the newView
and bindView
properly.
请记住正确实施newView
和bindView
。
A simplest sample may looks like below:
一个最简单的示例可能如下所示:
public class TestActivity extends Activity implements LoaderCallbacks<Cursor>{
ListView listview;
CursorAdapter cursorAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cursorAdapter = new CursorAdapter(this, null) {
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView;
rowView = inflater.inflate(R.layout.device_list_item, parent, false);
bindView(rowView, context, cursor);
return rowView;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView textView = view.findViewById(R.id.text);
textView.setText(cursor.getString(0));
}
};
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return db.query(...);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
cursorAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
回答by J Jiang
USE this tutorial my be it help you.1> Android-sqlite-and-listview-example
使用本教程我会帮助你。1> Android-sqlite-and-listview-example