Android Studio报错:已创建列却提示列不存在?
Hey, let's break down what's going on here. Your error log says the contacts table doesn't have a name column, but looking at your code, you did define that column in your CREATE statement. The problem is a typo in your onCreate method—and it's a classic easy-to-miss mistake!
Look at this snippet from your onCreate:
public void onCreate(SQLiteDatabase db) { String create = "CREATE TABLE " + TABLE_CONTACTS + "("+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PH_NO + " TEXT" + ")"; db.execSQL(create2); // <-- Here's the critical mistake! }
You built your correct table creation SQL and stored it in the create variable, but you tried to execute create2 instead. That variable doesn't match the valid SQL you wrote, so the actual table created in your database doesn't have the name or phone_number columns you expected.
Step-by-Step Fixes:
- Fix the typo immediately: Change
db.execSQL(create2);todb.execSQL(create);so your proper table structure gets executed. - Clear the old broken table: Since your app already created a table with the wrong structure, you need to reset it:
- Uninstall your app from the emulator/device, then reinstall it to start fresh.
- Or, increment your database version number (the integer passed to your
SQLiteOpenHelperconstructor) to trigger theonUpgrademethod, which will drop the old table and rebuild it with the correct structure.
Here's the corrected onCreate method for reference:
public void onCreate(SQLiteDatabase db) { String create = "CREATE TABLE " + TABLE_CONTACTS + "("+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_PH_NO + " TEXT" + ")"; db.execSQL(create); // Now using the right variable! }
Once you make these changes, your addContact method should work as expected—since the table will finally have the columns you're trying to insert into.
内容的提问来源于stack exchange,提问作者Abo Ali

