gpt4 book ai didi

java - 函数中重新赋值后全局变量赋值保持不变(Android Studio)

转载 作者:行者123 更新时间:2023-12-02 09:04:11 25 4
gpt4 key购买 nike

程序员,我对 android studio 和 java 非常陌生,在这种情况下,我尝试上传检索到的用户信息并将其存储在 firebase 数据库中。检索过程成功,登录后可以看到检索URL。但是,String pathToProfile没有分配URL,当我检查日志时,它是空的。提前致谢!

全局声明:

String pathToProfile;
Map<String, Object> UserInfo = new HashMap<>();

获取下载URL的函数

// retrieved URL should be saved in user document
private void retrieveProfileViaURL () {
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
pathToProfile = uri.toString();
UserInfo.put(PROFILE_URL, pathToProfile);
Log.d(TAG, "retrieve profile image successful" + pathToProfile);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Log.d(TAG, "retrieve profile image failure");
// pathToProfile = "uri download unsuccessful";
}
});
}

将用户信息上传到firebase的函数

private void uploadUserInfo(String user, String bioInfo) {
// CollectionReference users = db.collection("users");
String UID = getUserID();
retrieveProfileViaURL();

// UserInfo.put(USERID, UID);
UserInfo.put(USERNAME, user);
UserInfo.put(BIO, bioInfo);


mDocRef.collection("users").document(UID).set(UserInfo)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(USER_INFO, "Document has been saved");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(USER_INFO, "Document was not saved!", e);
}
});
}

最佳答案

Firebase 数据库中的所有数据都是异步读取的。您无法在调用之外获取值。这就是为什么您的 pathToProfile 显示 null。

为了更好的方法,你可以尝试这样的事情。

用户上传数据后,会自动允许用户通过url写入数据

private void retrieveProfileViaURL () {
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
pathToProfile = uri.toString();
String UID = getUserID();
UserInfo.put(USERNAME, user);
UserInfo.put(BIO, bioInfo);
UserInfo.put(PROFILE_URL, pathToProfile);
mDocRef.collection("users").document(UID).set(UserInfo)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(USER_INFO, "Document has been saved");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(USER_INFO, "Document was not saved!", e);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Log.d(TAG, "retrieve profile image failure");
// pathToProfile = "uri download unsuccessful";
}
});
}

关于java - 函数中重新赋值后全局变量赋值保持不变(Android Studio),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59960284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com