Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/187.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android-使用上下文菜单编辑和删除sqlite中的数据_Android_Sqlite_Contextmenu_Android Contextmenu - Fatal编程技术网

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

Android-使用上下文菜单编辑和删除sqlite中的数据,android,sqlite,contextmenu,android-contextmenu,Android,Sqlite,Contextmenu,Android Contextmenu,我试图利用上下文菜单删除和编辑我的sqlite数据库数据。我希望我的应用程序检测我从列表中选择的项目,并将始终删除、编辑列表中的选定项目。但问题是,应用程序只是从列表中删除/编辑id为0的第一项。有人能帮我解决这个问题吗? 这是我的密码: public class DashboardActivity extends ListActivity implements OnClickListener { Intent intent; TextView eventId; EventController

我试图利用上下文菜单删除和编辑我的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;
}
公共类DashboardActivity扩展ListActivity实现OnClickListener{
意图;
TextView事件ID;
EventController=新的EventController(此);
用户函数用户函数;
钮扣痛风;
烟草;
按钮显示;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
/**
*应用程序的仪表板屏幕
* */
//检查数据库中的登录状态
userFunctions=新的userFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
setContentView(R.layout.activity_main);
show=(按钮)findViewById(R.id.button1);
show.setOnClickListener(这个);
//创建选项卡
th=(TabHost)findviewbyd(R.id.TabHost);
th.setup();
TabSpec specs=th.newTabSpec(“tag1”);//在中设置TabSpec
//tabhost(th)称之为tag1
specs.setContent(R.id.tab1);//设置“tab1”xml的内容
规格设置指示器(“事件”);
th.addTab(规格);
specs=th.newTabSpec(“tag2”);//在中设置选项卡spec
//tabhost(th)称之为tag1
specs.setContent(R.id.tab2);//设置“tab1”xml的内容
规格设置指示器(“朋友”);
th.addTab(规格);
ArrayList eventList=控制器
.getAllEvents();
if(eventList.size()!=0){
ListView lv=getListView();
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
eventId=(TextView)view.findViewById(R.id.eventId);
字符串valEventId=eventId.getText().toString();
Intent objIndent=新的Intent(getApplicationContext(),
EventPage.class);
objIndent.putExtra(“eventId”,valEventId);
星形触觉(明显);
}
});
ListAdapter=新的SimpleAdapter(DashboardActivity.this,
事件列表,R.layout.view\u事件\u条目,新字符串[]{
“eventId”、“eventName”、“eventDate”},
新int[]{R.id.eventId,R.id.eventName,
R.id.eventDate});
setListAdapter(适配器);
registerForContextMenu(lv);
}
}否则{
//用户未登录显示登录屏幕
Intent login=newintent(getApplicationContext(),login.class);
login.addFlags(Intent.FLAG\u ACTIVITY\u CLEAR\u TOP);
startActivity(登录);
//关闭仪表板屏幕
完成();
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单项充气,以便在操作栏中使用
MenuInflater充气机=getMenuInflater();
充气机。充气(右菜单。主菜单,菜单);
返回super.onCreateOptions菜单(菜单);
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目上的按下
开关(item.getItemId()){
案例R.id.action\u用户:
logoutUser(getApplicationContext());
Intent login=newintent(getApplicationContext(),login.class);
login.addFlags(Intent.FLAG\u ACTIVITY\u CLEAR\u TOP);
startActivity(登录);
//关闭仪表板屏幕
完成();
返回true;
违约:
返回super.onOptionsItemSelected(项目);
}
}
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
Intent objIntent=newintent(getApplicationContext(),AddEvent.class);
星形触觉;
}
@凌驾
public void onCreateContextMenu(ContextMenu,视图v,
上下文菜单信息(menuInfo){
字符串[]menuItems=getResources().getStringArray(R.array.menu);
对于(int i=0;i
这是我的数据库类:

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;
}
public类EventController扩展SQLiteOpenHelper{
私有静态最终字符串LOGCAT=null;
公共事件控制器(上下文应用程序上下文){
super(applicationcontext,“androidsqlite.db”,null,1);
Log.d(LOGCAT,“创建”);
}
公共void onOpen(SQLiteDatabase数据库){
如果(!database.isReadOnly()){
//启用外键约束
execSQL(“PRAGMA foreign_keys=ON;”;
}
}
@凌驾
//为数据库创建表
public void onCreate(SQLiteDatabase){
字符串查询,查询1,查询2;
query=“创建表事件(eventId整数主键、eventName文本、eventDate文本、eventLocation文本、eventDescription文本);”;
query1=“创建表fri
@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

}