我编写了这段代码,其中变量 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;
}
}
}
最佳答案
Java 使用“按值传递”。这意味着 DEVICE
的 value 被传递给您的函数,而不是引用。尽管您正在为参数 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
关于JAVA - 变量始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41893780/