Android SQLite. Ошибка столбца не найдена

У приложения нет ошибок кодирования, но он падает при запуске. В LogCat я вижу ошибку, но столбец не найден, но я не могу понять, где проблема. Я провел много исследований, но без успеха. Вот исходный код для моих классов:

Класс MainActivity:

public class MainActivity extends ListActivity {

private StudentOperations studentDBoperation;

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 studentDBoperation = new StudentOperations(this);
 studentDBoperation.open();

 List values = studentDBoperation.getAllStudents();

 // Use the SimpleCursorAdapter to show the
 // elements in a ListView
 ArrayAdapter adapter = new ArrayAdapter(this,
 android.R.layout.simple_list_item_1, values);
 setListAdapter(adapter);
}

public void addUser(View view) {

 ArrayAdapter adapter = (ArrayAdapter) getListAdapter();

 EditText text = (EditText) findViewById(R.id.editText1);
 EditText text1 = (EditText) findViewById(R.id.editText2);
 Student stud = studentDBoperation.addStudent(text.getText().toString(),text1.getText().toString());

 adapter.add(stud);

}

public void deleteFirstUser(View view) {

 ArrayAdapter adapter = (ArrayAdapter) getListAdapter();
 Student stud = null;

 if (getListAdapter().getCount() > 0) {
 stud = (Student) getListAdapter().getItem(0);
 studentDBoperation.deleteStudent(stud);
 adapter.remove(stud);
 }

}

@Override
protected void onResume() {
 studentDBoperation.open();
 super.onResume();
}

@Override
protected void onPause() {
 studentDBoperation.close();
 super.onPause();
}

}

Студенческий класс:

public class Student {

private int id;
private String name;
private String password;

public long getId() {
 return id;
}

public void setId(int id) {
 this.id = id;
}

public String getName() {
 return this.name;
}

public void setName(String name) {
 this.name = name;
}

@Override
public String toString() {
 return name;
}

public String getPassword() {
 return this.password;
}

public void setPassword(String password) {
 this.password = password;
}

}

Класс ученика:

public class StudentOperations {

// Database fields
private DataBaseWrapper dbHelper;
private String[] STUDENT_TABLE_COLUMNS = { DataBaseWrapper.STUDENT_ID, DataBaseWrapper.STUDENT_NAME, DataBaseWrapper.STUDENT_PASSWORD };
private SQLiteDatabase database;

public StudentOperations(Context context) {
 dbHelper = new DataBaseWrapper(context);
}

public void open() throws SQLException {
 database = dbHelper.getWritableDatabase();
}

public void close() {
 dbHelper.close();
}

public Student addStudent(String name,String password) {

 ContentValues values = new ContentValues();

 values.put(DataBaseWrapper.STUDENT_NAME, name);
 values.put(DataBaseWrapper.STUDENT_PASSWORD, password);

 long studId = database.insert(DataBaseWrapper.STUDENTS, null, values);

 // now that the student is created return it ...
 Cursor cursor = database.query(DataBaseWrapper.STUDENTS,
 STUDENT_TABLE_COLUMNS, DataBaseWrapper.STUDENT_ID + " = "
 + studId, null, null, null, null);

 cursor.moveToFirst();

 Student newComment = parseStudent(cursor);
 cursor.close();
 return newComment;
}

public void deleteStudent(Student comment) {
 long id = comment.getId();
 System.out.println("Comment deleted with id: " + id);
 database.delete(DataBaseWrapper.STUDENTS, DataBaseWrapper.STUDENT_ID
 + " = " + id, null);
}

public List getAllStudents() {
 List students = new ArrayList();

 Cursor cursor = database.query(DataBaseWrapper.STUDENTS,
 STUDENT_TABLE_COLUMNS, null, null, null, null, null);

 cursor.moveToFirst();
 while (!cursor.isAfterLast()) {
 Student student = parseStudent(cursor);
 students.add(student);
 cursor.moveToNext();
 }

 cursor.close();
 return students;
}

private Student parseStudent(Cursor cursor) {
 Student student = new Student();
 student.setId((cursor.getInt(0)));
 student.setName(cursor.getString(1));
 return student;
}

}

Класс DataBaseWrapper:

