android - 如何从listView中删除项目?

标签 android listview

我在Listview中从SQLite获取数据。当用户单击检查时我需要删除此项
框并按删除按钮或仅单击复选框,
我不明白该怎么做?这是我的示例代码供引用。

MyTable.java

public class MyTable extends ListActivity {


 MySQLiteHelper m=new MySQLiteHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {        
    super.onCreate(savedInstanceState);     
    Intent intent = getIntent();
    setResult(RESULT_OK, intent);       
    ArrayAdapter<Model> adapter = new InteractiveArrayAdapter(this,
            getModel());
    setListAdapter(adapter);
}


private List<Model> getModel()
{

    List<Model> list = new ArrayList<Model>();
    final MySQLiteHelper m=new MySQLiteHelper(getBaseContext());
    final List<LocWiseProfileBeans> LocWiseProfile= m.getAllLocWiseProfile();       

    for (final LocWiseProfileBeans cn : LocWiseProfile) {

    list.add((get(cn.getLocname())));
    //list.add(get(cn.getSelectedprofile()));

    // Initially select one of the items
    list.get(0).setSelected(true);

    }
    return list;
}
private Model get(String s) {
    return new Model(s);
}

InteractiveArrayAdapter.java

    public class InteractiveArrayAdapter extends ArrayAdapter<Model> {

private final List<Model> list;
private final Activity context;

public InteractiveArrayAdapter(Activity context, List<Model> list) 
{
    super(context, R.layout.locprofile, list);
    this.context = context;
    this.list = list;
}

static class ViewHolder {
    protected TextView text;
    protected CheckBox checkbox;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View view = null;

    if (convertView == null) {


        LayoutInflater inflator = context.getLayoutInflater();
        view = inflator.inflate(R.layout.locprofile, null);

        final ViewHolder viewHolder = new ViewHolder();

        viewHolder.text = (TextView) view.findViewById(R.id.label);
        viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
        viewHolder.checkbox
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isChecked) {
                        Model element = (Model) viewHolder.checkbox
                                .getTag();
                        element.setSelected(buttonView.isChecked());

                    }
                });
        view.setTag(viewHolder);
        viewHolder.checkbox.setTag(list.get(position));

    } else {

        view = convertView;
        ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));

    }


    ViewHolder holder = (ViewHolder) view.getTag();
    holder.text.setText(list.get(position).getName());
    holder.checkbox.setChecked(list.get(position).isSelected());


    return view;
}
}

MySQliteHelper.java

public static final String TABLE_NAME = "loc_wise_profile";
public static final String TABLE_NAME2 = "supervisor";
public static final String COLUMN_ID = "_id";
public static final String COLUMN1 = "loc_name";
public static final String COLUMN2 = "lattitude";
public static final String COLUMN3 = "longitude";
public static final String COLUMN4 = "selectedprofile";
public static final String COLUMN5 = "contactno";
public static final String COLUMN6 = "message";
//public static final String COLUMN7 = "enabled";
public static final String COLUMN8 = "NotificeationMessage";

SQLiteDatabase db;   
private static final String DATABASE_NAME = "locale";
private static final int DATABASE_VERSION = 2;

// Database creation sql statement
private static final String DATABASE_CREATE = "create table IF NOT EXISTS "
        + TABLE_NAME + "( " + COLUMN_ID
        + " integer primary key autoincrement, " 
        + COLUMN1 + " text not null, "
        + COLUMN2 + " double not null, "
        + COLUMN3 + " double not null, "
        + COLUMN4 + " text not null ,"
        + COLUMN5 + " text not null ,"
        + COLUMN6 + " text not null ,"
        //+ COLUMN7 + " text not null ,"
        + COLUMN8 + " text not null "
        + ");";



public MySQLiteHelper(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase database) {
    // TODO Auto-generated method stub
    database.execSQL(DATABASE_CREATE);
    //database.execSQL(DATABASE_CREATE2);
}


  // Adding new Location wise Profile
