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

Android Studio中Firebase数据库添加食物按钮点击崩溃求助

Firebase数据库添加数据时应用崩溃问题排查与解决

我最近在Android Studio里用Firebase Realtime Database开发食物管理应用,遇到了个头疼的问题:输入食物名称后点击添加按钮,应用直接崩溃,数据也没写入数据库;但空着食物名称点按钮时,提示"Please enter a food name"的Toast能正常弹出。下面是我的代码、Logcat日志,以及排查出的问题和解决办法:

我的代码

public class addFood extends AppCompatActivity { 
EditText editTextName;
EditText editTextBestBefore;
Button buttonAddFood;
Spinner spinnerCategory;
DatabaseReference foodDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_food);
    foodDatabase = FirebaseDatabase.getInstance().getReference("food");
    editTextName =(EditText)(findViewById(R.id.editTextName));
    editTextBestBefore =(EditText)(findViewById(R.id.editTextBestBefore));
    buttonAddFood =(Button) (findViewById(R.id.buttonAddFood));
    spinnerCategory =(Spinner) (findViewById(R.id.spinnerCategory));
    buttonAddFood.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addFood();
        }
    });
}
private void addFood() 
{
    String foodName = editTextName.getText().toString().trim();
    String bestBefore = editTextBestBefore.getText().toString().trim();
    String category = spinnerCategory.getSelectedItem().toString();
    if (!TextUtils.isEmpty(foodName)){
        String id = foodDatabase.push().getKey();
        food food = new food(id,foodName, bestBefore, category);
        foodDatabase.child(id).setValue(food);
        Toast.makeText(this, "food added!", Toast.LENGTH_LONG).show();
    } else{
        Toast.makeText(this, "Please enter a food name", Toast.LENGTH_LONG).show();
    }
}
}

Logcat日志

01-16 15:28:57.972 27506-27506/com.virtual.a2018fridge I/FA: App measurement is starting up, version: 11020
01-16 15:28:57.973 27506-27506/com.virtual.a2018fridge I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
01-16 15:28:58.032 27506-27506/com.virtual.a2018fridge V/FA: Collection enabled
01-16 15:28:58.033 27506-27506/com.virtual.a2018fridge V/FA: App package, google app id: com.virtual.a2018fridge, 1:203952876063:android:ae6871bb1651394b
01-16 15:28:58.035 27506-27506/com.virtual.a2018fridge I/FA: To enable faster debug mode event logging run: adb shell setprop debug.firebase.analytics.app com.virtual.a2018fridge
01-16 15:28:58.035 27506-27506/com.virtual.a2018fridge D/FA: Debug-level message logging enabled
01-16 15:28:58.145 27506-27506/com.virtual.a2018fridge V/FA: Registered activity lifecycle callback
01-16 15:28:58.272 27506-27625/com.virtual.a2018fridge V/FA: Using measurement service
01-16 15:28:58.287 27506-27625/com.virtual.a2018fridge V/FA: Connecting to remote service
01-16 15:28:58.348 27506-27625/com.virtual.a2018fridge V/FA: Using measurement service
01-16 15:28:58.348 27506-27625/com.virtual.a2018fridge V/FA: Connection attempt already in progress
01-16 15:28:59.474 27506-27506/com.virtual.a2018fridge V/FA: onActivityCreated
01-16 15:29:01.984 27506-27625/com.virtual.a2018fridge V/FA: Using measurement service
01-16 15:29:01.984 27506-27625/com.virtual.a2018fridge V/FA: Connection attempt already in progress
01-16 15:29:01.989 27506-27625/com.virtual.a2018fridge V/FA: Activity resumed, time: 329370286
01-16 15:29:01.993 27506-27625/com.virtual.a2018fridge I/FA: Tag Manager is not found and thus will not be used
01-16 15:29:02.001 27506-27625/com.virtual.a2018fridge D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_screen_class(_sc)=addFood, firebase_screen_id(_si)=3652847265616890340}]
01-16 15:29:02.030 27506-27625/com.virtual.a2018fridge V/FA: Using measurement service
01-16 15:29:02.030 27506-27625/com.virtual.a2018fridge V/FA: Connection attempt already in progress
01-16 15:29:03.231 27506-27625/com.virtual.a2018fridge D/FA: Connected to remote service
01-16 15:29:03.232 27506-27625/com.virtual.a2018fridge V/FA: Processing queued up service tasks: 4
01-16 15:29:03.981 17286-27703/? V/FA-SVC: Logging event: origin=auto,name=screen_view(_vs),params=Bundle[{firebase_event_origin(_o)=auto, firebase_screen_class(_sc)=addFood, firebase_screen_id(_si)=3652847265616890340}]
01-16 15:29:04.047 17286-27703/? V/FA-SVC: Saving event, name, data size: screen_view(_vs), 52
01-16 15:29:04.057 17286-27703/? V/FA-SVC: Event recorded: Event{appId='com.virtual.a2018fridge', name='screen_view(_vs)', params=Bundle[{firebase_event_origin(_o)=auto, firebase_screen_class(_sc)=addFood, firebase_screen_id(_si)=3652847265616890340}]}
01-16 15:29:04.063 17286-27703/? V/FA-SVC: Upload scheduled in approximately ms: 978689
01-16 15:29:04.097 17286-27703/? V/FA-SVC: Scheduling upload with GcmTaskService
01-16 15:29:04.098 17286-27703/? V/FA-SVC: Scheduling task with Gcm. Time978689
01-16 15:29:04.106 17286-27703/? V/FA-SVC: Background event processing time, ms: 133
01-16 15:29:07.348 27772-27772/? I/FA: App measurement is starting up, version: 11020
01-16 15:29:07.349 27772-27772/? I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
01-16 15:29:07.370 27772-27772/? V/FA: Collection enabled
01-16 15:29:07.371 27772-27772/? V/FA: App package, google app id: com.whatsapp, 1:293955441834:android:7373a2d0bdfa3228
01-16 15:29:07.372 27772-27772/? I/FA: To enable faster debug mode event logging run: adb shell setprop debug.firebase.analytics.app com.whatsapp
01-16 15:29:07.372 27772-27772/? D/FA: Debug-level message logging enabled
01-16 15:29:07.388 27772-27772/? V/FA: Registered activity lifecycle callback
01-16 15:29:07.415 27772-27818/? V/FA: Using measurement service
01-16 15:29:07.419 27772-27818/? V/FA: Connecting to remote service
01-16 15:29:07.439 27772-27818/? V/FA: Using measurement service
01-16 15:29:07.439 27772-27818/? V/FA: Connection attempt already in progress
01-16 15:29:08.026 27772-27818/? D/FA: Connected to remote service
01-16 15:29:08.026 27772-27818/? V/FA: Processing queued up service tasks: 2
01-16 15:29:09.150 27506-27625/com.virtual.a2018fridge V/FA: Inactivity, disconnecting from the service
[ 01-16 15:29:09.339 27506:27506 W/ ]
Unable to open '/system/framework/prcui-config.jar': No such file or directory
01-16 15:29:11.535 17286-27791/? D/FA-SVC: Got package replaced intent: com.virtual.a2018fridge

