Android - 使用上下文菜单编辑和删除sqlite中的数据

时间:2013-11-06 12:08:21

标签: android sqlite contextmenu android-contextmenu

我试图利用上下文菜单删除和编辑我的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;
}

1 个答案:

答案 0 :(得分:0)

更改为:

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    // Get the position of the pressed item from the Adapter
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
    itemPos = info.position; // global variable
    if(itemPos != 0){
        menu.setHeaderTitle("Choose");
        menu.add(0, v.getId(), 0, "Edit");
        menu.add(0, v.getId(), 0, "Delete");
    }

}


@Override
public boolean onContextItemSelected(MenuItem item) {

    if (item.getTitle() == "Delete") {
        deleteReport(itemPos);
    } else if (item.getTitle() == "Edit") {
        editReport(itemPos);
    } else {
        return false;
    }
    return true;
}

public void deleteReport(int id){

// your delete code

}

public void editReport(int id){

//your edit code

}

这对我有用。