![](/img/trans.png)
[英]Java is printing out char array length as 0 even though I have assigned it a length
[英]Variable not assigned even though I assigned it (Android Java)
這是我的 java 代碼:
public void updateWalletString(){
User user = (User)Homeactivity.getUser()
wallet = user.getWallet()
String walletKey = getAWalletKey(wallet);
Log.v(TAG, walletKey);
}
private String getAWalletKey(Wallet w) {
String walletname = w.getName();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
final String[] WalletKey = new String[1];
databaseReference.child("Users").child(uid).child("wallets").orderByChild("name")
.equalTo(walletname).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
WalletKey[0] = childSnapshot.getKey();
Log.d(TAG, "getWalletkey: "+ WalletKey[0]);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(HomeActivity.this, "Error retrieving walletId from database", Toast.LENGTH_SHORT);
}
});
return WalletKey[0];
}
但是我的 logcat 打印了:
D/HomeActivity: getAWalletKey: Cash Wallet (此行來自 getAWalletKey() function )
V/HomeActivity:null (此行來自updateWalletString()函數)
我檢查了代碼,一切都正確。
當前有兩個不同的線程在您的代碼中執行。 第一個是您執行的主線程
String walletname = w.getName();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
final String[] WalletKey = new String[1];
return WalletKey[0];
以及從 firebase 獲取數據的異步線程。 當您返回 WalletKey[0] 時,該值仍然是null
,因為異步過程尚未完成。
我認為克服這個問題的最佳方法是更改getAWalletKey
function 以更改錢包。 像這樣。
public void updateWalletString(){
User user = (User)Homeactivity.getUser()
wallet = user.getWallet()
updateAWalletKey(wallet);
}
private void getAWalletKey(Wallet w) {
String walletname = w.getName();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
final String[] WalletKey = new String[1];
databaseReference.child("Users").child(uid).child("wallets").orderByChild("name")
.equalTo(walletname).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
WalletKey[0] = childSnapshot.getKey();
Log.v(TAG, walletKey);
Log.d(TAG, "getWalletkey: "+ WalletKey[0]);
doTheWallet(childSnapshot.getKey()); // whatever you want to do with the wallet.
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(HomeActivity.this, "Error retrieving walletId from database", Toast.LENGTH_SHORT);
}
});
return WalletKey[0];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.