我试图使用上下文菜单来删除和编辑我的 sqlite 数据库数据。现在问题是我选择的任何数据,id 总是 0。所以我总是会删除,编辑第一个数据。谁能帮我解决这个问题?这是我的代码
public class DashboardActivity extends ListActivity implements OnClickListener {
Intent intent;
TextView eventId;
EventController controller = new EventController(this);
UserFunctions userFunctions;
Button btnLogout;
TabHost th;
Button show;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status in database
userFunctions = new UserFunctions();
if (userFunctions.isUserLoggedIn(getApplicationContext())) {
setContentView(R.layout.activity_main);
show = (Button) findViewById(R.id.button1);
show.setOnClickListener(this);
// create tabs
th = (TabHost) findViewById(R.id.tabhost);
th.setup();
TabSpec specs = th.newTabSpec("tag1"); // setting up a tabspec in
// tabhost(th) call it tag1
specs.setContent(R.id.tab1);// set content of "tab1" xml
specs.setIndicator("Event");
th.addTab(specs);
specs = th.newTabSpec("tag2"); // setting up a tabspec in
// tabhost(th) call it tag1
specs.setContent(R.id.tab2);// set content of "tab1" xml
specs.setIndicator("Friend");
th.addTab(specs);
ArrayList<HashMap<String, String>> eventList = controller
.getAllEvents();
if (eventList.size() != 0) {
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
eventId = (TextView) view.findViewById(R.id.eventId);
String valEventId = eventId.getText().toString();
Intent objIndent = new Intent(getApplicationContext(),
EventPage.class);
objIndent.putExtra("eventId", valEventId);
startActivity(objIndent);
}
});
ListAdapter adapter = new SimpleAdapter(DashboardActivity.this,
eventList, R.layout.view_event_entry, new String[] {
"eventId", "eventName", "eventDate" },
new int[] { R.id.eventId, R.id.eventName,
R.id.eventDate });
setListAdapter(adapter);
registerForContextMenu(lv);
}
} else {
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), Login.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_user:
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), Login.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getApplicationContext(), AddEvent.class);
startActivity(objIntent);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
String[] menuItems = getResources().getStringArray(R.array.menu);
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
int menuItemIndex = item.getItemId();
eventId = (TextView) findViewById(R.id.eventId);
if (menuItemIndex == 0) {
String valEventId = eventId.getText().toString();
Intent objIndent = new Intent(getApplicationContext(),
EditEvent.class);
objIndent.putExtra("eventId", valEventId);
startActivity(objIndent);
} else if (menuItemIndex == 1) {
String valEventId2 = eventId.getText().toString();
controller.deleteEvent(valEventId2);
Intent objIntent = new Intent(getApplicationContext(),
DashboardActivity.class);
startActivity(objIntent);
}
return true;
}
这是我的数据库类:
public class EventController extends SQLiteOpenHelper {
private static final String LOGCAT = null;
public EventController(Context applicationcontext) {
super(applicationcontext, "androidsqlite.db", null, 1);
Log.d(LOGCAT, "Created");
}
public void onOpen(SQLiteDatabase database){
if (!database.isReadOnly()) {
// Enable foreign key constraints
database.execSQL("PRAGMA foreign_keys=ON;");
}
}
@Override
// create table for the database
public void onCreate(SQLiteDatabase database) {
String query, query1, query2;
query = "CREATE TABLE events ( eventId INTEGER PRIMARY KEY, eventName TEXT, eventDate TEXT, eventLocation TEXT, eventDescription TEXT);";
query1 = "CREATE TABLE friends ( friendId INTEGER PRIMARY KEY, friendName TEXT, friendNumber TEXT, friendEmail TEXT, friendSpending DOUBLE, friendEvent INTEGER, FOREIGN KEY(friendEvent) REFERENCES events(eventId) ON DELETE CASCADE);";
query2 = "CREATE TABLE expenses ( expenseId INTEGER PRIMARY KEY, expenseName TEXT, expenseType TEXT, expensePrice DOUBLE, expenseFriend INTEGER, FOREIGN KEY(expenseFriend) REFERENCES friends(friendId) ON DELETE CASCADE);";
database.execSQL(query);
database.execSQL(query1);
database.execSQL(query2);
Log.d(LOGCAT, "events Created");
Log.d(LOGCAT, "friends Created");
Log.d(LOGCAT, "expenses Created");
}
@Override
// drop the database and reset if required
public void onUpgrade(SQLiteDatabase database, int version_old,
int current_version) {
String query, query1;
query = "DROP TABLE IF EXISTS events";
query1 = "DROP TABLE IF EXISTS friends";
database.execSQL(query);
database.execSQL(query1);
onCreate(database);
}
public void insertEvent(HashMap<String, String> queryValues) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("eventName", queryValues.get("eventName"));
values.put("eventDate", queryValues.get("eventDate"));
values.put("eventLocation", queryValues.get("eventLocation"));
values.put("eventDescription", queryValues.get("eventDescription"));
database.insert("events", null, values);
database.close();
}
public void insertFriend(HashMap<String, String> queryValues) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("friendEvent", queryValues.get("eventId"));
values.put("friendName", queryValues.get("friendName"));
values.put("friendNumber", queryValues.get("friendNumber"));
values.put("friendEmail", queryValues.get("friendEmail"));
values.put("friendSpending", 0);
database.insert("friends", null, values);
database.close();
}
public int updateEvent(HashMap<String, String> queryValues) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("eventName", queryValues.get("eventName"));
values.put("eventLocation", queryValues.get("eventLocation"));
values.put("eventDescription", queryValues.get("eventDescription"));
return database.update("events", values, "eventId" + " = ?",
new String[] { queryValues.get("eventId") });
// String updateQuery =
// "Update words set txtWord='"+word+"' where txtWord='"+ oldWord +"'";
// Log.d(LOGCAT,updateQuery);
// database.rawQuery(updateQuery, null);
// return database.update("words", values, "txtWord = ?", new String[]
// { word });
}
public int updateFriend(HashMap<String, String> queryValues) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("friendName", queryValues.get("friendName"));
values.put("friendNumber", queryValues.get("friendNumber"));
values.put("friendEmail", queryValues.get("friendEmail"));
return database.update("friends", values, "friendId" + " = ?",
new String[] { queryValues.get("friendId") });
// String updateQuery =
// "Update words set txtWord='"+word+"' where txtWord='"+ oldWord +"'";
// Log.d(LOGCAT,updateQuery);
// database.rawQuery(updateQuery, null);
// return database.update("words", values, "txtWord = ?", new String[]
// { word });
}
public void deleteEvent(String id) {
Log.d(LOGCAT, "delete");
SQLiteDatabase database = this.getWritableDatabase();
String deleteQuery = "DELETE FROM events where eventId='" + id + "'";
Log.d("query", deleteQuery);
database.execSQL(deleteQuery);
}
public void deleteFriend(String id) {
Log.d(LOGCAT, "delete");
SQLiteDatabase database = this.getWritableDatabase();
String deleteQuery = "DELETE FROM friends where friendId='" + id + "'";
Log.d("query", deleteQuery);
database.execSQL(deleteQuery);
}
public ArrayList<HashMap<String, String>> getAllEvents() {
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM events";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("eventId", cursor.getString(0));
map.put("eventName", cursor.getString(1));
map.put("eventDate", cursor.getString(2));
wordList.add(map);
} while (cursor.moveToNext());
}
// return contact list
return wordList;
}
public ArrayList<HashMap<String, String>> getAllFriends(
HashMap<String, String> queryValues) {
ArrayList<HashMap<String, String>> wordList;
ContentValues values = new ContentValues();
values.put("friendEvent", queryValues.get("eventId"));
wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM friends WHERE friendEvent = "
+ queryValues.get("eventId");
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("friendId", cursor.getString(0));
map.put("friendName", cursor.getString(1));
map.put("friendSpending", "RM " + cursor.getString(4));
wordList.add(map);
} while (cursor.moveToNext());
}
// return contact list
return wordList;
}
public HashMap<String, String> getEventInfo(String id) {
HashMap<String, String> wordList = new HashMap<String, String>();
SQLiteDatabase database = this.getReadableDatabase();
String selectQuery = "SELECT * FROM events where eventId='" + id + "'";
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
// HashMap<String, String> map = new HashMap<String, String>();
wordList.put("eventName", cursor.getString(1));
wordList.put("eventDate", cursor.getString(2));
wordList.put("eventLocation", cursor.getString(3));
wordList.put("eventDescription", cursor.getString(4));
// wordList.add(map);
} while (cursor.moveToNext());
}
return wordList;
}
public HashMap<String, String> getFriendInfo(String id) {
HashMap<String, String> wordList = new HashMap<String, String>();
SQLiteDatabase database = this.getReadableDatabase();
String selectQuery = "SELECT * FROM friends where friendId='" + id
+ "'";
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
// HashMap<String, String> map = new HashMap<String, String>();
wordList.put("friendName", cursor.getString(1));
wordList.put("friendNumber", cursor.getString(2));
wordList.put("friendEmail", cursor.getString(3));
// wordList.add(map);
} while (cursor.moveToNext());
}
return wordList;
}