Android Studio中SQLite应用持续崩溃,寻求故障原因及解决办法
分析你的Android SQLite应用崩溃问题
先看你提供的代码,有几个关键错误直接导致了应用崩溃,我帮你逐一拆解:
1. MainActivity中控件初始化的严重错误
你在MainActivity类的成员位置直接初始化控件:
EditText studentid = (EditText) findViewById(R.id.id); EditText studentname = (EditText) findViewById(R.id.name); TextView first = (TextView) findViewById(R.id.first);
这是完全错误的,因为**findViewById必须在setContentView()之后调用**,而且类成员初始化阶段Activity还未完成布局加载,此时调用会直接返回null,后续操作这些控件(比如setText)就会触发NullPointerException导致崩溃。
修复方法:
把控件声明移到类成员区域,初始化操作放在onCreate方法里,并且一定要先调用setContentView加载布局:
public class MainActivity extends Activity { // 先声明控件引用 EditText studentid; EditText studentname; TextView first; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 必须先加载布局文件 setContentView(R.layout.activity_main); // 现在才能安全初始化控件 studentid = (EditText) findViewById(R.id.id); studentname = (EditText) findViewById(R.id.name); first = (TextView) findViewById(R.id.first); } // 后续的addStudent、loadStudents方法逻辑保持不变即可 }
2. SQLite建表语句的语法错误
在MyDBHandler的onCreate方法里,你的建表SQL语句缺少必要的空格,会导致数据库创建失败:
String CREATE_TABLE = "CREATE TABLE" + TABLE_NAME + "(" + COLUMN_ID + "INTEGER PRIMARYKEY," + COLUMN_NAME + "TEXT )";
这里的具体问题:
CREATE TABLE和表名TABLE_NAME之间没有空格,会变成CREATE TABLEStudent,属于SQL语法错误COLUMN_ID和INTEGER之间没有空格,变成StudentIDINTEGER,语法错误PRIMARYKEY应该写成PRIMARY KEY(两个单词分开)COLUMN_NAME和TEXT之间没有空格,变成StudentNametext,语法错误
修复方法:
修正SQL语句,添加必要的空格:
@Override public void onCreate(SQLiteDatabase db) { String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT )"; db.execSQL(CREATE_TABLE); }
3. 其他潜在问题(提前规避后续崩溃)
- 在
updateHandler方法中,直接拼接整数作为查询条件虽然暂时不会崩溃,但存在风险,建议改为参数化查询,同时主键ID不需要更新:
public boolean updateHandler(int ID, String name) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues args = new ContentValues(); args.put(COLUMN_NAME, name); // 用参数化方式传递条件,更安全 return db.update(TABLE_NAME, args, COLUMN_ID + "=?", new String[]{String.valueOf(ID)}) > 0; }
findHandler方法中,字符串拼接查询条件存在SQL注入风险,建议改为参数化查询:
public Student findHandler(String studentname) { String query = "Select * FROM " + TABLE_NAME + " WHERE " + COLUMN_NAME + " = ?"; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query, new String[]{studentname}); Student student = null; if (cursor.moveToFirst()) { student = new Student(); student.setID(cursor.getInt(0)); student.setStudentName(cursor.getString(1)); } cursor.close(); db.close(); return student; }
另外,你提供的Logcat日志里的音频相关错误(AudioFlinger: not enough memory)是系统层面的干扰,和你的SQLite应用崩溃无关,主要问题还是代码里的上述错误。
按照上面的修复方法修改后,你的应用应该能正常运行了。
内容的提问来源于stack exchange,提问作者Vít Vohralík
相关产品推荐
相关产品推荐

