简体   繁体   English

JAVA-变量始终为null

[英]JAVA - Variable is always null

I've made this code where the variable DEVICE will change if a file exist or not. 我已经编写了此代码,其中如果文件存在或不存在,变量DEVICE都会更改。 So i have made this code but the variable DEVICE is always null 因此,我编写了此代码,但变量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;
        }

    }

}

Java uses 'pass by value'. Java使用“按值传递”。 This means that the value of DEVICE is passed to your function, not the reference. 这意味着DEVICE将传递给您的函数,而不是引用。 Although you are assigning a value to the parameter string , it will never be assigned to DEVICE . 尽管您正在为参数string分配一个值,但永远不会将其分配给DEVICE

You must return the value of disp from your function and assign it to DEVICE 您必须从函数中返回disp的值并将其分配给DEVICE

Define your function like this 这样定义你的功能

public String checktypezip()

and call it like this 并这样称呼它

DEVICE = checktypezip();

At the end of checktypezip , you must add return disp checktypezip的末尾,您必须添加return disp

On a side note: 附带说明:

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

This will block your main thread indefinitely and cause an ANR after 5 seconds. 这将无限期阻塞您的主线程,并在5秒钟后导致ANR。 I would suggest replacing while with if 我会建议更换whileif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM