有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android:如何从保存在SQLite数据库中的listview中删除项目?

我必须从保存在SQLite数据库中的listview中删除一项。我可以使用搜索“EditText”来完成,但我只需要点击它们就可以删除行。 这是我的代码:

DBHelper:

public class EventDbHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "USERINFO.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
        "CREATE TABLE "+ Event.NewEventInfo.TABLE_NAME+"("+
                Event.NewEventInfo.NAME+" TEXT,"+
                Event.NewEventInfo.YEAR+" TEXT,"+
                Event.NewEventInfo.MONTH+" TEXT,"+
                Event.NewEventInfo.DAY+" TEXT,"+
                Event.NewEventInfo.HOUR+" TEXT,"+
                Event.NewEventInfo.MINUTE+" TEXT);";

public EventDbHelper(Context context){

    super(context,DATABASE_NAME,null,DATABASE_VERSION);
    Log.e("DATABASE OPERATIONS","Database created/opened...");

}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(CREATE_QUERY);
    Log.e("DATABASE OPERATIONS","Table created...");

}

public void addInformation (String name,String year,String month,String day,String hour,String minute,SQLiteDatabase db)
{
    ContentValues contentValues=new ContentValues();
    contentValues.put(Event.NewEventInfo.NAME,name);
    contentValues.put(Event.NewEventInfo.YEAR,year);
    contentValues.put(Event.NewEventInfo.MONTH,month);
    contentValues.put(Event.NewEventInfo.DAY,day);
    contentValues.put(Event.NewEventInfo.HOUR,hour);
    contentValues.put(Event.NewEventInfo.MINUTE,minute);
    db.insert(Event.NewEventInfo.TABLE_NAME,null,contentValues);
    Log.e("DATABASE OPERATIONS","One row inserted...");
}

public Cursor getInformation (SQLiteDatabase db)
{
    Cursor cursor;
    String[] projections = {Event.NewEventInfo.NAME, Event.NewEventInfo.YEAR, Event.NewEventInfo.MONTH,
            Event.NewEventInfo.DAY, Event.NewEventInfo.HOUR, Event.NewEventInfo.MINUTE};
    cursor = db.query(Event.NewEventInfo.TABLE_NAME,projections,null,null,null,null,null);
    return cursor;

}



public void deleteInformation(String name, SQLiteDatabase db)
{
    String selection = Event.NewEventInfo.NAME+" LIKE ?";
    String[] selection_args = {name};
    db.delete(Event.NewEventInfo.TABLE_NAME,selection,selection_args);
}




@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
}

主要活动:

 public void deleteEvent (View view)
{
    search_name=et.getText().toString();
    eventDbHelper= new EventDbHelper(getApplicationContext());
    sqLiteDatabase= eventDbHelper.getReadableDatabase();
    eventDbHelper.deleteInformation(search_name, sqLiteDatabase);
    Toast.makeText(getApplicationContext(),"Event  deleted",Toast.LENGTH_SHORT).show();
    finish();
    startActivity(getIntent());

}

ListDataAdapterActivity:

public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
    super(context, resource);
}

static class LayoutHandler
{
    TextView NAME,DAYS,HOURS,MINUTES,SECONDS;

}

@Override
public void add(Object object) {
    super.add(object);
    list.add(object);
}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int position) {
    return list.get(position);
}

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

    View row = convertView;
    LayoutHandler layoutHandler;
    if(row == null)
    {
        LayoutInflater layoutInflater =(LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = layoutInflater.inflate(R.layout.list_item,parent,false);
        layoutHandler = new LayoutHandler();
        layoutHandler.NAME = (TextView) row.findViewById(R.id.text_name);
        layoutHandler.DAYS = (TextView) row.findViewById(R.id.days_list_item);
        layoutHandler.HOURS = (TextView) row.findViewById(R.id.hours_list_item);
        layoutHandler.MINUTES = (TextView) row.findViewById(R.id.minutes_list_item);
        //layoutHandler.SECONDS = (TextView) row.findViewById(R.id.seconds_list_item);
        row.setTag(layoutHandler);
    }

    else{

        layoutHandler =(LayoutHandler) row.getTag();

    }

    DataProvider dataProvider =(DataProvider) this.getItem(position);
    layoutHandler.NAME.setText(dataProvider.getName());
    layoutHandler.DAYS.setText(dataProvider.getsDays());
    layoutHandler.HOURS.setText(dataProvider.getsHours());
    layoutHandler.MINUTES.setText(dataProvider.getsMinutes());
    //layoutHandler.SECONDS.setText(dataProvider.getsSeconds());

    return row;
}

}

我应该编辑什么


