我开始了一个小的Android项目来重新学习一点Android开发,我已经卡住了......
我不知道如何执行删除我的一个元素ListView
!
这是项目:https ://github.com/gdurelle/Listify
现在它旨在显示元素列表的列表。
我使用自定义CursorAdapter
来显示我的元素列表,并且我已经有一个(丑陋的)销毁按钮,但我不知道如何让它从列表(和数据库)中删除一个实际元素。
我使用ActiveAndroid以ActiveRecord的方式管理数据库。
另外:我不确定是否使用getView()
, bindView()
, 和/或newView()
...
我创建了一个问题来记住这一点并在此处引用此问题:https ://github.com/gdurelle/Listify/issues/1
public class ListifyCursorAdapter extends CursorAdapter {
public String content;
public ListifyCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it, you don't bind any data to the view at this point.
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.element_line, parent, false);
}
// The bindView method is used to bind all data to a given view such as setting the text on a TextView.
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
}
}
在我的 MainActivity 中:
Cursor cursor = ListifyElement.fetchResultCursor();
adapter = new ListifyCursorAdapter(this, cursor);
listView.setAdapter(adapter);
我可能在想一个:
Button delete_button = (Button) listView.findViewById(R.id.delete_button);
类似于ListifyElement.load(ListifyElement.class, the_id_of_the_element).delete();
where the_id_of_the_element将是从用户界面中单击它的 delete_button 以某种方式检索的元素的 DB id ...
更新:
@Override
public void bindView(View view, Context context, final Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
Button delete_button = (Button) view.findViewById(R.id.delete_button);
delete_button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
System.out.println(cursor.getColumnName(0)); // Id
System.out.println(cursor.getColumnName(1)); // ListifyContainer
System.out.println(cursor.getColumnName(2)); // content
System.out.println(cursor.getColumnIndexOrThrow("Id")); // 0
ListifyElement.load(ListifyElement.class, cursor.getColumnIndexOrThrow("Id")).delete();
notifyDataSetChanged();
}
});
单击删除按钮时出现此错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gdurelle.listify.models.ListifyElement.delete()' on a null object reference