删除数据库中的行不起作用。如何获取我单击的行的ID?

时间:2015-01-20 16:55:59

标签: android database sqlite

每行都有一个ID和电话号码。我知道位置和身份不同。但我通过getitemID获得了该职位的ID。仍然没有工作。
如何获取我点击的行的ID?

              public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read);
    mainListView = (ListView) findViewById( R.id.mainListView );
   // DatabaseHandler db = new DatabaseHandler(this);

    /**
     * CRUD Operations
     * */


    ArrayList<String> planetList = new ArrayList<String>();

    // Reading all contacts

    contacts = db.getAllContacts();

    for (Contact cn : contacts) {
        log = "ID"+cn.getID()+"Phone: " + cn.getPhoneNumber();


        // Writing Contacts to log
        planetList.addAll( Arrays.asList(log) );
    }

    listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
    mainListView.setAdapter( listAdapter );
    registerForContextMenu(mainListView);
}

            public boolean onContextItemSelected(MenuItem item)
       {  
        AdapterView.AdapterContextMenuInfo info =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        try
        {

        //  info.position will give the index of selected item

                        if(item.getTitle()=="DELETE")
                        { 
                            Contact cn= new Contact();

                            //cn._id=info.position+1; 

                        cn._id= Math.abs((int)listAdapter.getItemId(info.position));
                             db.deleteContact(new Contact(cn._id,cn._phone_number));
                            listAdapter.remove(listAdapter.getItem(info.position));

                            listAdapter.notifyDataSetChanged();

                        }  
                        else
                        {
                            return false;
                        }  

                        return true;  
           }  
        catch(Exception e)
        {
                return true;
        }
    }

}  

数据库代码

             import android.content.ContentValues;
         import android.content.Context;
         import android.database.Cursor;
         import android.database.sqlite.SQLiteDatabase;
         import android.database.sqlite.SQLiteOpenHelper;

         import java.util.ArrayList;
         import java.util.List;

         class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
public static final String DATABASE_NAME = "contactsManager";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
public final String KEY_ID = "id";

public  final String KEY_PH_NO = "phone_number";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," +
            KEY_PH_NO + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
void addContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}

void deleteContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    String DELETE_ID= "DELETE FROM " + TABLE_CONTACTS +" WHERE"+" "+ KEY_ID +"="+contact._id;
    db.execSQL(DELETE_ID);

}


// Getting All Contacts
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));

            contact.setPhoneNumber(cursor.getString(1));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}

}

1 个答案:

答案 0 :(得分:0)

您的删除查询不正确。

你应该在“WHERE”之后有一个空格

String DELETE_ID= "DELETE FROM " + TABLE_CONTACTS +"    WHERE"+""+KEY_ID+"="+contact._id; 

您是否可以看到“WHERE”保留字后面没有空格

修改

KEY_ID不应该是id。它应该是您要保存ID的列的名称。但是,你并没有向我们提供这样的信息,所以我们不能说它应该是什么列。

同时检查您的ID并查看它们是否与您在适配器上获得的ID非常匹配。请告诉我们您的插入查询,以便我们更好地为您提供帮助。

<强> EDIT2

你有一个非常混乱的代码让我告诉你。我建议你在继续之前先清除它。但是,当您调用delete方法时,可以尝试使用此方法检索联系人的真实ID:

String s = listAdapter.getItem(info.position);
int id = Integer.parseInt(s.substring(s.indexOf("D")+1,s.indexOf("P")));
db.deleteContact(new Contact(id,cn._phone_number));