首页 > 解决方案 > 如何修复仅在我的手机上一直出现的空对象?

问题描述

我对 Android Studio 有疑问。我正在尝试做一个非常简单的应用程序,但在我的手机(Galaxy S8)上它总是给我同样的错误。我用两台电脑在家和学校做同样的事情。当我使用模拟器时,一切都很好。

标签: android

解决方案


试试这个防御性编程代码。这应该可以避免 NPE 问题,但根本原因是:

  1. 您应该使用一些设计模式重构您的游戏代码(至少尝试 MVC)。您不应将 TextView 字符串值用于游戏逻辑决策。

  2. 某些 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;
    }

推荐阅读