当前位置:   article > 正文

运用按钮点击事件让list动态获取sqllite数据(Android学习笔记2)_根据点击事件获取动态表格信息

根据点击事件获取动态表格信息
 

1.ListView在使用Adapter适配器时,在主函数默认加载静态的数据,如果想用点击事件来增加数据行将无显示,下面我们用一个点击事件举例

代码演示

  1. b_1.setOnClickListener(new View.OnClickListener() {
  2. @Override
  3. public void onClick(View view) {
  4. StuDBHelper helper=new StuDBHelper(MainActivity.this,"stu_db",null,1);
  5. SQLiteDatabase db=helper.getReadableDatabase();
  6. Cursor cursor=db.query("stu_table",new String[]
  7. {"id","sname","date"},null,null,null,null,null);
  8. while (cursor.moveToNext()) {
  9. String name = cursor.getString(cursor.getColumnIndex("sname"));
  10. String time= cursor.getString(cursor.getColumnIndex("date"));
  11. PanDuan panDuan=new PanDuan(name,time);
  12. list.add(panDuan);
  13. }
  14. db.close();
  15. }
  16. });

效果演示

这里我们点击按钮,listview没有子布局出现

2.这时我们可以在Adapter写一个方法

  1. public class Adapter extends ArrayAdapter {
  2. private int Getid;
  3. private Holder holder;
  4. private List<PanDuan> list; //这个是重点,一定要设置个List成员变量
  5. public Adapter(@NonNull Context context, int resource, @NonNull List<PanDuan> objects) {
  6. super(context, resource, objects);
  7. Getid=resource;
  8. list=objects; //获取到MainActivity的list子布局内容
  9. }
  10. public void add(PanDuan panDuan){
  11. list.add(panDuan);
  12. notifyDataSetChanged(); //动态刷新listview列表
  13. }

3.定义一个泛型获取sqllite数据库的中转站 

  1. public class PanDuan {
  2. String value;
  3. String valuetime;
  4. public PanDuan(String value,String valuetime){
  5. this.value=value;
  6. this.valuetime=valuetime;
  7. }
  8. public String getString(){
  9. return value;
  10. }
  11. public String getStringtime(){
  12. return valuetime;
  13. }
  14. }

4.在主函数中的点击事件调用add方法

  1. list_1.setAdapter(adapter);
  2. StuDBHelper helper=new StuDBHelper(MainActivity.this,"stu_db",null,1);
  3. SQLiteDatabase db=helper.getReadableDatabase();
  4. db=helper.getWritableDatabase();
  5. String sql="insert into stu_table(id,sname) values(1,'张三')";
  6. db.execSQL(sql);
  7. b_1.setOnClickListener(new View.OnClickListener() {
  8. @Override
  9. public void onClick(View view) {
  10. StuDBHelper helper=new StuDBHelper(MainActivity.this,"stu_db",null,1);
  11. SQLiteDatabase db=helper.getReadableDatabase();
  12. Cursor cursor=db.query("stu_table",new String[]{"id","sname","date"},null,null,null,null,null);
  13. while (cursor.moveToNext()) {
  14. String name = cursor.getString(cursor.getColumnIndex("sname"));
  15. String time= cursor.getString(cursor.getColumnIndex("date"));
  16. PanDuan panDuan=new PanDuan(name,time);
  17. adapter.add(panDuan);
  18. }
  19. db.close();
  20. }
  21. });
  22. }

效果演示(此时我们可以动态获取到sqllite值)

52c58a44be46cb7b2e1a4ef3d

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/234261
推荐阅读
相关标签
  

闽ICP备14008679号