public void insertLocWiseProfile(LocWiseProfileBeans loc) {
     db= this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(COLUMN1, loc.getLocname()); // Contact Name
    values.put(COLUMN2, loc.getLattitude()); // Contact Phone Number
    values.put(COLUMN3, loc.getLongitude());
    values.put(COLUMN4, loc.getSelectedprofile());
    values.put(COLUMN5, loc.getContactno());
    values.put(COLUMN6, loc.getMessage());
    //values.put(COLUMN7, loc.getEnabled());
    values.put(COLUMN8, loc.getNotificationMessage());
    // Inserting Row
    db.insert(TABLE_NAME, null, values);
    db.close(); // Closing database connection
}



    // Getting All Contacts
 public List<LocWiseProfileBeans> getAllLocWiseProfile() {
    List<LocWiseProfileBeans> LocWiseProfileList = new ArrayList<LocWiseProfileBeans>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            LocWiseProfileBeans loc= new LocWiseProfileBeans();
            //loc.set
            loc.setId(cursor.getInt(0));
            loc.setLocname(cursor.getString(1));
            loc.setLattitude(cursor.getDouble(2));
            loc.setLongitude(cursor.getDouble(3));
            loc.setSelectedprofile(cursor.getString(4));
            loc.setContactno(cursor.getString(5));
            loc.setMessage(cursor.getString(6));
           // loc.setEnabled(cursor.getString(7));
            // Adding contact to list
            LocWiseProfileList.add(loc);
        } while (cursor.moveToNext());
    }

    // return contact list
    return LocWiseProfileList;
}


@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    Log.w(MySQLiteHelper.class.getName(), "Upgrading database from version "
            + oldVersion + " to " + newVersion
            + ", which will destroy all old data");
    database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(database);
}
public void delete(int value)
{
    try{            
        SQLiteDatabase db= this.getWritableDatabase();
        db.delete(TABLE_NAME, COLUMN_ID+"="+value, null);

}
    catch(Exception e){}

}


public void deleteAll(){
    try{
    //db.execSQL("delete * from "+ TABLE_NAME);

        SQLiteDatabase db= this.getWritableDatabase();
        db.delete(TABLE_NAME, null, null);

    }catch(Exception e){}
}   

}

最佳答案

您需要更改 getView 原型(prototype):

public View getView(int position, View convertView, ViewGroup parent)

public View getView(final int position, View convertView, ViewGroup parent)

然后添加到您的 viewHolder.checkbox.setOnCheckedChangeListener 监听器:

Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
InteractiveArrayAdapter.this.remove(InteractiveArrayAdapter.this.getItem(position));
list.remove(position); //here consider whether you can afford changing list
// If you want to add code to remove the element from the database too

我自己没有尝试过,但似乎可行。

编辑:根据您的请求,我添加代码以从数据库中删除该条目:

在您的 MySQliteHelper 类中添加以下方法:

public void deleteByName(String name) {          
   SQLiteDatabase db= this.getWritableDatabase();
   db.delete(TABLE_NAME, COLUMN1 +"=?", new String [] { name });
   db.close();
}

然后更改监听器的代码:

Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
InteractiveArrayAdapter.this.remove(InteractiveArrayAdapter.this.getItem(position));

MySQLiteHelper m = new MySQLiteHelper(InteractiveArrayAdapter.this.context);
m.deleteNyName(list.get(position).toString());
list.remove(position); //here consider whether you can afford changing list

在这里我假设你的名字是独一无二的。如果这不是真的,您将需要重构您的 Model 类(顺便说一句,这已经太困惑了,我只是疯狂猜测 model.toString() 将返回名称)。

关于android - 如何从listView中删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9645101/

相关文章:

java - 如何从天数转换为天数、周数、月数、年数(以每日储蓄计)

java - 如何在android应用程序中设置可点击的链接?

c# - 将文件从 ListView 拖放到 Windows 资源管理器?

android - 从远程服务器加载图像?

android - 安卓的屏幕和通过HDMI连接的屏幕是否可以显示不同的内容?

android - 切换按钮不适用于抽屉导航

android - ListView 项目 ListSelector 可绘制闪烁

android - android中的appwidget listview更新问题

c# - ListView 鼠标点击事件

C# UWP Listview/GridView 所选项目的标记