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

为什么每次运行安卓设备时Android Studio模拟器都会被终止?

你遇到的模拟器运行时应用终止问题核心是代码逻辑错误触发的APP崩溃,具体问题及修复方案如下:

1. 致命崩溃根源:secondActivity引用不存在的控件

你的activity_second.xml布局文件中没有定义id为button2的按钮控件,但secondActivity.java的onCreate方法中执行了b1 = (Button) findViewById(R.id.button2);,该方法返回null,后续调用setOnClickListener时触发空指针异常,直接导致APP崩溃退出,表象就是模拟器中应用被终止。

修复方案:

方案1:在activity_second.xml中添加对应id的按钮,示例代码如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="272dp"
    android:text="!!WELCOME!!"
    android:textSize="35dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

  <TextView
    android:id="@+id/textView4"
    android:layout_width="109dp"
    android:layout_height="34dp"
    android:layout_marginTop="28dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textview" />

<!-- 新增返回按钮 -->
<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="返回登录"
    android:layout_marginTop="20dp"
    app:layout_constraintTop_toBottomOf="@+id/textView4"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

 </androidx.constraintlayout.widget.ConstraintLayout>

方案2:删除secondActivity.java中所有和b1按钮相关的代码,避免空指针。

2. 非致命但易触发异常的问题:布局属性混用

你在ConstraintLayout的子控件中添加了layout_alignParentTop、layout_below等仅RelativeLayout生效的属性,虽然不会直接崩溃,但可能导致Android Studio布局渲染器异常,极端情况下会触发布局解析失败崩溃。

修复方案:

删除所有ConstraintLayout子控件下的非约束布局属性,仅保留app:layout_constraint开头的约束属性即可。

3. 其他优化建议

  • 将MainActivity和secondActivity的父类从Activity改为AppCompatActivity,获得更好的系统版本兼容性,减少底层崩溃概率
  • MainActivity中登录成功逻辑无需重复执行findViewById获取用户名输入框,直接使用已经初始化完成的ed1变量即可
  • 确认AndroidManifest.xml中已经完成secondActivity的注册,未注册的Activity跳转时也会直接触发崩溃
  • 建议给EXTRA_TEXT常量赋值固定值,比如public static String EXTRA_TEXT = "LOGIN_USERNAME";,提升代码规范性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 08:06:05