java从外部得到数据_java – 如何实现Observer以从侦听器获取数据?

 2023-09-09 阅读 25 评论 0

摘要:我正在使用MaterialDrawer库为我的应用程序创建一个简单的抽屉,库中的一些类实例需要在调用时传递给它们的字符串.一个例子是IProfile类:java和大数据哪个好,IProfile profile = new ProfileDrawerItem().withName(“John Doe”);其中withName()方法接受一个字符串

我正在使用

MaterialDrawer库为我的应用程序创建一个简单的抽屉,库中的一些类实例需要在调用时传递给它们的字符串.一个例子是IProfile类:

java和大数据哪个好,IProfile profile = new ProfileDrawerItem().withName(“John Doe”);

其中withName()方法接受一个字符串.

我创建了一个类MyObservable.java(扩展Observable)类,我打算用它来获取要在我的MainActivity中使用的数据,该实现了MaterialDrawer库.在这个类中,我有一个方法implementData(),它有我的firebase数据库所需的监听器.

java数据权限怎么做?这就是它的样子:

public class MyObservable extends Observable {

// Attach our firebase reference...

java向数据库写入数据、Firebase userRef = new Firebase("https://myApp.firebaseio.com/users");

AuthData authData;

public String username = "";

大数据技术java?public String email = "";

public void changeUsername(String username) {

this.username = username;

setChanged();

notifyObservers(username);

}

public void implementData(){

// Get the authentication data of our user from the reference.

authData = userRef.getAuth();

// This is the listener I have to get the data from.

userRef.child(authData.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {

@Override

public void onDataChange(DataSnapshot snapshot) {

UserSchema user = snapshot.getValue(UserSchema.class);

// This guy needs to be used in the MainActivity appDrawer() method

String userName = user.getName();

}

@Override

public void onCancelled(FirebaseError firebaseError) {

}

});

}

}

class MyObserver implements Observer {

public void update(Observable observable, Object data) {

// For now I just print it out to System.out

System.out.println("Username:" + data);

}

}

然后我通过changeUsername()方法通知我的观察者用户名更改:

public void changeUsername(String username) {

this.username = username;

setChanged();

notifyObservers(username);

}

在MyObservable类中,我有一个MyObserver类,它实现Observer,并在更新观察者时调用update()方法.在now()方法中,我只打印出用户的用户名以确保实际发生了什么.

这是我需要来自观察者的数据(在MainActivity中):

public class MainActivity extends AppCompatActivity {

...

public void appDrawer(){

IProfile profile = new ProfileDrawerItem()

// I need the user's data here

.withName("Test")

.withEmail("test@test.com")

.withIcon(R.drawable.avatar2);

}

...

}

我花了几个小时试图通过尝试检索要在我的MainActivity中使用的数据来对发生在侦听器中的事件做出“反应”,但我不确定我是否正确使用了Observable / Observer模式,因为这是一个异步Firebase获取数据的事件,使用Observer是最好的方法.

appDrawer()方法在我的Activity的onCreate()中调用.

如何使用Observer从Listener中检索数据,以便在其他地方使用它?

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/26059.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息