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

如何判断录音是否为空?解决保存按钮验证点击崩溃问题

问题解决方案

一、修复保存按钮崩溃问题

你的代码崩溃大概率出自以下几个点,对应修复方式如下:

  1. 确保集合listfiles已初始化
    如果listfiles没有提前执行listfiles = new ArrayList<>()初始化,调用listfiles.size()会直接抛出NullPointerException,要在使用集合前完成初始化:
// 可在类成员变量声明或方法开头添加
List<File> listfiles = new ArrayList<>();
  1. 避免strreminder_txt空指针异常
    直接调用strreminder_txt.isEmpty()前,必须先判断strreminder_txt是否为null,否则会触发崩溃:
// 替换原文本空值判断逻辑
if (strreminder_txt == null || strreminder_txt.trim().isEmpty()) {
    // 后续提示或处理逻辑
}
  1. 确认btnsaveReminder控件已绑定
    要确保btnsaveReminder已经通过findViewById完成控件绑定,否则调用getText()会崩溃,使用前增加非空判断:
if (btnsaveReminder != null && btnsaveReminder.getText().equals("Update")) {
    updateReminder(...);
} else {
    saveReminder(...);
}

二、正确实现输入验证逻辑

原代码用mediaRecorder==null&&mediaPlayer==null判断是否有录音的逻辑错误,应该直接校验录音文件是否存在且有效,结合文本输入状态完成验证:

完整修正后的验证代码

File fileName = new File(finalpath);
Log.e("FileName::", "" + fileName);

// 兜底初始化集合(防止未初始化导致崩溃)
if (listfiles == null) {
    listfiles = new ArrayList<>();
}

// 文件列表更新逻辑保持不变
if (listfiles.size() == 0) {
    listfiles.add(fileName);
} else {
    if (notifiadapeterpos < listfiles.size()) {
        listfiles.set(notifiadapeterpos, fileName);
    } else {
        listfiles.add(fileName);
    }
}
notificationPart = prepareFilePart1(listfiles);

// 核心验证:文本非空 或 录音文件有效,二者满足其一即可
boolean hasValidText = strreminder_txt != null && !strreminder_txt.trim().isEmpty();
boolean hasValidAudio = isAudioFileValid(fileName);

if (!hasValidText && !hasValidAudio) {
    Toast.makeText(RegisterMember.this, "请输入提醒文本或录制提醒音频", Toast.LENGTH_SHORT).show();
} else {
    if (btnsaveReminder != null && btnsaveReminder.getText().equals("Update")) {
        updateReminder(strreminder_txt, strreminder_time, fileName, finalStrcheckDialy, notificationPart);
    } else {
        saveReminder(strreminder_txt, strreminder_time, fileName, finalStrcheckDialy, notificationPart);
    }
}

三、判断录音文件是否为空(有效)

实现一个工具方法,从文件存在性和文件大小两个维度判断录音文件是否有效:

private boolean isAudioFileValid(File audioFile) {
    // 检查文件存在,且文件大小大于0(避免生成空录音文件)
    return audioFile != null && audioFile.exists() && audioFile.length() > 0;
}

说明:

  • audioFile.exists():确保录音文件确实被创建在指定路径
  • audioFile.length() > 0:过滤掉用户点击录制但立刻停止生成的空文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:10:36