gpt4 book ai didi

Android 应用程序在执行 if 语句时崩溃?

转载 作者:行者123 更新时间:2023-12-02 06:34:26 25 4
gpt4 key购买 nike

我不知道为什么我的 Android 应用程序崩溃了。我注意到当我放入简单的firstTime变量时发生了这种情况,但老实说我不知道​​为什么firstTime变量会让整个应用程序崩溃。如果我去掉 if 语句,其他所有部分都会起作用。这是我到目前为止所输入的内容:

public class MainActivity extends Activity {

static int firstTime = 0;
BroadcastReceiver receiver = null;
@Override
protected void onCreate(Bundle savedInstanceState) {

if(firstTime == 0){
logTime(false);
firstTime++;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
if(arg1.getAction().equals(Intent.ACTION_SCREEN_OFF)){
logTime(true);
}
else if(arg1.getAction().equals(Intent.ACTION_SCREEN_ON)){
logTime(false);
}
}
};
registerReceiver(receiver, filter);

}

有人可能知道为什么firstTime变量会使我的应用程序崩溃吗?谢谢!

最佳答案

我之前没有想到这一点,我以为你只是想增加int,所以我没有考虑再次调用logTime(),并且不明白这么简单的概念怎么会崩溃。

您的问题可能是顺序,因为使用您当前的代码,方法中的textView将为null并且会抛出NPE访问时。

这是因为 logTime() 中的 findViewById() 将返回 null (未设置内容 View - 因此没有没有找到任何东西):

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(firstTime == 0){
logTime(false);
firstTime++;
}

关于Android 应用程序在执行 if 语句时崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15048298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com