android - 如何修复仅在我的手机上一直出现的空对象?
问题描述
我对 Android Studio 有疑问。我正在尝试做一个非常简单的应用程序,但在我的手机(Galaxy S8)上它总是给我同样的错误。我用两台电脑在家和学校做同样的事情。当我使用模拟器时,一切都很好。
解决方案
试试这个防御性编程代码。这应该可以避免 NPE 问题,但根本原因是:
您应该使用一些设计模式重构您的游戏代码(至少尝试 MVC)。您不应将 TextView 字符串值用于游戏逻辑决策。
某些 UI 树节点可能已在循环内更改。
public boolean checkEndOfGame(LinearLayout cartes, LinearLayout piles){
if(nbCartes == 0){
return true;
}
for (int i=0; i< piles.getChildCount(); i++){
LinearLayout sorte = (LinearLayout)piles.getChildAt(i);
for(int j=0; j< sorte.getChildCount(); j++){
View sorteChild = sorte.getChildAt(j);
if(sorteChild instanceof ConstraintLayout){
ConstraintLayout pile = (ConstraintLayout)sorteChild;
if(0 == pile.getChildCount) {
Log.e("TAG", "pile's child count = 0 ");
continue; //or break ?
}
View pileChild = pile.getChildAt(0);
if(pileChild instanceof TextView) {
TextView textePile = (TextView) pileChild;
int noPile = Integer.valueOf(textePile.getText());
for(int k=0; k< cartes.getChildCount(); k++){
View cartesChild = cartes.getChildAt(i);
if(cartesChild instanceof LinearLayout) {
LinearLayout rangee = (LinearLayout)cartesChild;
for(int l=0; l< rangee.getChildCount(); l++){
View carteChild = rangee.getChildAt(l);
if(carteChild instanceof ConstraintLayout) {
ConstraintLayout carte = (ConstraintLayout)carteChild;
View tv = carte.getChildAt(0);
if(tv instanceof TextView) {
TextView texteCarte = (TextView) tv;
int noCarte = Integer.valueOf(texteCarte.getText());
if(i>0){ //UP
if(noCarte>noPile){
return false;
}
}else{ //DOWN
if(noCarte<noPile){
return false;
}
}
}
}
}
}
}
}
}
}
}
return true;
}
推荐阅读
- r - 正则表达式编写您自己的 NGram 分词器
- python - Alembic:AttributeError:“RedshiftDDLCompiler”对象没有属性“访问子句”
- mysql - SQL OrderBy 子句不适用于最大别名
- reactjs - 如何在 MaterialUI 中从 Select 中更改 Menu 下拉元素?
- google-cloud-platform - GCP VPC 服务控制允许从 VM SSH 浏览器下载
- aws-api-gateway - API Gateway Lambda 代理和 Cognito
- r - 由于 CPL_write_ogr 错误,写入 sf 对象失败
- java - 重构在矩阵中给出最大路径和的路径
- vue.js - 我的道具数组没有设置我的数据数组值
- typescript - 如果单元格在制表网格中有颜色,则选择的颜色不可见。有没有办法让选择的颜色可见?