Listview和复选框(如何放入数据库(sqlite))

Posted

技术标签:

【中文标题】Listview和复选框(如何放入数据库(sqlite))【英文标题】:Listview and checkbox( how to put in database(sqlite)) 【发布时间】:2012-11-19 16:07:20 【问题描述】:

我是 android 新手,正在开发一个软件,将用户联系人显示为带有复选框的列表视图,如何根据是否选中将复选框数据插入数据库?

在我的数据库类中,我有一个函数用于将名称和数字添加到我的数据库中

createntry(String number,String name) // in my database class

我真的试图找到答案并想出我应该为此使用 getview 功能,但仍然找不到解决方案。

我的 CursorAdapterClass

     public class ContactCursorAdapterCT extends CursorAdapter 
     private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
     private Context context1;
     DataBaseBON dd1= new DataBaseBON(context1);
         public ContactCursorAdapterCT(Context context, Cursor c) 

    super(context, c);
    this.context1 = context;
    for (int i = 0; i < this.getCount(); i++) 
        itemChecked.add(i, false); // initializes all items value with false
    



@Override
public void bindView(View view, Context context, Cursor cursor) 
      TextView name = (TextView)view.findViewById(R.id.contactlistTV1);      
          name.setText(cursor.getString
          (cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
          TextView phone = (TextView)view.findViewById(R.id.contactlistTV2);                
           phone.setText(cursor.getString          
          (cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));


@Override
public View newView(Context context, Cursor cursor, ViewGroup parent)  
    LayoutInflater inflater = LayoutInflater.from(context);
    View v = inflater.inflate(R.layout.lvct, parent, false);
            bindView(v, context, cursor);
    return v;



public View getView(final int pos, View inView, ViewGroup parent)  //getView 

    if (inView == null) 
    LayoutInflater inflater = (LayoutInflater) context1
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inView = inflater.inflate(R.layout.lvct, null);
    

    final CheckBox cBox = (CheckBox)inView.findViewById(R.id.checkBox1); // my
    // CheckBox

    cBox.setOnClickListener(new OnClickListener() 
        public void onClick(View v) 
            CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox1);

            if (cb.isChecked()) 
                itemChecked.set(pos, true);

                      //My problem should be here??

             else if (!cb.isChecked()) 
                itemChecked.set(pos, false);

            
        
    );
    cBox.setChecked(itemChecked.get(pos)); // this will Check or Uncheck the
    // CheckBox in ListView
    // according to their original
    // position and CheckBox never
    // loss his State when you
    // Scroll the List Items.
    return inView;

我的活动课

   public class Contacts extends Activity 
@Override
protected void onCreate(Bundle savedInstanceState) 
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contacts);

    Cursor cursor = getContentResolver().query
            (ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);
        startManagingCursor(cursor);
           ContactCursorAdapterCT adapter= new ContactCursorAdapterCT
           (Contacts.this, cursor);
       ListView contactLV = (ListView) findViewById(R.id.listviewblcontactsDB);
           contactLV.setAdapter(adapter);

我的数据库类

  public long creatEntry(String inputnumber , String name)  // for add data   

    // TODO Auto-generated method stub
    ContentValues cv= new ContentValues();
    cv.put(KEY_NUMBER, inputnumber);
    cv.put(N_NAME, name);
    Log.v(inputnumber, "adding to Database");
    return ourdatabase.insert(DATABASE_TABLE, null, cv);
  

【问题讨论】:

我应该在哪里调用 createentry 函数? 【参考方案1】:

这是一个简单的 DBhelper 示例,它允许使用 SQLite 数据库。它具有添加新数据和更新已保存数据所需的方法。

public class DBHelper extends SQLiteOpenHelper 

private static DBHelper instance;
private static final String DATABASE_NAME = "HangmanBase";
    private static final int DATABASE_VERSION = 2;
public static interface ITEM extends BaseColumns 
        String TABLE_NAME = "itemTable";
        String NAME = "itemName";
        String CHECK = "itemCheck";
    
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS ";
    private static final String DROP_TABLE = "DROP TABLE IF EXISTS ";
    private static final String UNIQUE = "UNIQUE ON CONFLICT ABORT";
