数据库调用后如何设置文本

时间:2016-07-27 19:36:34

标签: android firebase textview firebase-realtime-database

我不确定如何解决这个问题。我有一个TextView(包含在一个片段中),它需要保存来自firebase的数据(来自MainActivity中包含的监听器)。我没有长时间编程java,所以我想知道除了使textview静态之外我的选择是什么(因为这是不好的做法)?

以下是MainActivity的onCreate;

    private void getExtras(String uid) {
    mFirebaseRef.child("users").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                System.out.println(TAG + "TEST: " + user.getUsername());
                CURRENT_USER.setSex(user.getSex());
                CURRENT_USER.setEmail(user.getEmail());
                CURRENT_USER.setAge(user.getAge());
                CURRENT_USER.setUsername(user.getUsername());
                CURRENT_USER.setCreatedTime(user.getCreatedTime());
                Log.e(TAG, "Logged user is "+ CURRENT_USER.getId());
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

以下是我的片段onViewCreated:

    @Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    tvUserTitle = (TextView) getView().findViewById(R.id.tvUserTitle);
    tvUserTitle.setText(MainScreen.CURRENT_USER.getUsername());
}

如您所见,片段是在设置变量之前创建的,因此它显示为空(null)。

2 个答案:

答案 0 :(得分:3)

您需要从MainActivity中获取对Fragment的引用,然后调用一个设置TextView文本的方法。

MainActivity回调

CustomFragment customFragment =(CustomFragment)getSupportFragmentManager().findFragmentById(R.id.custom_frag_id);
customFragment.setTextView(firebaseText);

CustomFragment班级

public void setTextView(String text){
    myTextView.setText(text);
}

答案 1 :(得分:0)

After receiving the callback that the data has been inserted, get your current fragment from the fragment manager and call a method in the fragment where you can access the UI and change the UI.

YourFragment fragment =(YourFragment)getSupportFragmentManager().findFragmentById(R.id.fragment);
fragment.setTextView(text);

I usually like sending the whole object to the class so that we can use whatever we want whenever we need.

public void updateData(DataModel data) {
this.data = data;
refreshUI(); // reload the content.`enter code here`
}