问题排查与解决

从现象来看,空名称时逻辑正常执行,说明addFood()里的判断没问题,崩溃肯定出在if块内的代码。最可能的问题出在**food实体类**上,Firebase Realtime Database序列化对象时有几个硬性要求:

  • 类名遵循Java规范:你的实体类叫food,首字母小写,虽然语法合法,但Firebase序列化时可能出现匹配问题,建议改成Food。
  • 必须有公共无参构造函数:Firebase需要通过无参构造函数实例化对象,若只写了带参构造函数,会导致序列化失败崩溃。
  • 字段有公共访问权限:要么把字段设为public,要么给每个字段添加公共getter方法,否则Firebase无法读取字段值。

修正后的Food类示例

public class Food {
    public String id;
    public String foodName;
    public String bestBefore;
    public String category;

    // 必须的无参构造函数
    public Food() {}

    // 带参数的构造函数
    public Food(String id, String foodName, String bestBefore, String category) {
        this.id = id;
        this.foodName = foodName;
        this.bestBefore = bestBefore;
        this.category = category;
    }

    // 如果字段不是public,需添加getter方法
    public String getId() {
        return id;
    }

    public String getFoodName() {
        return foodName;
    }

    public String getBestBefore() {
        return bestBefore;
    }

    public String getCategory() {
        return category;
    }
}

同时记得把addFood()方法里的实例化代码改成:

Food food = new Food(id,foodName, bestBefore, category);

另外还要检查Firebase数据库规则,确保允许写入操作,调试阶段可暂时设置为:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

(上线前一定要改成更安全的规则,比如仅允许认证用户读写)

最后建议你在Logcat里过滤AndroidRuntime标签,这样能看到更明确的崩溃报错信息,比如NoSuchMethodException(无参构造函数缺失)或IllegalAccessException(字段访问权限不足),能更快定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:41:32