2016-06-09 15 views
0

我必須從列表視圖中刪除保存在SQLite數據庫中的項目。我可以使用搜索「EditText」來做到這一點,但我只需要移除只點擊它們的行。 這裏是我的代碼:Android:如何刪除保存在SQLite數據庫中的列表視圖中的項目?

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) { 

} 
} 

MainActivity:

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; 
} 

}

什麼我應該編輯?

+0

[刪除從SQLite]可能的重複(http://stackoverflow.com/questions/7633168/deleting-from-sqlite) – Vucko

+0

如果需要我可以發佈一個示例代碼誰刪除onLongClick項目... –

+0

發佈它請。 @AlexandreMartin –

回答

0

您應該使用適配器來鏈接xml佈局文件和對象元素列表以分別顯示項目和填充列表視圖。

然後,刪除數據庫中的項目和刷新列表。

+0

我已經爲適配器添加了另一個類 –

0

下面是一個由SQLite數據庫填充的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> 

是時候適配器和類別列表視圖列表鏈接。

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); 

這裏有getAllCategories和deleteCategory查詢從DatabaseHelper:

/* 
* 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) }); 
} 

不要羞於問,如果您需要進一步的援助,以插入數據庫項目,更新它們或其他任何東西!

+0

非常感謝,我將嘗試它。 –

相關問題