Android,删除列表和sqlite java中的项目
Posted
技术标签:
【中文标题】Android,删除列表和sqlite java中的项目【英文标题】:Android, delete item in list and in sqllite java 【发布时间】:2021-01-24 08:54:14 【问题描述】:注意问题的最后是更新,但仍然不是 工作中
大家好,我有一个列表和一个弹出窗口,我可以在其中点击删除。
如何删除我在列表中长按的项目此列表存储在本地 sqllite 数据库中。
我想点击删除以删除爱丁堡项目
我的列表代码:
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();
这是我的数据库代码:
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) );
另一个更新: 问题可能是您在此处引用的最后一行看到的 -1。 如果我在单击删除按钮后在此处写其他内容并再次从主活动返回列表,则文本将被数字替换,并且某些元素被删除,而其他元素则获得一个数字或一些我可以写入的文本-1. 在另一种情况下,如果我在这个循环中多走几次,数字就会被总结出来,令人毛骨悚然。
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
);
如果您有任何问题,请在下面的 cmets 中问我。 感谢您的回复:)
更新 1.0:
我现在遇到的问题是,我不知道如何获取我长按并在出现的弹出窗口上按删除的 ListView 项的 ID。
我必须将这个 ListView 项目的(ID 随便)放到我的数据库代码中才能删除这个项目。
如果您有任何问题,请询问。
请详细描述:) 我不知道我该怎么做
【问题讨论】:
我怕不跟? @EyosiyasBerketab 我想在我的应用程序中删除一个 ListView 项目,同时按下弹出部分删除。但我无法删除该项目。 是否 myDB.delete(theList.get(position));删除记录? 先测试,然后再通知Adapter数据发生变化。 现在解决了 1/2,因为我现在遇到的问题是我的整个列表都被删除了。db.execSQL("DELETE FROM " + TABLE_TWHERETOGOLIST + " WHERE " + COL2 + " = " + position + ";"); db.execSQL("UPDATE " + TABLE_TWHERETOGOLIST + " SET " + COL2 + " = " + COL2 + " -1 " + " WHERE " + COL2 + " > " + position + ";");
@IntelliJAmiya
【参考方案1】:
当您单击删除时,您必须调用delete
函数并将您要删除的元素的ID
传递给此函数。
为此,您必须将元素读入database
并选择您选择的元素。
我认为一个问题应该是position
从零开始,元素从位置1进入数据库,所以你必须考虑这一点。
这应该是读取元素的功能:
(更多信息请查看this,它可能对您有用)
更新:根据您使用合同类进行调整
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();
更新:
为了更清楚,使用定义数据库表的合同类。如果你使用它,你可以参考 YourEntry.name_of_the_column 之类的元素(你必须在 ex: 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*/
(因此您必须使用 YourEntry.collum 或 YourEntry.TABLE_NAME 更改您的 onCreate 以适应它,例如上面的链接)
【讨论】:
评论不用于扩展讨论;这个对话是moved to chat。以上是关于Android,删除列表和sqlite java中的项目的主要内容,如果未能解决你的问题,请参考以下文章
Android:无法从 ListView 和 SQLite 中删除记录
Android clear listview 链接到 SQLite
Xamarin/SQLite/C# - 如何使用菜单项删除从列表视图和 SQLite 表中删除一行