简体   繁体   中英

Why the static variable doesn't work in other class?

I encountered a problem during do android project... I declared six variable in "A.java" as below.

public static int a = -1;
public static int b = -1;
public static int c = -1;
public static int d = -1;
public static int e = -1;
public static int f = -1;

I set that if readMessage equaled to s1..., then a = 0. And go on. readMessage, s1, s2, s3, s4, s5 and s6 are strings.

 if(readMessage.equals(s1)){
                   a=1;
                }
                else if(readMessage.equals(s2)){
                   b=1;
                }
                else if(readMessage.equals(s3) ){
                   c=1;
                }
                else if(readMessage.equals(s4)){

                   d=1;
                }
                else if(readMessage.equals(s5)){

                   e=1;
                }
                else if(readMessage.equals(s6)){
                   f=1;
                }

Now in MainActivity.java, I write codes as below. But it doesn't work! The images don't change.

ImgPhoto = (ImageView)findViewById(R.id.logoImageView);

if((A.a) == 1){ImgPhoto.setImageResource(imgId[0]);}
    else if((A.b) == 1){ImgPhoto.setImageResource(imgId[1]);}
    else if((A.c) == 1){ImgPhoto.setImageResource(imgId[2]);}
    else if((A.d) == 1){ImgPhoto.setImageResource(imgId[3]);}
    else if((A.e) == 1){ImgPhoto.setImageResource(imgId[4]);}
    else if((A.f) == 1){ImgPhoto.setImageResource(imgId[5]);}

Can anyone help me? I searched on internet but I did't find any solution.... I will appreciate for your helps!

The primitive data type INT 's default value is 0.

You can see the doc here

So all of your fields AF's value if 0.

from oracle

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

so all static variables in A.java will set to zero or null by jvm and the first if statement will always be true

the best Solution is to set them to unused value for example -1

public static int a=-1;
public static int b=-1;
public static int c=-1;
public static int d=-1;
public static int e=-1;
public static int f=-1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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