英文:
Android, delete item in list and in sqllite java
问题
> 注意:问题的末尾有更新但仍未生效。
大家好,我有一个列表和一个弹出窗口,在弹出窗口中我可以点击**删除**。
我如何删除我在列表中长按的项目
***此列表存储在本地的 sqllite 数据库中。***
***我想点击删除以删除 Edinburgh 项目***
[![在这里输入图片描述][1]][1]
我的列表代码:
```java
public class ViewListContents extends AppCompatActivity {
DatabaseHelper myDB;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.popup_layout, menu);
return true;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewcontents_layout);
ListView listView = findViewById(R.id.listView);
myDB = new DatabaseHelper(this);
final MenuItem deleteItem, editItem;
final ArrayList<String> theList = new ArrayList<>();
final Cursor data = myDB.getListContents();
final ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
listView.setAdapter(listAdapter);
deleteItem = findViewById(R.id.delete_item);
editItem = findViewById(R.id.edit_item);
final ListView finalListView = listView;
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View v, final int position, final long id) {
PopupMenu p = new PopupMenu(ViewListContents.this, v);
MenuInflater inflater = p.getMenuInflater();
inflater.inflate(R.menu.popup_layout, p.getMenu());
p.show();
// 监听器等待在弹出菜单项上的点击
p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(),
item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.delete_item:
finalListView.getItemAtPosition(position);
myDB.deleteEntry(finalListView.getSelectedItemPosition());
((ArrayAdapter) listAdapter).remove(listAdapter.getItem(position));
((ArrayAdapter) listAdapter).notifyDataSetChanged();
int x = ReadID(position);
myDB.deleteEntry(x);
myDB.getAllItems(Contract.YourEntry.COL2);
return true;
case R.id.edit_item:
getTheme();
return true;
default:
return true;
}
}
});
return true;
}
});
if (data.getCount() == 0) {
Toast.makeText(ViewListContents.this, "Your list is empty :(", Toast.LENGTH_LONG).show();
} else {
while (data.moveToNext()) {
theList.add(data.getString(1));
listView.setAdapter(listAdapter);
}
}
}
public int ReadID(int position){
DatabaseHelper mDbHelper = new DatabaseHelper(this);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {Contract.YourEntry.COL2};
String sortOrder = Contract.YourEntry.COL2 + " ASC";
Cursor cursor = db.query(
Contract.YourEntry.TABLE_NAME,
null,
null,
null,
null,
null,
sortOrder
);
try {
int idColumnIndex = cursor.getColumnIndex(Contract.YourEntry.intWhereToGoListOID);
int currentID = 0;
int count = 0;
while ((cursor.moveToNext() == true) && (count != (position + 1))) {
currentID = cursor.getInt(idColumnIndex + 1);
count ++;
}
return currentID;
} finally {
cursor.close();
}
}
}
这是我的数据库代码:
public class DatabaseHelper extends SQLiteOpenHelper {
// 数据库
public static final String DATABASE_NAME = "mylist.db";
// 表
public static final String TABLE_TWHERETOGOLIST = "TWhereToGoList";
public static final String TABLE_NAME_2 = "TCategories";
public static final String TABLE_TListDefiniton = "TListDefinition";
// 表: TWhereToGoList 的列
public static final String intWhereToGoListOID = "WhereToGoListOID";
public static final String COL2 = "COL2";
public static final String intCategoriesOID = "CategoriesOID ";
public static final DateFormat dtDateLastModified = DateFormat.getDateInstance();
// ... 其他列的定义 ...
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.deleteDatabase(new File(DATABASE_NAME));
String createTable = "CREATE TABLE " + TABLE_TWHERETOGOLIST + " (intWhereToGoListOID INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " COL2 TEXT, " + " intCategoriesOID TEXT, " + " strDescription TEXT, "
+ " strGoogleLink TEXT, " + " bVisited INTEGER)";
db.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(String.format("DROP IF TABLE EXISTS ", TABLE_TWHERETOGOLIST));
onCreate(db);
}
// ... 其他方法的定义 ...
}
如果你有任何问题,请在下方评论中询问。感谢您的回复
更新 1.0:
我现在的问题是,我不知道如何获取我在列表项上长按并按下弹出窗口中的删除按钮后的 ListView 项的 ID。
我必须将这个 ListView 项的 (ID 或其他内容) 传递给我的数据库代码,以便删除此项。
如果你有问题,请详细描述
我不知道我如何做到这一点。
<details>
<summary>英文:</summary>
> ATTENTION AT THE END OF THE QUESTION IS THE UPDATE BUT STILL NOT
> WORKING
Hey everyone I'm having a list and a popup where I can click on **delete**.
How can I delete the item which I long click in my list
***This list is stored in the local sqllite db.***
***I wanna click delete to delete the Edinbourgh item***
[![enter image description here][1]][1]
My Code for the list:
public class ViewListContents extends AppCompatActivity {
DatabaseHelper myDB;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.popup_layout, menu);
return true;
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewcontents_layout);
ListView listView = findViewById(R.id.listView);
myDB = new DatabaseHelper(this);
final MenuItem deleteItem, editItem;
final ArrayList<String> theList = new ArrayList<>();
final Cursor data = myDB.getListContents();
final ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
listView.setAdapter(listAdapter);
deleteItem = findViewById(R.id.delete_item);
editItem = findViewById(R.id.edit_item);
final ListView finalListView = listView;
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View v, final int position, final long id) {
PopupMenu p = new PopupMenu(ViewListContents.this, v);
MenuInflater inflater = p.getMenuInflater();
inflater.inflate(R.menu.popup_layout, p.getMenu());
p.show();
//Listener wait for the click on the popup menu item
p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(),
item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.delete_item:
finalListView.getItemAtPosition(position);
myDB.deleteEntry(finalListView.getSelectedItemPosition());
((ArrayAdapter) listAdapter).remove(listAdapter.getItem(position));
((ArrayAdapter) listAdapter).notifyDataSetChanged();
int x = ReadID(position);
myDB.deleteEntry(x);
myDB.getAllItems(Contract.YourEntry.COL2);
return true;
case R.id.edit_item:
getTheme();
return true;
default:
return true; //return ViewListContents.super.onOptionsItemSelected(deleteItem);
}
}
});
/* @Override
public boolean onOptionsItemSelected() {
switch (item.getItemId()) {
case R.id.delete_item:
theList.remove(position);
return true;
case R.id.edit_item:
getTheme();
return true;
default:
return ViewListContents.super.onOptionsItemSelected(deleteItem);
}
}*/
/* deleteItem.setOnActionExpandListener("Ok", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
theList.remove(position);
finalListView.setAdapter(listAdapter);
}
});*/
return true;
}
});
if (data.getCount() == 0) {
Toast.makeText(ViewListContents.this, "Your list is empty :(", Toast.LENGTH_LONG).show();
} else {
while (data.moveToNext()) {
theList.add(data.getString(1));
listView.setAdapter(listAdapter);
}
}
}
public int ReadID(int position){
DatabaseHelper mDbHelper = new DatabaseHelper(this);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {Contract.YourEntry.COL2};
String sortOrder = Contract.YourEntry.COL2 + " ASC";
Cursor cursor = db.query(
Contract.YourEntry.TABLE_NAME, // The table to query
null, // The array of columns to return (null to get all)
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // null if you don't want to group the rows
null, // null if you don't want filter by row groups
sortOrder // the order
);
try {
int idColumnIndex = cursor.getColumnIndex(Contract.YourEntry.intWhereToGoListOID);
int currentID = 0;
int count = 0;
while ((cursor.moveToNext() == true) && (count != (position + 1))) {
currentID = cursor.getInt(idColumnIndex + 1);
count ++;
}
return currentID;
} finally {
cursor.close();
}
}
}
And here's my DB code:
public class DatabaseHelper extends SQLiteOpenHelper {
// DATABASE
public static final String DATABASE_NAME = "mylist.db";
// TABLES
public static final String TABLE_TWHERETOGOLIST = "TWhereToGoList";
public static final String TABLE_NAME_2 = "TCategories";
public static final String TABLE_TListDefiniton = "TListDefinition";
// COLUMNS FOR TABLE: TWhereToGoList
public static final String intWhereToGoListOID = "WhereToGoListOID";
public static final String COL2 = "COL2";
public static final String intCategoriesOID = "CategoriesOID ";
public static final DateFormat dtDateLastModified = DateFormat.getDateInstance();
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
public String formattedDate = df.format(c);
public static final String strDescription = "Description";
public static final String strGoogleLink = "GoogleLink";
public static final Integer bVisited = 0;
public static final Integer bRecommend = 0;
public static final Integer intListDefinitionOID = 0;
// COLUMNS FOR TABLE: TCategories
public static final Integer getIntListDefinitionOID = 0;
//public static final String strTitle = "strTitle"; // Both can get called from the top
//public static final String strDescription = "strDescription"; // Both can get called from the top
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.deleteDatabase(new File(DATABASE_NAME));
String createTable = "CREATE TABLE " + TABLE_TWHERETOGOLIST + " (intWhereToGoListOID INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " COL2 TEXT, " + " intCategoriesOID TEXT, " + " strDescription TEXT, "
+ " strGoogleLink TEXT, " + " bVisited INTEGER)";
db.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(String.format("DROP IF TABLE EXISTS ", TABLE_TWHERETOGOLIST));
onCreate(db);
}
public boolean addData(String string) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, string);
long result = db.insert(TABLE_TWHERETOGOLIST, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_TWHERETOGOLIST, null);
return data;
}
/*public int delete(int position) {
SQLiteDatabase db = this.getWritableDatabase();
if (db == null) {
Logger.getLogger("The DB is empty");
}
db.delete(TABLE_TWHERETOGOLIST, COL2 + " = ?", new String[]{ (intWhereToGoListOID) }); //new String[]{Long.toString(positionOfId)} );
***ANOTHER UPDATE:***
Probably the problem is the -1 which you see at the last line in this quote here.
If I write there something else after the click on the delete button and looking from the main activity again back to the list the text gets replaced by the number and some elements get deleted and other gets a number or some text which i can write to the -1.
In another situation if i go some more times through this cyclus the numbers get summarize and just creepy.
> public void deleteEntry(int position) {
> SQLiteDatabase sqLiteDatabase = getWritableDatabase();
>
> sqLiteDatabase.execSQL("DELETE FROM " + Contract.YourEntry.TABLE_NAME + " WHERE " +
> Contract.YourEntry.COL2 + " = " + position + ";");
> sqLiteDatabase.execSQL("UPDATE " + Contract.YourEntry.TABLE_NAME + " SET " + Contract.YourEntry.COL2 +
> " = " + Contract.YourEntry.COL2 + " -1 " + " WHERE " + Contract.YourEntry.COL2 + " > " + position + ";");
> }
Logger.getLogger("Successfully deleted the item!!!");
//Logger.getLogger(String.valueOf(getListContents()));
db.close();
return 1;
}
public Cursor getAllItems() {
SQLiteDatabase db = getReadableDatabase();
return db.query(
TABLE_TWHERETOGOLIST,
null,
null,
null,
null,
null,
null
);
}
}
***If you're having any questions ask me in the comments below.
Thanks for your reply :)***
> UPDATE 1.0:
I've now the problem that I don't know how I could take the ID of the ListView Item I longclicked and pressed delete on the popup which occurs.
I've to get the (ID whatever) of this ListView Item to my DB code to delete this item.
Please ask if you have questions.
Please describe in DETAIL :)
I don't know how I can do this
[1]: https://i.stack.imgur.com/JkjVK.png
[2]: https://i.stack.imgur.com/5b8ti.png
</details>
# 答案1
**得分**: 1
当您点击删除时,您必须调用`delete`函数并将要删除的元素的`ID`传递给此函数。 <br>
为了做到这一点,您必须将元素读入`database`,并选择您选择的元素。 <br>
我认为一个问题可能是`position`从零开始,而数据库中的元素从位置1开始,所以您必须考虑这一点。 <br> <br>
这应该是读取元素的函数: <br>
(查看[此链接][1]获取更多信息,可能对您有用) <br> <br>
更新:根据您使用的合同类进行了调整
```java
public int ReadID(int position){
mDbHelper = new YourDbHelper(this);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {BaseColumns.intWhereToGoListOID,
};
String sortOrder = YourEntry.intWhereToGoListOID+ " ASC";
Cursor cursor = db.query(
YourEntry.TABLE_NAME, // 要查询的表
projection, // 要返回的列的数组(如果要获取全部列,则为null)
null, // WHERE子句的列
null, // WHERE子句的值
null, // 如果不想按行分组,则为null
null, // 如果不想按行组过滤,则为null
sortOrder // 排序顺序
);
try {
int idColumnIndex = cursor.getColumnIndex(YourEntry.intWhereToGoListOID);
int currentID = 0;
int count=0;
while ((cursor.moveToNext() == true) && (count != (position + 1))) {
currentID = cursor.getInt(idColumnIndex);
count ++;
}
return currentID;
} finally {
cursor.close();
}
}
更新:
为了更清晰,使用一个合同类来定义数据库的表。如果您使用它,您可以像这样引用元素:YourEntry.name_of_the_column(您必须在之前导入该类,例如:import .com.example. ... .YourContract.YourEntry)。
这是一个contract class
的示例:
import android.provider.BaseColumns;
public class YourContract {
private YourContract(){}
public static final class YourEntry implements BaseColumns {
public static final String TABLE_NAME = "TABLE_TWHERETOGOLIST";
public static final String intWhereToGoListOID = BaseColumns.intWhereToGoListOID;
public static final String COL2 = "COL2";
public static final String intCategoriesOID = "CategoriesOID ";
/*Other columns*/
}
}
(因此您必须更改您的onCreate,用YourEntry.collum或YourEntry.TABLE_NAME进行调整,链接中有示例)
英文:
When you click delete you have to call the delete
function and pass the ID
of the element you want to delete to this function.<br>
In order to do this you have to read the elements into the database
and pick the one you selected. <br>
I think that one problem should be that position
starts from zero and the elements into the database from position 1, so you have to consider that.<br><br>
This should be the function for read elements:<br>
(Check this for more, it may be useful for you)<br><br>
UPDATE: adapted as your are using a contract class
public int ReadID(int position){
mDbHelper = new YourDbHelper(this);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {BaseColumns.intWhereToGoListOID,
};
String sortOrder = YourEntry.intWhereToGoListOID+ " ASC";
Cursor cursor = db.query(
YourEntry.TABLE_NAME, // The table to query
projection, // The array of columns to return (null to get all)
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // null if you don't want to group the rows
null, // null if you don't want filter by row groups
sortOrder // the order
);
try {
int idColumnIndex = cursor.getColumnIndex(YourEntry.intWhereToGoListOID);
int currentID = 0;
int count=0;
while ((cursor.moveToNext() == true) && (count != (position + 1))) {
currentID = cursor.getInt(idColumnIndex);
count ++;
}
return currentID;
} finally {
cursor.close();
}
}
<br><br>
UPDATE:<br>
To be clearer use a contract class where you define your table of the database. If you use it you can refere to elements like YourEntry.name_of_the_column (you have to import the class before ex: import .com.example. ... .YourContract.YourEntry ).<br>
This is a contract class
example:<br>
import android.provider.BaseColumns;
public class YourContract {
private YourContract(){}
public static final class YourEntry implements BaseColumns {
public static final String TABLE_NAME = "TABLE_TWHERETOGOLIST";
public static final String intWhereToGoListOID = BaseColumns.intWhereToGoListOID;
public static final String COL2 = "COL2";
public static final String intCategoriesOID = "CategoriesOID ";
/*Other columns*/
}
}
(so you have to change your onCreate adapting it with YourEntry.collum or YourEntry.TABLE_NAME, example in the link above)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论