简体   繁体   中英

Android: private variable scope in a class

Requirement: I want passWord to be accessible everywhere in the class.

This is the code:

public class DetailComm extends AppCompatActivity {

    private String passWord;
    private Bundle bundle;
    private Button mSendButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bundle = getIntent().getExtras();
        mSendButton = (Button) findViewById(R.id.sendButton);

        final Query query = mFirebaseDatabaseReference.child(<mylink>).orderByKey().equalTo(<myname>);
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot)
            {

                for (final DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    passWord = snapshot.getValue().toString();
                    //Point 1. Toast prints correct value of passWord here//
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError)
            {

            }
        });
        if (bundle != null) {
            for (String key : bundle.keySet()) {
                Toast.makeText(DetailComm.this, passWord.toString(), Toast.LENGTH_SHORT).show();
                //Point 2. Toast prints blank output here//
            }
        }

        mSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Point 3. Toast displays correct value of passWord here!!
            }
        }
    }
}

The question is: how can the same variable be inaccessible at Point 2 here? If at point 1 when I set passWord, it is in a different class, it might explain point 2 having null string, but then, should it also not be inaccessible at point3? What am I missing?

How can I make passWord accessible everywhere in the class? I changed it to a public variable, Point 2 still displays null value. Also, this class is one of the many classes in the project. I know for sure there is no other class with this variable name.

You set value in the Listener anonymous class which means that variable initialize only when event is happenned, in your case, when data change in FireBase db or when the first-time response was delivered. But point 2 happens exactly after you set the Listener, so it happens BEFORE point 1. That's why you give the null value. And, in addition, point 3 also happens in lustener, so it very unclear which of points will be called first - point 1 or point 3.

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