JAVA - 变量始终为null

时间:2017-01-27 12:14:18

标签: java android variables null

我已经创建了这个代码,如果文件存在与否,变量DEVICE将会改变。所以我创建了这段代码,但变量DEVICE始终为null

public class MainActivity extends AppCompatActivity{

    String DEVICE;

 @Override
    protected void onCreate(Bundle savedInstanceState) {

        apply = (Button) findViewById(R.id.apply);
        apply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    checktypezip(DEVICE);
                    while (DEVICE == null){
                        Log.v("Check","Check non completo");
                    }
            }
        });

    }

    public void checktypezip(String string){
        String percorso = Environment.getExternalStorageDirectory().getPath()+"/BAC/.unzipfile/";

        File normalzip = new File (percorso+"desc.txt");
        File flashzip = new File (percorso+"/system/media/bootanimation.zip");
        File samsung = new File (percorso+"/bootsamsung.qmg");
        File flashsamsung = new File (percorso+"/system/media/bootsamsung.qmg");
        String disp;

        disp=string;
        if (normalzip.exists()){
            disp = "Normal";
            string=disp;
        }
        else if (flashzip.exists()){
            disp = "Flashnormal";
            string=disp;
        }
        else if (samsung.exists()){
            disp = "Samsung";
            string=disp;
        }
        else if (flashsamsung.exists()){
            disp = "Samsungflash";
            string=disp;
        }
        else
        {
            disp = "Unknown";
            string=disp;
        }

    }

}

1 个答案:

答案 0 :(得分:5)

Java使用'按值传递'。这意味着DEVICE会传递给您的函数,而不是参考。虽然您要为参数string指定值,但永远不会将其分配给DEVICE

您必须从函数返回disp的值,并将其分配给DEVICE

像这样定义你的功能

public String checktypezip()

并像这样称呼它

DEVICE = checktypezip();

checktypezip结束时,您必须添加return disp

旁注:

while (DEVICE == null){
    Log.v("Check","Check non completo");
}

这将无限期地阻止主线程并在5秒后导致ANR。我建议将while替换为if