赞
踩
1.ListView在使用Adapter适配器时,在主函数默认加载静态的数据,如果想用点击事件来增加数据行将无显示,下面我们用一个点击事件举例
代码演示
- b_1.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- StuDBHelper helper=new StuDBHelper(MainActivity.this,"stu_db",null,1);
- SQLiteDatabase db=helper.getReadableDatabase();
- Cursor cursor=db.query("stu_table",new String[]
- {"id","sname","date"},null,null,null,null,null);
- while (cursor.moveToNext()) {
- String name = cursor.getString(cursor.getColumnIndex("sname"));
- String time= cursor.getString(cursor.getColumnIndex("date"));
- PanDuan panDuan=new PanDuan(name,time);
- list.add(panDuan);
- }
- db.close();
- }
- });
效果演示
这里我们点击按钮,listview没有子布局出现
2.这时我们可以在Adapter写一个方法
- public class Adapter extends ArrayAdapter {
- private int Getid;
- private Holder holder;
- private List<PanDuan> list; //这个是重点,一定要设置个List成员变量
- public Adapter(@NonNull Context context, int resource, @NonNull List<PanDuan> objects) {
- super(context, resource, objects);
- Getid=resource;
- list=objects; //获取到MainActivity的list子布局内容
- }
-
-
- public void add(PanDuan panDuan){
- list.add(panDuan);
- notifyDataSetChanged(); //动态刷新listview列表
- }
3.定义一个泛型获取sqllite数据库的中转站
- public class PanDuan {
- String value;
- String valuetime;
- public PanDuan(String value,String valuetime){
- this.value=value;
- this.valuetime=valuetime;
-
- }
- public String getString(){
- return value;
- }
- public String getStringtime(){
- return valuetime;
- }
- }
4.在主函数中的点击事件调用add方法
- list_1.setAdapter(adapter);
- StuDBHelper helper=new StuDBHelper(MainActivity.this,"stu_db",null,1);
- SQLiteDatabase db=helper.getReadableDatabase();
- db=helper.getWritableDatabase();
- String sql="insert into stu_table(id,sname) values(1,'张三')";
- db.execSQL(sql);
- b_1.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- StuDBHelper helper=new StuDBHelper(MainActivity.this,"stu_db",null,1);
- SQLiteDatabase db=helper.getReadableDatabase();
- Cursor cursor=db.query("stu_table",new String[]{"id","sname","date"},null,null,null,null,null);
- while (cursor.moveToNext()) {
- String name = cursor.getString(cursor.getColumnIndex("sname"));
- String time= cursor.getString(cursor.getColumnIndex("date"));
- PanDuan panDuan=new PanDuan(name,time);
- adapter.add(panDuan);
- }
- db.close();
- }
- });
-
- }
效果演示(此时我们可以动态获取到sqllite值)
52c58a44be46cb7b2e1a4ef3d
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。