public class DataBaseWrapper extends SQLiteOpenHelper {

public static final String STUDENTS = "Students";
public static final String STUDENT_ID = "_id";
public static final String STUDENT_NAME = "name";
public static final String STUDENT_PASSWORD = "password";

private static final String DATABASE_NAME = "Students.db";
private static final int DATABASE_VERSION = 1;

// creation SQLite statement
private static final String DATABASE_CREATE = "create table " + STUDENTS
 + "(" + STUDENT_ID + " integer primary key autoincrement, " + STUDENT_NAME + " text not null " + STUDENT_PASSWORD + " text not null ); ";

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

@Override
public void onCreate(SQLiteDatabase db) {
 db.execSQL(DATABASE_CREATE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 // you should do some logging in here
 // ..

 db.execSQL("DROP TABLE IF EXISTS " + STUDENTS);
 onCreate(db);
}

}

Ошибка LogCat:

11-05 21: 51: 02.430: D/AbsListView (26729): Get MotionRecognitionManager 11-05 21: 51: 02.470: E/SQLiteLog (26729): (1) нет такого столбца: name 11-05 21: 51: 02.470: D/AndroidRuntime (26729): выключение VM 11-05 21: 51: 02.470: W/dalvikvm (26729): threadid = 1: выход из потока с неперехваченным исключением (группа = 0x410762a0) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): FATAL EXCEPTION: main 11-05 21: 51: 02.480: E/AndroidRuntime (26729): java.lang.RuntimeException: не удается запустить Activity ComponentInfo {com.example.sqlite/com.example.sqlite.MainActivity}: android.database.sqlite.SQLiteException: нет такого столбца: name (код 1): при компиляции: SELECT _id, name, password FROM Students 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.app.ActivityThread.access $ 60 0 (ActivityThread.java:140) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1227) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.os.Handler.dispatchMessage(Handler.java:99) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.os.Looper.loop(Looper.java: 137) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.app.ActivityThread.main(ActivityThread.java:4898) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): в java.lang.reflect.Method.invokeNative(Native Method) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at java.lang.reflect.Method.invoke(Method.java:511) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1006) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at dalvik.system.NativeStart.main (родной метод) 11-05 21: 51: 02.480: E/AndroidRun time (26729): Caused by: android.database.sqlite.SQLiteException: нет такого столбца: name (код 1):, при компиляции: SELECT _id, name, password FROM Students 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.database.sqlite.SQLiteConnection.nativePrepareStatement (собственный метод) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1012 ) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:623) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): в android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.database.sqlite.SQLiteProgram. (SQLiteProgram.java:58) 11 -05 21: 51: 02.480: E/AndroidRuntime (26729): at android.database.sqlite.SQLiteQuery. (SQLiteQuery.java:37) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): у android. database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCu rsorDriver.java:44) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java: 1032) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at com.example.sqlite.StudentOperations.getAllStudents(StudentOperations.java:62) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at com.example.sqlite.MainActivity.onCreate(MainActivity. java: 23) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.app.Activity.performCreate(Activity.java:5206) 11-05 21: 51: 02.480: E/AndroidRuntime (26729): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083) 11-05 21:51:02 .480: E/AndroidRuntime (26729): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064) 11-05 21: 51: 02.480: E/AndroidRuntime (26729):... еще 11

3 ответа

Аналогичная ошибка возникла у меня, когда я изменил (т.е. Добавил дополнительный столбец) в свой файл Databasehandler (DataBaseWrapper в вашем случае). Я нашел, что это было разрешено после того, как я установил мое приложение с устройства, а затем снова установил его. Посмотрите на него.


В инструкции DATABASE_CREATE не указано запятая между определениями столбцов имени и пароля.


Вам нужно добавить запятую и удалить точку с запятой из инструкции create. Попробуйте изменить:

// creation SQLite statement
private static final String DATABASE_CREATE = "create table " + STUDENTS
 + "(" + STUDENT_ID + " integer primary key autoincrement, " + STUDENT_NAME + " text not null " + STUDENT_PASSWORD + " text not null ); ";

чтобы:

// creation SQLite statement
private static final String DATABASE_CREATE = "create table " + STUDENTS
 + "(" + STUDENT_ID + " integer primary key autoincrement, " + STUDENT_NAME + " text not null, " + STUDENT_PASSWORD + " text not null )";

licensed under cc by-sa 3.0 with attribution.