android-无法从数据库中删除项onLongItemClickListener listview

问题描述:

我有一个游标适配器,填充listview,它工作正常。 我想删除一个项目onLongItemClickListener。 我写了这段代码,但我知道这是错误的,因为我不知道数据库行ID是什么。android-无法从数据库中删除项onLongItemClickListener listview

 lv.setOnItemLongClickListener(new OnItemLongClickListener() { 
     @Override 
     public boolean onItemLongClick(AdapterView<?> parent, final View view,final int position, long id) { 

      builder= new AlertDialog.Builder(MainActivity.this); 
      builder.setMessage(R.string.deleteit) 
        .setCancelable(true) 
        .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          // myDb.deleteRow(position); 
         } 
        }); 
      AlertDialog alert = builder.create(); 
      alert.show(); 
      return false; 
     } 

    }); 

我登陆第三个项目从onItemLongClick (id),对于每一行它返回-1

我这是怎么填补我的ListView

cursor = myDb.getAllRows(); 
adapter_comments = new TimeListAdapter(MainActivity.this, cursor); 
lv.setAdapter(adapter_comments); 

这是我的CursorAdapter

public class TimeListAdapter extends CursorAdapter { 
    public TimeListAdapter(Context context, Cursor c) { 
     super(context, c); 
    } 

    public class ViewHolder { 
     TextView tvTitle; 
     TextView tvt9; 

     public ViewHolder(View row) { 
      tvTitle = (TextView) row.findViewById(R.id.title); 
      tvt9 = (TextView) row.findViewById(R.id.textView9); 

     } 
    } 

    @Override 
    public View newView(Context context, Cursor arg1, ViewGroup arg2) { 
     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View row = inflater.inflate(R.layout.spots_custom_listview, arg2,false); 
     ViewHolder holder = new ViewHolder(row); 
     row.setTag(holder); 
     return row; 
    } 

    @Override 
    public void bindView(View v, Context context, Cursor c) { 
     ViewHolder holder = (ViewHolder) v.getTag(); 
     holder.tvTitle.setText(c.getString(5)); 
     holder.tvt9.setText(c.getString(4)); 

    } 
} 

你能帮助我吗?

+0

发布您的错误logcat –

+0

@PratikButani没有错误,我只是不知道如何从此列表中删除一行数据库列。 – user3657105

+0

我已在下面回答,请检查它。 –

onItemLongClick的第三个参数是BaseColumns._ID值。

现在,你提到它返回-1,所以,列表或适配器有问题。

也许您传递给cursorAdapter的游标不包含_ID列作为投影的一部分。

您可以将代码发布到创建cursorAdapter的地方吗?

+0

谢谢你的回复,我附上了cursorAdapter类,我确定cursor有数据库中的_id。 – user3657105

+0

如果这不是一个答案,那么你为什么接受? –

+0

我看不出在这里扩展游标适配器的理由。你应该可以用正常的游标适配器来做到这一点,覆盖方法,而不是调用超级可能会给你意想不到的结果,也许这是问题的根源 – shalafi

试试这个:

public void onClick(DialogInterface dialog, int id) { 
    // First you have to get cursor using position 
    Cursor cursor = (Cursor) lv.getItemAtPosition(position); 

    //Now you can get id using column name of ROW_ID 
    int id = cursor.getInt(cursor.getColumnIndex("your_row_id_column_name")); 

    //Now delete you row 
    myDb.deleteRow(id); 
} 

随意ping通,如果有任何疑问。