全局变量在内部类中不是null,而在外部类中不是null

时间:2019-03-13 02:42:16

标签: android android-fragments android-lifecycle

我有一个名为“ myEmail”的全局变量,我想在一个方法中更改它的值 这样做时变量的值确实会改变,但仅在方法内部 (我已经使用日志检查了它),但是在更改值后再次尝试使用Variable时,它为null。

我不知道此问题的原因是什么。我尝试调用该方法 在onCreate上,因为我认为可能在更改值之前调用了变量,但是问题仍然相同。

这是我的代码

public class messagesFragment extends Fragment {
    private FirebaseFirestore db = FirebaseFirestore.getInstance();
    private String uid = FirebaseAuth.getInstance().getUid();
    private CollectionReference messageRef = db.collection("messages");
    private View v;
    private RecyclerView recyclerView;
    private messageAdapter mAdapter;
    private String myEmail;
    private FloatingActionButton addmsg;

    public messagesFragment() {
    }
    // Creating the fragment view.
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.messages_fragment, container, false);
        addmsg = (FloatingActionButton) v.findViewById(R.id.sendmsgfab);
        addmsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), createmessageActivity.class);
                startActivity(intent);
            }
        });

        getemail();       // Here the variable myEmail is null.
        setupRecycler();

        return v;
    }

    private void getemail(){
        DocumentReference documentReference = db.collection("users").document(uid);
        documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(final DocumentSnapshot documentSnapshot) {
                myEmail = documentSnapshot.get("email").toString();
              // Here the variable myEmail is not null.
            }
        });
        }

    private void setupRecycler() {
        Query query = messageRef.whereEqualTo("receiver", myEmail);
        FirestoreRecyclerOptions<message> options = new FirestoreRecyclerOptions.Builder<message>()
                .setQuery(query, message.class)
                .build();
        mAdapter = new messageAdapter(options);
        recyclerView = (RecyclerView) v.findViewById(R.id.messagesRecycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onStart() {
        super.onStart();
        mAdapter.startListening();
    }

    @Override
    public void onStop() {
        super.onStop();
        mAdapter.stopListening();
    }
}

2 个答案:

答案 0 :(得分:0)

原因是myEmail是在回调方法中分配的,该方法可以在调用setupRecycler()之后触发。因此,您需要在setupRecycler()的{​​{1}}内部进行检查

onSuccess

答案 1 :(得分:0)

getemail方法的返回值无效!请在您的方法上将String替换为void。