private static final String CREATE_TABLE_ITEM = CREATE_TABLE + ITEM.TABLE_NAME + " (" + ITEM._ID
            + " INTEGER PRIMARY KEY, " + ITEM.NAME + " TEXT " + UNIQUE + ", " + ITEM.CHECK + " INTEGER);";
private DBHelper(Context context) 
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    
public static DBHelper getInstance(Context context) 
        if (instance == null) 
            instance = new DBHelper(context);
        
        return instance;
    
@Override
    public void onCreate(SQLiteDatabase db) 
        db.execSQL(CREATE_TABLE_ITEM);
    
@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        db.execSQL(DROP_TABLE + ITEM.TABLE_NAME);
        onCreate(db);
    
public long addWord(String name, boolean check) 
        ContentValues values = new ContentValues();
        values.put(ITEM.NAME, name);
        values.put(ITEM.CHECK, check);
        return getWritableDatabase().insert(ITEM.TABLE_NAME, null, values);
    
public Cursor getAllItemCursor() 
        return getReadableDatabase().rawQuery("SELECT * FROM " + ITEM.TABLE_NAME, null);
    
public void changeItemCheck(String itemName, boolean isChecked) 
        ContentValues values = new ContentValues();
        values.put(ITEM.CHECK, isChecked);
        getWritableDatabase().update(ITEM.TABLE_NAME, values, ITEM.NAME + " =? ", new String[]  itemName );
    

一个 ListView 的简单活动:

私有ListView itemList;

私有 DBHelper dbHelper;

私有 CursorAdapter 适配器;

@Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cursor_list);
        itemList = (ListView)findViewById(R.id.item_list);
        dbHelper = DBHelper.getInstance(this);
        Cursor allItemCursor = dbHelper.getAllItemCursor();
        adapter = new ItemCursorAdapter(this, allItemCursor, true);
        itemList.setAdapter(adapter);
    

还有带有自定义 OnCheckedChangeListener 的 SimpleCursorAdapter 示例。也许它不是将检查更改保存到 DB 的最佳方式:

public class ItemCursorAdapter extends CursorAdapter 

private final LayoutInflater inflater;
    private int itemNameIndex;
    private int itemCheckIndex;
    private DBHelper dbHelper;
public ItemCursorAdapter(Context context, Cursor cursor, boolean autoRequery) 
        super(context, cursor, autoRequery);
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        itemNameIndex = cursor.getColumnIndex(DBHelper.ITEM.NAME);
        itemCheckIndex = cursor.getColumnIndex(DBHelper.ITEM.CHECK);
        dbHelper = DBHelper.getInstance(context);
    
public void bindView(View view, Context context, Cursor cursor) 
        String name = cursor.getString(itemNameIndex);
        boolean checked = cursor.getInt(itemCheckIndex) > 0;
        TextView nameTxt = (TextView) view.findViewById(R.id.item_name);
        CheckBox checkChk = (CheckBox) view.findViewById(R.id.item_check);
        checkChk.setOnCheckedChangeListener(new onItemCheckChangeListener(name));
        nameTxt.setText(name);
        checkChk.setChecked(checked);
    
@Override
    public View newView(Context context, Cursor c, ViewGroup parent) 
        View view = inflater.inflate(R.layout.row_item, null);
        return view;
    
private class onItemCheckChangeListener implements OnCheckedChangeListener 
private String itemName;
public onItemCheckChangeListener(String itemName) 
            this.itemName = itemName;
        
@Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
            dbHelper.changeItemCheck(itemName, isChecked);
        


【讨论】:

以上是关于Listview和复选框(如何放入数据库(sqlite))的主要内容,如果未能解决你的问题,请参考以下文章

如何获取listview里选中的checkbox

如何使用复选框和自定义适配器从 Listview 中获取选定的列表项?

如何将可扩展的 ListView 放入 ScrollView

使用android中的自定义arrayadapter在listview中使用复选框检查后如何删除多个项目?

C# winform listview 选中的复选框排序

如何使用复选框将Android联系人添加到列表视图中[重复]