1

I've made this code where the variable DEVICE will change if a file exist or not. So i have made this code but the variable DEVICE is always 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;
        }

    }

}
  • that's because you never giva a value to is. – Robin Dijkhof Jan 27 '17 at 12:16
  • 1
    You are not updating `DEVICE` in the `checktypezip` methods because `string` is not a pointer. `string = "foo"` will not update `DEVICE`. PS : this is a nice infinite loop ;) – AxelH Jan 27 '17 at 12:16
  • 1
    Add return type to checktypezip or remove param from it and access member variable directly. – Anurag Singh Jan 27 '17 at 12:18
  • Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – AxelH Jan 27 '17 at 12:18

1 Answers1

5

Java uses 'pass by value'. This means that the value of DEVICE is passed to your function, not the reference. Although you are assigning a value to the parameter string, it will never be assigned to DEVICE.

You must return the value of disp from your function and assign it to 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

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. I would suggest replacing while with if

0xDEADC0DE
  • 2,453
  • 1
  • 17
  • 22