共 (1) 个答案

  1. # 1 楼答案

    下面是一个由SQLite数据库填充的listview的简单示例

    我只会解释如何阅读信息,以及如何在之后删除一行

    首先,必须为列出的对象创建一个模式(可选)。listview还可以由字符串列表或基本变量类型填充

    让我们创建一个包含名称和简短描述的类别模式。它包含字段、构造函数、getter和setter:

    public class Category {
    
        //Fields
        private int id;
        private String name;
        private String description;
    
        //Constructors
        public Category()
        {
    
        }
    
        public Category(String name, String description)
        {
            this.name = name;
            this.description = description;
        }
    
        public Category(int id, String name, String description)
        {
            this.id = id;
            this.name = name;
            this.description = description;
        }
    
        //Setters
        public void setId(int id)
        {
            this.id = id;
        }
    
        public void setName(String name)
        {
            this.name = name;
        }
    
        public void setDescription(String description)
        {
            this.description = description;
        }
    
        //Getters
        public int getId()
        {
            return this.id;
        }
    
        public String getName()
        {
            return this.name;
        }
    
        public String getDescription()
        {
            return this.description;
        }
    
    }
    

    我们将用类别列表填充listView。此列表从数据库中获取信息

    最后,您需要创建一个自定义适配器(或使用预定义的适配器),将每个类别项链接到一个xml布局文件

    public class CategoryAdapter extends BaseAdapter {
    
        private Activity activity;
        private LayoutInflater inflater;
        private List<Category> items;
    
        public CategoryAdapter(Activity activity, List<Category> items) {
            this.activity = activity;
            this.items = items;
        }
    
        @Override
        public int getCount() {
            return items.size();
        }
    
        @Override
        public Object getItem(int location) {
            return items.get(location);
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
    
            if (inflater == null)
                inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
            if (convertView == null)
                convertView = inflater.inflate(R.layout.item_category, null);
    
            TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
            TextView tvDescription = (TextView) convertView.findViewById(R.id.tvDescription);
    
            // getting product data for the row
            Category c = items.get(position);
    
            // name
            tvName.setText(c.getName());
    
            // description
            tvDescription.setText(String.valueOf(c.getDescription()));
    
            return convertView;
        }
    
    }
    

    XML

    <?xml version="1.0" encoding="utf-8"?>
    
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:id="@+id/tvName"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:textStyle="bold"/>
    
        <TextView
            android:id="@+id/tvDescription"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:textColor="@color/gray"/>
    
    </LinearLayout>
    

    是时候将适配器和类别列表链接到listview了

    db = new DatabaseHelper(getApplicationContext());
    categories = new ArrayList<>();
    categories = db.getAllCategories();
    db.closeDB();
    
    //The category adapter links the list of categories to the listview
    lvCategories = (ListView) findViewById(R.id.lvCategories);
    adapter = new CategoryAdapter(this, categories);
    lvCategories.setAdapter(adapter);
    

    本简短教程的最后一部分将演示如何在长时间单击某个项目时删除该行。弹出窗口要求用户确认操作

            //onLongClick : delete item
            lvCategories.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    
                    try {
                        final Category category = (Category) parent.getItemAtPosition(position);
    
                        //Open dialog box
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(c);
    
                        alertDialogBuilder
                                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
    
                                        //Delete client by id
                                        db.deleteCategory(category.getId());
    
                                        //Confirmation message
                                        Toast.makeText(c, R.string.delete_category_successfull, Toast.LENGTH_SHORT).show();
    
                                        //Rafraîchir la liste
                                        onResume();
    
                                    }
                                })
                                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        //Cancel operation
    
                                    }
                                    // Create the AlertDialog object and return it
                                    // return builder.create();
                                })
                                .setTitle(getString(R.string.delete))
                                .setMessage(getString(R.string.delete_category, category.getName()))
                                .create();
    
                        alertDialogBuilder.show();
    
                    } catch (Exception e) {
                        Toast.makeText(c, String.valueOf(e), Toast.LENGTH_LONG).show();
                    }
    
    
                    return true;
                }
    
            });
    

    简历上

    categories = db.getAllCategories();
    db.closeDB();
    
    adapter = new CategoryAdapter(this, categories);
    lvCategories.setAdapter(adapter);
    

    以下是来自DatabaseHelper的getAllCategories和deleteCategory查询:

    /*
     * getting all categories
     * */
    public List<Category> getAllCategories() {
        List<Category> categories = new ArrayList<Category>();
        String selectQuery = "SELECT  * FROM " + TABLE_CATEGORIES;
    
        Log.e(LOG, selectQuery);
    
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);
    
        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                Category category = new Category();
                category.setId(Integer.parseInt(c.getString(c.getColumnIndex(ID))));
                category.setName(c.getString((c.getColumnIndex(CATEGORY_NAME))));
                category.setDescription((c.getString(c.getColumnIndex(CATEGORY_DESCRIPTION))));
    
                // adding to clients list
                categories.add(category);
            } while (c.moveToNext());
        }
    
        return categories;
    }
    
    
    /*
     * Deleting a category
     */
    public void deleteCategory(int category_id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CATEGORIES, ID + " = ?",
                new String[] { String.valueOf(category_id) });
    }
    

    不要羞于询问您是否需要进一步的帮助来在数据库中插入项目、更新项目或其他任何事情