我有一个无法应对的问题。我从数据库本身下载有关玩家,两列,id和玩家姓名的数据(在DatabaseHelper类中):
public ArrayList<HashMap<String, String>> getAllPlayers() {
try {
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
SQLiteDatabase db = this.getReadableDatabase();
String sqlSelect = "SELECT " + _id + ", " +
columnPlayerName + " FROM " + TABLE_NAME;
Cursor select = db.rawQuery(sqlSelect, null);
if(select != null) {
if(select.moveToFirst()) {
do {
map = new HashMap<String, String>();
map.put("_id", select.getString(0));
map.put("PLAYER_NAME", select.getString(1));
arraylist.add(map);
}
while(select.moveToNext());
}
}
select.close();
db.close();
return arraylist;
}
catch (Exception e) {
return null;
}
}
好的,然后将列表中显示的数据下载到两列(MainActivity类):
public class MainActivity extends AppCompatActivity {
ListView playersList;
DatabaseHelperPlayer playerDb = new DatabaseHelperPlayer(this);
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_players_list_view, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete_id:
TextView tv = (TextView) findViewById(R.id.playerNameListView);
String n = tv.getText().toString();
playerDb.deletePlayer(info.id);
}
return super.onContextItemSelected(item);
}
private void playersListView() {
ArrayList<HashMap<String, String>> playerList = playerDb.getAllPlayers();
playersList = (ListView) findViewById(R.id.listPlayer);
SimpleAdapter adt = new SimpleAdapter(this, playerList, R.layout.row_players, new String[]{"_id", "PLAYER_NAME"}, new int[]{R.id.id, R.id.playerNameListView});
playersList.setAdapter(adt);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_players);
playersListView();
registerForContextMenu(playersList);
}
}
当您按住列表上的项目时,在我选择删除时显示菜单,运行我应该从数据库中删除列表中所选行的方法。不幸的是,这种情况并没有发生。我不能处理它。请帮忙。
方法删除:
public Cursor deletePlayer(long id) {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "DELETE FROM " + TABLE_NAME + " WHERE " + columnPlayerName + " = " + id;
Cursor delete = db.rawQuery(sql, null);
if(delete != null) {
delete.moveToFirst();
}
return delete;
}
答案 0 :(得分:2)
不要使用rawQuery来执行删除。试试这个:
db.execSQL(sql);
而不是
Cursor delete = db.rawQuery(sql, null);
或直接使用db.delete方法。请参阅此处了解API:http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
答案 1 :(得分:1)
没关系?
public void deletePlayer(long id) {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "DELETE FROM " + TABLE_NAME + " WHERE " + columnPlayerName + " = " + id;
db.execSQL(sql);
}
但遗憾的是我不知道如何获取要删除的列表中的ID项。你能帮忙吗?