You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击联系人元素后App崩溃,SQL语法错误致详情无法显示

问题解决:点击联系人跳转详情页崩溃

崩溃原因

Logcat报错显示SQL语句存在语法错误:near "FROMCONTACT_TABLEWHEREID": syntax error,生成的错误SQL为SELECT *FROMCONTACT_TABLEWHEREID="1"——SQL关键字与表名/字段名之间缺少必要空格,触发SQLiteException,导致详情页Activity无法正常初始化,最终App崩溃。

解决方案

1. 修正详情页的单个联系人查询SQL

推测你在Activity_Contact_details中查询联系人详情时,拼接SQL未加空格,同时建议使用参数化查询避免语法错误和SQL注入:

// 正确的单联系人查询方法(示例)
public ModelContact getContactById(int contactId) {
    SQLiteDatabase db = getReadableDatabase();
    ModelContact contact = null;
    
    // 确保每个关键字前后添加空格,并用?作为参数占位符
    String selectQuery = "SELECT * FROM " + Constants.TABLE_NAME + " WHERE ID = ?";
    // 通过rawQuery的第二个参数传递参数值,避免字符串拼接问题
    Cursor cursor = db.rawQuery(selectQuery, new String[]{String.valueOf(contactId)});
    
    if (cursor.moveToFirst()) {
        // 解析Cursor数据到ModelContact对象
        contact = new ModelContact();
        contact.setId(cursor.getInt(cursor.getColumnIndex("ID")));
        // 补充其他字段的解析逻辑,比如姓名、电话等
    }
    
    // 关闭Cursor和数据库连接,避免资源泄漏
    cursor.close();
    db.close();
    return contact;
}

2. 修正全局查询SQL(可选但推荐)

你提供的getAllDta方法中,SQL也存在空格缺失问题(*FROM应改为* FROM),修正后避免后续潜在问题:

public ArrayList<ModelContact> getAllData(){
    SQLiteDatabase db= getReadableDatabase();       
    ArrayList<ModelContact> arraylist=new ArrayList<>();    
    // 修正*与FROM之间的空格
    String selectQuery="SELECT * FROM "+ Constants.TABLE_NAME ;  
    Cursor cursor =db.rawQuery(selectQuery,null);
    
    // 补充Cursor解析和数据添加逻辑
    // ...
    
    cursor.close();
    db.close();
    return arraylist;
}

3. 验证ID传递有效性

确认点击事件中传递的id是有效的联系人ID数值,避免传递null或非整数类型值导致SQL解析错误。

内容的提问来源于stack exchange,提问作者hmmm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 21:22:49